Merge branch 'dev' into feat/ranking

This commit is contained in:
Steven Tischer
2026-07-17 20:03:28 +02:00
118 changed files with 51930 additions and 2631 deletions
-2
View File
@@ -54,7 +54,6 @@ from inse.patents.service import (
router as patents_service_router,
)
from inse.works.purpose_router import router as works_purpose_router
from inse.works.v2.router import router as works_v2_router
logger = logging.getLogger(__name__)
@@ -87,7 +86,6 @@ app.include_router(institution_patents_router)
app.include_router(org_patents_router)
app.include_router(institutions_router)
app.include_router(topics_service_router)
app.include_router(works_purpose_router)
app.include_router(works_service_router)
app.include_router(persons_service_router)
app.include_router(funders_service_router)
@@ -32,17 +32,19 @@ def is_ambiguous_name(
openalex_full_name_count: int | None = None,
openalex_last_name_count: int | None = None,
) -> bool:
"""Decide whether a name is ambiguous using only internal project data.
"""Decide whether a name is strictly ambiguous using internal project data.
A name is treated as ambiguous (and therefore handled strictly) when:
A name is treated as strictly ambiguous when:
- it is a mononym / cannot be parsed into given + family name, or
- several authors in the local OpenAlex index share the exact name, or
- many authors in the local OpenAlex index share the family name, or
- the patent name search returns a very large number of hits.
- several authors in the local OpenAlex index share the exact full name.
Ambiguous names need a strong identity signal (institution/assignee or a
full given-name match with a matching research field) before a patent is
attributed to the person.
A frequent last name alone does **not** make a uniquely named author
strictly ambiguous (``openalex_full_name_count == 1``). In that case
personal-assignee identity can count when inventor and assignee both
match the full OpenAlex name.
When the full-name count is unknown, last-name frequency and patent-hit
volume remain as safety fallbacks.
"""
parsed = parse_person_name(display_name)
if parsed is None or parsed.is_single_token:
@@ -54,6 +56,9 @@ def is_ambiguous_name(
):
return True
if openalex_full_name_count == 1:
return False
if (
openalex_last_name_count is not None
and openalex_last_name_count >= OPENALEX_LAST_NAME_COUNT_THRESHOLD
@@ -105,6 +110,29 @@ def patent_institution_match(
return False
def patent_personal_assignee_full_match(
patent: model.PatentEntry,
display_name: str,
) -> bool:
"""True when a personal assignee matches the author's full given name."""
if not display_name or not display_name.strip():
return False
for assignee in patent.assignees:
if assignee and first_name_match_kind_for_person(assignee, display_name) == "full":
return True
return False
def patent_full_personal_identity_match(
patent: model.PatentEntry,
display_name: str,
) -> bool:
"""Strong personal identity: full inventor name and full personal assignee."""
if best_name_match_kind(patent, display_name) != "full":
return False
return patent_personal_assignee_full_match(patent, display_name)
def patent_personal_assignee_match(
patent: model.PatentEntry,
display_name: str,
@@ -271,29 +271,31 @@ def _given_name_matches(author: ParsedPersonName, inventor: ParsedPersonName) ->
if not inventor.given_names:
return False
# 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". 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
):
return True
author_full = [g for g in author.given_names if _initial_letter(g) is None]
inventor_full = [g for g in inventor.given_names if _initial_letter(g) is None]
inventor_tokens_full = [
token for token in inventor.given_names
if _initial_letter(token) is None
]
# Accept when one side's full (spelled-out) given names are entirely
# covered by the other's — e.g. "Maria Schmidt" vs "Anna Maria Schmidt"
# (shortened form). A single shared given-name token is not enough by
# itself when both sides also carry other, non-matching full given
# names: that pattern matches different people who happen to share one
# common given-name component rather than the same person (e.g. "Kim,
# Young Gil" vs "Moon Young Kim" both contain "Young", but "Gil" and
# "Moon" don't match — these are two different people, not the same
# person under a shortened name).
if author_full and inventor_full:
smaller, larger = (
(author_full, inventor_full)
if len(author_full) <= len(inventor_full)
else (inventor_full, author_full)
)
if all(
any(tokens_equal(token, other, allow_initial=False) for other in larger)
for token in smaller
):
return True
inventor_tokens_full = inventor_full
# Prevent false positives like "Karem C Weber" for "Christian Weber":
# if inventor has full given-name tokens but none matches the author,
@@ -30,7 +30,7 @@ def test_full_name_collision_makes_name_ambiguous() -> None:
)
def test_last_name_collision_makes_name_ambiguous() -> None:
def test_last_name_collision_makes_name_ambiguous_without_full_name_count() -> None:
assert (
is_ambiguous_name(
"Christian Weber",
@@ -43,7 +43,27 @@ def test_last_name_collision_makes_name_ambiguous() -> None:
)
def test_many_patent_hits_make_name_ambiguous() -> None:
def test_last_name_collision_not_ambiguous_when_full_name_unique() -> None:
assert (
is_ambiguous_name(
"Pedro José Marrón",
openalex_full_name_count=1,
openalex_last_name_count=OPENALEX_LAST_NAME_COUNT_THRESHOLD,
patent_hit_count=PATENT_HIT_COUNT_THRESHOLD,
)
is False
)
def test_many_patent_hits_not_ambiguous_when_full_name_unique() -> None:
assert (
is_ambiguous_name(
"Pedro José Marrón",
openalex_full_name_count=1,
patent_hit_count=PATENT_HIT_COUNT_THRESHOLD,
)
is False
)
assert (
is_ambiguous_name("Christian Weber", patent_hit_count=PATENT_HIT_COUNT_THRESHOLD)
is True
@@ -11,8 +11,13 @@ from inse.patents.authors.ipc_openalex_mapping import (
patent_topics_match_author,
resolve_mapped_topics_for_code,
)
from inse.patents.authors.identity import (
patent_full_personal_identity_match,
patent_personal_assignee_full_match,
)
from inse.patents.authors.topic_filter import filter_patents_by_ipc_topic_mapping
from inse.patents.common import model
from inse.patents.common.parsing import patent_map_key
def _author_with_topic(
@@ -172,19 +177,12 @@ def test_filter_rejects_ambiguous_name_on_fuzzy_label_only_match() -> None:
[tire_patent],
author,
is_ambiguous=True,
patent_topic_map={"USPTO:US12508845": [spurious_cardiac]},
patent_topic_map={patent_map_key(tire_patent): [spurious_cardiac]},
)
assert filtered == []
def test_filter_keeps_ambiguous_name_on_legacy_ipc_subclass_match() -> None:
custom = _custom_mapping()
custom["subclass"]["C07K"] = mapping_module.MappedOpenAlexTopic(
topic_id="https://openalex.org/T10158",
topic_display_name="Cancer Immunotherapy and Biomarkers",
ipc_level="subclass",
ipc_symbol="C07K",
)
def test_filter_keeps_ambiguous_name_on_keywords_index_topic_match() -> None:
author = _author_with_topic(
"https://openalex.org/T10158",
"Cancer Immunotherapy and Biomarkers",
@@ -199,21 +197,124 @@ def test_filter_keeps_ambiguous_name_on_legacy_ipc_subclass_match() -> None:
ipc=["C07K 14/705"],
inventors=["Schadendorf, Dirk"],
)
spurious = mapping_module.MappedOpenAlexTopic(
topic_id="https://openalex.org/T99999",
topic_display_name="Antimicrobial Peptides and Activities",
index_mapped = mapping_module.MappedOpenAlexTopic(
topic_id="https://openalex.org/T10158",
topic_display_name="Cancer Immunotherapy and Biomarkers",
subfield_id="https://openalex.org/subfields/2705",
field_id="https://openalex.org/fields/27",
field_name="Medicine",
)
filtered = filter_patents_by_ipc_topic_mapping(
[patent],
author,
is_ambiguous=True,
mapping=custom,
patent_topic_map={"EPO:EP1555271": [spurious]},
patent_topic_map={patent_map_key(patent): [index_mapped]},
)
assert len(filtered) == 1
def test_filter_rejects_ambiguous_personal_assignee_without_keywords_match() -> None:
author = _author_with_topic(
"https://openalex.org/T12345",
"Millimeter-Wave Propagation and Modeling",
subfield_id="https://openalex.org/subfields/2208",
field_id="https://openalex.org/fields/22",
domain_id="https://openalex.org/domains/3",
)
grill_patent = model.PatentEntry(
patent_id="EP999",
source="EPO",
title="FIRE BASIN",
ipc=["A47J 37/07"],
assignees=["Kaiser, Thomas"],
inventors=["Kaiser, Thomas"],
)
unrelated = mapping_module.MappedOpenAlexTopic(
topic_id="https://openalex.org/T88888",
topic_display_name="Food Science and Culinary Arts",
subfield_id="https://openalex.org/subfields/1106",
field_id="https://openalex.org/fields/11",
field_name="Agricultural and Biological Sciences",
)
filtered = filter_patents_by_ipc_topic_mapping(
[grill_patent],
author,
is_ambiguous=True,
patent_topic_map={patent_map_key(grill_patent): [unrelated]},
)
assert filtered == []
def test_filter_keeps_unique_name_on_full_personal_identity_without_topic_match() -> None:
author = _author_with_topic(
"https://openalex.org/T12345",
"Energy Efficient Wireless Sensor Networks",
subfield_id="https://openalex.org/subfields/1706",
field_id="https://openalex.org/fields/17",
domain_id="https://openalex.org/domains/3",
)
author.display_name = "Pedro José Marrón"
patent = model.PatentEntry(
patent_id="EP1542159",
source="EPO",
title="Card and reader/writer apparatus for cards",
ipc=["G06K 19/077"],
assignees=["Marron, Pedro José, Dr."],
inventors=["Marron, Pedro José"],
)
unrelated = mapping_module.MappedOpenAlexTopic(
topic_id="https://openalex.org/T88888",
topic_display_name="Advanced Image Processing Techniques",
subfield_id="https://openalex.org/subfields/1704",
field_id="https://openalex.org/fields/17",
field_name="Computer Science",
)
assert patent_full_personal_identity_match(patent, author.display_name) is True
filtered = filter_patents_by_ipc_topic_mapping(
[patent],
author,
is_ambiguous=False,
patent_topic_map={patent_map_key(patent): [unrelated]},
)
assert len(filtered) == 1
assert filtered[0].personal_assignee_match is True
def test_filter_rejects_initial_only_personal_assignee_without_topic_match() -> None:
author = _author_with_topic(
"https://openalex.org/T12345",
"Energy Efficient Wireless Sensor Networks",
subfield_id="https://openalex.org/subfields/1706",
field_id="https://openalex.org/fields/17",
domain_id="https://openalex.org/domains/3",
)
author.display_name = "Pedro José Marrón"
patent = model.PatentEntry(
patent_id="EP999",
source="EPO",
title="Card reader",
ipc=["G06K 19/077"],
assignees=["Marron, P. J."],
inventors=["Marron, P. J."],
)
unrelated = mapping_module.MappedOpenAlexTopic(
topic_id="https://openalex.org/T88888",
topic_display_name="Advanced Image Processing Techniques",
subfield_id="https://openalex.org/subfields/1704",
field_id="https://openalex.org/fields/17",
field_name="Computer Science",
)
assert patent_personal_assignee_full_match(patent, author.display_name) is False
assert patent_full_personal_identity_match(patent, author.display_name) is False
filtered = filter_patents_by_ipc_topic_mapping(
[patent],
author,
is_ambiguous=False,
patent_topic_map={patent_map_key(patent): [unrelated]},
)
assert filtered == []
def test_custom_mapping_table() -> None:
custom = _custom_mapping()
author = Author(
@@ -1,10 +1,11 @@
"""Filter name-matched patents using precomputed IPC/CPC → OpenAlex topic mappings."""
"""Filter name-matched patents using IPC/CPC → OpenAlex topic mappings."""
from __future__ import annotations
from dataclasses import dataclass
from inse.models.openalex.author import Author
from inse.patents.authors.identity import (
patent_full_personal_identity_match,
patent_institution_match,
patent_personal_assignee_match,
)
@@ -14,6 +15,7 @@ from inse.patents.authors.ipc_openalex_mapping import (
load_ipc_openalex_mapping,
mapped_topics_match_author,
mapped_topics_match_author_for_ambiguous,
mapped_topics_match_author_strict,
patent_topics_match_author,
resolve_mapped_topics_for_patent,
)
@@ -70,7 +72,15 @@ def filter_patents_by_ipc_topic_mapping(
mapping=None,
patent_topic_map: dict[str, list[MappedOpenAlexTopic]] | None = None,
) -> list[TopicFilterResult]:
"""Filter patents by comparing IPC/CPC codes with the author's OpenAlex topics.
When ``patent_topic_map`` is provided (from the ``patents_openalex_keywords``
index via :class:`PatentOpenAlexMappingResolver`), that mapping is the primary
signal: patents must share a topic or subfield with the author, unless the
assignee matches one of the author's institutions.
"""
table = mapping if mapping is not None else load_ipc_openalex_mapping()
using_keywords_index = patent_topic_map is not None
institution_names = [
name
for institution in author.last_known_institutions or []
@@ -87,17 +97,31 @@ def filter_patents_by_ipc_topic_mapping(
for patent in patents:
institution_match = patent_institution_match(patent, institution_names)
personal_assignee_match = patent_personal_assignee_match(patent, display_name)
strong_identity = institution_match or personal_assignee_match
if using_keywords_index:
if is_ambiguous:
strong_identity = institution_match
else:
strong_identity = institution_match or patent_full_personal_identity_match(
patent,
display_name,
)
else:
strong_identity = institution_match or personal_assignee_match
mapped_topics = _resolve_patent_topics(patent, table, patent_topic_map)
if is_ambiguous:
if using_keywords_index:
matched_via_mapping = mapped_topics_match_author_strict(
mapped_topics,
author,
)
elif is_ambiguous:
matched_via_mapping = mapped_topics_match_author_for_ambiguous(
patent,
author,
mapped_topics,
table,
)
elif patent_topic_map is not None:
matched_via_mapping = mapped_topics_match_author(mapped_topics, author)
else:
matched_via_mapping = patent_topics_match_author(patent, author, table)
@@ -113,17 +137,22 @@ def filter_patents_by_ipc_topic_mapping(
)
continue
if is_ambiguous:
if matched_via_mapping:
filtered.append(
TopicFilterResult(
patent=patent,
decision="keep",
matched_via_mapping=True,
institution_match=False,
personal_assignee_match=False,
)
if matched_via_mapping:
filtered.append(
TopicFilterResult(
patent=patent,
decision="keep",
matched_via_mapping=True,
institution_match=False,
personal_assignee_match=False,
)
)
continue
if using_keywords_index:
continue
if is_ambiguous:
continue
if _topic_conflict(mapped_topics, author):
@@ -50,6 +50,7 @@ _MAX_SEARCH_KEYWORDS = 10
_MIN_KEYWORD_RELEVANCE = 0.0
_MIN_IPC_MATCH_SCORE = 0.65
_MIN_PATENT_MATCH_SCORE = 0.50
_DEFAULT_SCORE_WEIGHTS = {"ipc": 0.60, "topic": 0.25, "text": 0.15}
_SEARCHABLE_IPC_LEVELS = frozenset({"subgroup", "group", "subclass"})
# Soft field overlap for natural-science / engineering patent domains.
_SOFT_MATCH_FIELD_NAMES = frozenset(
@@ -492,15 +493,32 @@ def _patent_passes_relevance_gate(
return has_topic_match or text_score > 0.0
def _normalize_score_weights(
weights: dict[str, float] | None = None,
) -> dict[str, float]:
raw = {
"ipc": float((weights or {}).get("ipc", _DEFAULT_SCORE_WEIGHTS["ipc"])),
"topic": float((weights or {}).get("topic", _DEFAULT_SCORE_WEIGHTS["topic"])),
"text": float((weights or {}).get("text", _DEFAULT_SCORE_WEIGHTS["text"])),
}
total = sum(raw.values())
if total <= 0:
return dict(_DEFAULT_SCORE_WEIGHTS)
return {key: value / total for key, value in raw.items()}
def _compute_final_score(
ipc_score: float,
topic_score: float,
text_score: float,
*,
weights: dict[str, float] | None = None,
) -> float:
normalized = _normalize_score_weights(weights)
return round(
0.60 * ipc_score
+ 0.25 * topic_score
+ 0.15 * text_score,
normalized["ipc"] * ipc_score
+ normalized["topic"] * topic_score
+ normalized["text"] * text_score,
4,
)
@@ -753,6 +771,9 @@ async def get_patents_by_keywords(
KeywordPatentMatch(
patent=patent,
match_score=score,
ipc_score=ipc_score,
topic_score=topic_score,
text_score=text_score,
matched_keywords=matched_keywords,
matched_ipc_symbols=matched_symbols,
)
@@ -45,6 +45,9 @@ class PatentsByKeywordsRequest(BaseModel):
class KeywordPatentMatch(BaseModel):
patent: PatentEntry
match_score: float = Field(description="Combined match quality score.")
ipc_score: float = Field(description="IPC/CPC classification match score.")
topic_score: float = Field(description="OpenAlex topic overlap score (0 or 1).")
text_score: float = Field(description="Title/abstract keyword overlap score.")
matched_keywords: list[str] = Field(default_factory=list)
matched_ipc_symbols: list[str] = Field(default_factory=list)
@@ -417,6 +417,12 @@ def test_compute_final_score_weights_ipc_topic_and_text() -> None:
4,
)
assert _compute_final_score(0.6742, 0.0, 0.0) == round(0.60 * 0.6742, 4)
assert _compute_final_score(
0.8,
1.0,
0.5,
weights={"ipc": 0.2, "topic": 0.2, "text": 0.6},
) == round(0.2 * 0.8 + 0.2 * 1.0 + 0.6 * 0.5, 4)
def test_score_patent_rejects_subclass_only_without_topic_or_text() -> None:
+107 -32
View File
@@ -13,10 +13,9 @@ from inse.institutions.institutions_search_client import InstitutionsSearchClien
from inse.models.openalex.author import Author
from inse.patents.authors.identity import (
author_institution_names,
is_ambiguous_name,
patent_institution_match,
patent_personal_assignee_match,
)
from inse.patents.authors.ipc_openalex_mapping import normalize_openalex_id
from inse.patents.authors.name_matching import filter_patents_by_author_name
from inse.patents.common.elastic_search_client import MissingApiKeyError
from inse.patents.common.model import PatentEntry
@@ -27,10 +26,12 @@ from inse.patents.common.parsing import (
parse_epo_hits,
parse_uspto_hits,
patent_dedup_key,
patent_map_key,
)
from inse.patents.institutions.logic import get_patents_by_institution_id
from inse.patents.ipc_search_client import IpcSearchClient
from inse.patents.patents_openalex_keywords.client import PatentsOpenAlexKeywordsClient
from inse.patents.patents_openalex_keywords.resolver import PatentOpenAlexMappingResolver
from inse.patents.org.elastic_search_client import (
OrgPatentsSearchClient,
fetch_authors_by_institution_name,
@@ -218,11 +219,72 @@ def org_patent_to_es_document(patent: OrgPatentEntry) -> dict:
}
MIN_CORROBORATING_TOPIC_OVERLAP = 2
def primary_classification_codes(patent: PatentEntry) -> list[str]:
"""Returns only the patent's primary IPC/CPC code(s) (marked "AFI" in the
raw EPO/USPTO string), falling back to all codes if none are marked.
Patents can carry dozens of secondary/incidental classification codes
(marked "ALI") alongside their real subject. Resolving OpenAlex topics
from *all* of them gives some patents a huge, unfocused topic cloud —
confirmed against a real org_patents rebuild, where a 20-code patent
picked up 70+ unrelated topics, making a coincidental two-topic overlap
with an unrelated same-named author far more likely than intended.
"""
all_codes = [*patent.ipc, *patent.cpc]
primary = [code for code in all_codes if "AFI" in code]
return primary or all_codes
def topic_corroborated_patents(
patents: list[PatentEntry],
author: Author,
patent_topic_map: dict[str, list],
) -> list[PatentEntry]:
"""Keeps only patents whose IPC/CPC-derived OpenAlex topics share at
least MIN_CORROBORATING_TOPIC_OVERLAP exact topic IDs with the author's
own research topics — used to disambiguate common inventor names where
institution/self-assignee matching alone isn't enough.
Requiring a single shared topic ID was still too loose: broad,
genuinely common topics (e.g. "Image Processing Techniques") show up on
many unrelated patents *and* on many unrelated researchers' profiles, so
one coincidental overlap doesn't mean much (confirmed against a real
org_patents rebuild: match_type=name patents still ballooned to ~2000).
Two independent topic overlaps happening by chance is far less likely,
while a patent genuinely invented by the author would typically share
more than one topic with their own body of work. If the author has no
topic profile at all, there is nothing to corroborate against.
"""
author_topic_ids = {
normalize_openalex_id(topic.id)
for topic in (author.topics or [])
if topic.id
}
author_topic_ids.discard(None)
if not author_topic_ids:
return []
kept: list[PatentEntry] = []
for patent in patents:
mapped_topics = patent_topic_map.get(patent_map_key(patent), [])
patent_topic_ids = {
normalize_openalex_id(topic.topic_id)
for topic in mapped_topics
if topic.topic_id
}
patent_topic_ids.discard(None)
if len(patent_topic_ids & author_topic_ids) >= MIN_CORROBORATING_TOPIC_OVERLAP:
kept.append(patent)
return kept
async def _search_patents_by_author(
author: Author,
institution_name: str | None,
search_client: PatentSearchClient,
ipc_client: IpcSearchClient,
) -> list[PatentEntry]:
author_name = author.display_name
if not author_name:
@@ -248,40 +310,53 @@ async def _search_patents_by_author(
patents = parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data)
patents = deduplicate_patents(patents)
patent_hit_count = len(patents)
name_matched = filter_patents_by_author_name(patents, author_name)
if not name_matched:
return []
from inse.persons import logic as person_logic
from inse.patents.authors.name_variants import parse_person_name
# Applied to every name-based hit, not gated behind an ambiguity check:
# the institution itself being the assignee is the only unambiguous
# case — accepted outright. Everything else matched on name alone,
# including a personal-assignee match (several different same-named
# people could each be listed as their own patent's assignee) or a
# third-party assignee (e.g. an industry partner on a co-invented
# patent — the normal case for academic patents, not a red flag by
# itself), only counts if the patent's IPC/CPC-derived OpenAlex topics
# also overlap with the author's own research topics. This
# intentionally does not rely on is_ambiguous_name: a name can look
# unique in our local OpenAlex slice while still being common globally
# in EPO/USPTO, so a bare name-on-inventor match alone is never a
# strong enough signal on its own.
inst_names = [institution_name] if institution_name else []
strong_identity_matched = [
p for p in name_matched
if patent_institution_match(p, inst_names)
]
matched_keys = {patent_dedup_key(p) for p in strong_identity_matched}
remaining = [p for p in name_matched if patent_dedup_key(p) not in matched_keys]
if not remaining:
return strong_identity_matched
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,
)
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)
topic_matched: list[PatentEntry] = []
try:
resolver = PatentOpenAlexMappingResolver()
primary_only = [
patent.model_copy(update={
"ipc": primary_classification_codes(patent),
"cpc": [],
})
for patent in remaining
]
else:
return name_matched
patent_topic_map = await resolver.resolve_topics_for_patents(primary_only)
topic_matched = topic_corroborated_patents(remaining, author, patent_topic_map)
except Exception:
logger.warning(
"OpenAlex topic corroboration failed for author %s",
author_name,
exc_info=True,
)
return strong_identity_matched + topic_matched
async def build_org_patents_for_institution(
@@ -320,7 +395,7 @@ 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, institution_name, patent_client, ipc_search_client
author, institution_name, patent_client
)
return author, patents
+111 -1
View File
@@ -1,11 +1,16 @@
from inse.models.openalex.author import Author
from inse.models.openalex.work_topic import WorkTopic
from inse.patents.authors.ipc_openalex_mapping import MappedOpenAlexTopic
from inse.patents.common.model import PatentEntry
from inse.patents.common.parsing import patent_map_key
from inse.patents.org.logic import (
merge_org_patents,
org_patent_document_id,
primary_classification_codes,
resolve_match_type,
topic_corroborated_patents,
)
from inse.patents.org.model import MatchedAuthor
from inse.models.openalex.author import Author
def _patent(
@@ -102,3 +107,108 @@ def test_org_patent_document_id_is_stable() -> None:
doc_id = org_patent_document_id("I62318514", patent)
assert doc_id == "I62318514_EPO_EP1234567_20240101_A1"
def _author_with_topics(author_id: str, name: str, topic_ids: list[str]) -> Author:
return Author(
id=f"https://openalex.org/{author_id}",
display_name=name,
topics=[WorkTopic(id=tid, display_name=f"Topic {tid}") for tid in topic_ids],
)
def _mapped_topics(*topic_ids: str) -> list[MappedOpenAlexTopic]:
return [
MappedOpenAlexTopic(topic_id=tid, topic_display_name=f"Topic {tid}")
for tid in topic_ids
]
def test_topic_corroborated_patents_keeps_two_overlapping_topics() -> None:
author = _author_with_topics(
"A123", "Wei Zhang",
["https://openalex.org/T1", "https://openalex.org/T2"],
)
patent = _patent("EP1")
patent_topic_map = {
patent_map_key(patent): _mapped_topics(
"https://openalex.org/T1", "https://openalex.org/T2", "https://openalex.org/T3"
),
}
result = topic_corroborated_patents([patent], author, patent_topic_map)
assert result == [patent]
def test_topic_corroborated_patents_drops_single_coincidental_overlap() -> None:
"""A single shared topic isn't enough — broad, common topics show up on
many unrelated patents and profiles by coincidence."""
author = _author_with_topics(
"A123", "Xin Wang",
["https://openalex.org/T1", "https://openalex.org/T9"],
)
patent = _patent("EP2")
patent_topic_map = {
patent_map_key(patent): _mapped_topics(
"https://openalex.org/T1", "https://openalex.org/T2", "https://openalex.org/T3"
),
}
result = topic_corroborated_patents([patent], author, patent_topic_map)
assert result == []
def test_topic_corroborated_patents_drops_patent_without_mapped_topics() -> None:
author = _author_with_topics("A123", "Wei Zhang", ["https://openalex.org/T1"])
patent = _patent("EP3")
result = topic_corroborated_patents([patent], author, {})
assert result == []
def test_topic_corroborated_patents_rejects_everything_without_author_topic_profile() -> None:
author = Author(id="https://openalex.org/A999", display_name="Wei Zhang")
patent = _patent("EP4")
patent_topic_map = {
patent_map_key(patent): _mapped_topics(
"https://openalex.org/T1", "https://openalex.org/T2"
),
}
result = topic_corroborated_patents([patent], author, patent_topic_map)
assert result == []
def test_primary_classification_codes_keeps_only_afi_marked_codes() -> None:
"""A patent with many secondary ("ALI") codes alongside its one primary
("AFI") code must only contribute the primary one — otherwise a large
secondary-code topic cloud makes coincidental multi-topic overlaps with
an unrelated same-named author far too easy (confirmed against a real
org_patents rebuild: a 20-code patent picked up 70+ topics)."""
patent = _patent("EP1")
patent.ipc = [
"G06V 10/776 20220101AFI20250422BHUS",
"G01N 33/569 20060101ALI20250422BHUS",
"G06T 5/20 20060101ALI20250422BHUS",
]
patent.cpc = ["G16H 30/40 20180101ALI20250422BHUS"]
result = primary_classification_codes(patent)
assert result == ["G06V 10/776 20220101AFI20250422BHUS"]
def test_primary_classification_codes_falls_back_to_all_codes_without_afi_marker() -> None:
patent = _patent("EP2")
patent.ipc = ["G06V 10/776 20220101ALI20250422BHUS"]
patent.cpc = ["G01N 33/569 20060101ALI20250422BHUS"]
result = primary_classification_codes(patent)
assert result == patent.ipc + patent.cpc
@@ -17,6 +17,7 @@ from inse.patents.patents_openalex_keywords.mapping import (
logger = logging.getLogger(__name__)
_LEVEL_LOOKUP_ORDER = ("subgroup", "group", "subclass", "class", "section")
_MAX_SEARCH_WINDOW = 10_000 # Elasticsearch's default index.max_result_window
def candidate_doc_ids(symbol: str) -> list[str]:
@@ -179,26 +180,35 @@ class PatentsOpenAlexKeywordsClient:
return hits[0].get("_source") if hits else None
async def lookup_ids(self, doc_ids: list[str]) -> dict[str, dict[str, Any]]:
"""Resolves multiple doc ids in a single _search request (id -> _source)."""
"""Resolves multiple doc ids in as few _search requests as possible
(id -> _source). Chunked to stay under Elasticsearch's
index.max_result_window (10000) — a single query with more ids than
that fails with a 400 "Result window is too large" error, which hit
real org_patents rebuilds resolving topics for many patents at once.
"""
unique_ids = list(dict.fromkeys(doc_ids))
if not unique_ids:
return {}
results: dict[str, dict[str, Any]] = {}
async with httpx.AsyncClient(
base_url=self.base_url,
timeout=self.timeout,
transport=self.transport,
) as client:
response = await client.post(
f"/{PATENTS_OPENALEX_KEYWORDS_INDEX}/_search",
headers=self._headers(),
json={"size": len(unique_ids), "query": {"ids": {"values": unique_ids}}},
)
if response.status_code == 404:
return {}
response.raise_for_status()
hits = response.json().get("hits", {}).get("hits", [])
return {hit["_id"]: hit.get("_source", {}) for hit in hits}
for start in range(0, len(unique_ids), _MAX_SEARCH_WINDOW):
chunk = unique_ids[start : start + _MAX_SEARCH_WINDOW]
response = await client.post(
f"/{PATENTS_OPENALEX_KEYWORDS_INDEX}/_search",
headers=self._headers(),
json={"size": len(chunk), "query": {"ids": {"values": chunk}}},
)
if response.status_code == 404:
continue
response.raise_for_status()
hits = response.json().get("hits", {}).get("hits", [])
results.update({hit["_id"]: hit.get("_source", {}) for hit in hits})
return results
async def lookup_symbol(self, symbol: str) -> dict[str, Any] | None:
ordered_ids = candidate_doc_ids(symbol)
@@ -15,7 +15,10 @@ from inse.patents.authors.ipc_openalex_mapping import (
)
from inse.patents.common import model
from inse.patents.ipc_lookup import extract_ipc_symbol, parse_ipc_symbol
from inse.patents.patents_openalex_keywords.client import PatentsOpenAlexKeywordsClient
from inse.patents.patents_openalex_keywords.client import (
PatentsOpenAlexKeywordsClient,
candidate_doc_ids,
)
from inse.patents.patents_openalex_keywords.ipc_entries import infer_subclass, normalize_symbol
logger = logging.getLogger(__name__)
@@ -213,8 +216,24 @@ class PatentOpenAlexMappingResolver:
self,
patents: list[model.PatentEntry],
) -> dict[str, list[MappedOpenAlexTopic]]:
"""Resolves topics for many patents at once via a single batched
Elasticsearch request, instead of the sequential per-patent /
per-code lookups in resolve_mapped_topics_for_patent(). This matters
a lot when called for many patents at once (e.g. building
org_patents across thousands of authors) — one request per code,
repeated per patent, previously added minutes of latency."""
from inse.patents.common.parsing import patent_map_key
if not patents:
return {}
candidate_symbols: list[str] = []
for patent in patents:
for raw_code in (*patent.ipc, *patent.cpc):
candidate_symbols.extend(_lookup_candidates(raw_code))
await self._preload_documents(candidate_symbols)
result: dict[str, list[MappedOpenAlexTopic]] = {}
for patent in patents:
result[patent_map_key(patent)] = await self.resolve_mapped_topics_for_patent(
@@ -222,6 +241,55 @@ class PatentOpenAlexMappingResolver:
)
return result
async def _preload_documents(self, symbols: list[str]) -> None:
"""Resolve all IPC/CPC candidate symbols in one or few ES _search requests."""
pending = list(
dict.fromkeys(
normalized
for symbol in symbols
if (normalized := normalize_symbol(symbol))
and normalized not in self._doc_cache
)
)
if not pending:
return
all_doc_ids = list(
dict.fromkeys(
doc_id
for symbol in pending
for doc_id in candidate_doc_ids(symbol)
)
)
docs_by_id: dict[str, dict] = {}
if all_doc_ids and await self._elasticsearch_enabled_for_request():
try:
batch_size = 500
for start in range(0, len(all_doc_ids), batch_size):
batch = all_doc_ids[start : start + batch_size]
docs_by_id.update(await self.client.lookup_ids(batch))
except Exception as exc:
logger.warning(
"patents_openalex_keywords batch preload failed: %s",
exc,
)
self._elasticsearch_enabled = False
json_table = load_patents_openalex_keywords_json()
for symbol in pending:
doc = next(
(
docs_by_id[doc_id]
for doc_id in candidate_doc_ids(symbol)
if doc_id in docs_by_id
),
None,
)
if doc is None:
doc = _json_lookup_symbol(symbol, json_table)
self._doc_cache[symbol] = doc
async def _elasticsearch_enabled_for_request(self) -> bool:
if not self.use_elasticsearch:
return False
@@ -3,7 +3,10 @@ import json
import httpx
import pytest
from inse.patents.patents_openalex_keywords.client import PatentsOpenAlexKeywordsClient
from inse.patents.patents_openalex_keywords.client import (
_MAX_SEARCH_WINDOW,
PatentsOpenAlexKeywordsClient,
)
from inse.patents.patents_openalex_keywords.mapping import PATENTS_OPENALEX_KEYWORDS_INDEX
@@ -97,6 +100,34 @@ async def test_lookup_symbol_resolves_via_a_single_batched_request():
assert doc == {"ipc_label": "match"}
@pytest.mark.anyio
async def test_lookup_ids_chunks_requests_over_max_search_window():
"""A single _search with more than index.max_result_window (10000) ids
fails with a 400 "Result window is too large" error — confirmed against
the real cluster. lookup_ids() must split large id lists into chunks
that each stay within that limit."""
captured_sizes: list[int] = []
def handler(request: httpx.Request) -> httpx.Response:
body = json.loads(request.content)
values = body["query"]["ids"]["values"]
captured_sizes.append(len(values))
hits = [{"_id": doc_id, "_source": {"ipc_label": doc_id}} for doc_id in values[:1]]
return httpx.Response(200, json={"hits": {"hits": hits}})
client = PatentsOpenAlexKeywordsClient(
api_key="test-key",
transport=httpx.MockTransport(handler),
)
doc_ids = [f"subgroup:X{i}" for i in range(_MAX_SEARCH_WINDOW + 500)]
result = await client.lookup_ids(doc_ids)
assert captured_sizes == [_MAX_SEARCH_WINDOW, 500]
assert all(size <= _MAX_SEARCH_WINDOW for size in captured_sizes)
assert len(result) == 2
@pytest.mark.anyio
async def test_lookup_symbol_prefers_more_specific_level_when_multiple_match():
def handler(request: httpx.Request) -> httpx.Response:
@@ -45,13 +45,26 @@ def test_mapped_topics_from_index_doc_includes_topics_and_keywords() -> None:
class _FakeKeywordsClient:
def __init__(self, docs: dict[str, dict]):
self.docs = docs
self.lookup_ids_calls = 0
self.lookup_symbol_calls = 0
async def index_exists(self) -> bool:
return True
async def lookup_symbol(self, symbol: str):
self.lookup_symbol_calls += 1
return self.docs.get(symbol)
async def lookup_ids(self, doc_ids: list[str]) -> dict[str, dict]:
self.lookup_ids_calls += 1
result: dict[str, dict] = {}
for doc_id in doc_ids:
_level, symbol = doc_id.split(":", 1)
doc = self.docs.get(symbol)
if doc is not None:
result[doc_id] = doc
return result
def test_resolver_uses_index_doc_before_legacy_fallback() -> None:
resolver = PatentOpenAlexMappingResolver(
@@ -100,3 +113,45 @@ def test_filter_uses_patent_topic_map_from_resolver() -> None:
patent_topic_map=topic_map,
)
assert len(filtered) == 1
def test_resolve_topics_for_patents_preloads_documents_in_one_batch() -> None:
client = _FakeKeywordsClient(
{
"H01L": {
"ipc_level": "subclass",
"ipc_symbol": "H01L",
"topic_matches": [
{
"topic_id": "https://openalex.org/T99999",
"topic_display_name": "Semiconductor materials and devices",
}
],
"keyword_matches": [],
},
"C07C": {
"ipc_level": "subclass",
"ipc_symbol": "C07C",
"topic_matches": [
{
"topic_id": "https://openalex.org/T11111",
"topic_display_name": "Organic chemistry",
}
],
"keyword_matches": [],
},
}
)
resolver = PatentOpenAlexMappingResolver(client=client, use_elasticsearch=True)
patents = [
model.PatentEntry(patent_id="EP1", source="EPO", ipc=["H01L 21/02"]),
model.PatentEntry(patent_id="EP2", source="EPO", ipc=["C07C 31/20"]),
model.PatentEntry(patent_id="US1", source="USPTO", ipc=["H01L 27/04"]),
]
topic_map = asyncio.run(resolver.resolve_topics_for_patents(patents))
assert client.lookup_ids_calls == 1
assert client.lookup_symbol_calls == 0
assert len(topic_map) == 3
assert all(topics for topics in topic_map.values())
@@ -136,6 +136,8 @@ def test_first_name_match_kind() -> None:
("Schmitz, Oliver", "Oliver J. Schmitz", False),
("Schmitz, Oliver J.", "Oliver J. Schmitz", True),
("Schmitz, O. J.", "Oliver J. Schmitz", True),
("Kim, Young Gil", "Moon Young Kim", False),
("Kim, Young Hwan", "Moon Young Kim", False),
],
)
def test_name_matches_person_multi_part(
-36
View File
@@ -4,7 +4,6 @@
Pydantic models for publication works.
"""
from enum import StrEnum
from typing import List
from typing import Optional
@@ -42,38 +41,3 @@ class WorkPage(BaseModel):
class WorkList(BaseModel):
elements: List[Work] = Field(default_factory=list, description="All works.")
total: int = Field(default=0, description="The total number of works.")
class WorkPurpose(StrEnum):
"""Represents the purpose of a work."""
BASIC_RESEARCH = "Basic Research"
APPLIED_RESEARCH = "Applied Research"
NON_RESEARCH = "Non-Research"
EXPERIMENTAL_DEVELOPMENT = "Experimental Development"
NOT_CLASSIFIED = "Not Classified"
class SpecificWorkPurpose(BaseModel):
"""Represents the purpose of a specific work, including its ID, purpose, and optional reasoning."""
raw_oa_work_id: str = Field(description="The raw OpenAlex work id.")
publication_year: Optional[int] = Field(
default=None, description="The publication year of the work."
)
purpose: WorkPurpose = Field(description="The purpose of the work.")
reasoning: Optional[str] = Field(
default=None, description="The reasoning behind the purpose determination."
)
class AuthorWorkPurposes(BaseModel):
"""Represents the purposes of an author, including their ID and a list of specific work purposes."""
raw_oa_author_id: str = Field(description="The raw OpenAlex author id.")
total: int = Field(
default=0, description="The total number of works for the author."
)
purposes: List[SpecificWorkPurpose] = Field(
default_factory=list, description="The list of specific work purposes."
)
@@ -1,36 +0,0 @@
from typing import Annotated
from fastapi import APIRouter, Path
from inse.tags import Tags
from inse.works.model import AuthorWorkPurposes, SpecificWorkPurpose
from inse.works import purpose_service
WORKS_PREFIX = "/api/purpose"
router = APIRouter(prefix=WORKS_PREFIX, tags=[Tags.WORKS])
@router.get(
"/{raw_oa_work_id}/purpose",
operation_id="getWorkPurpose",
summary="Returns the purpose of a work based on its ID.",
)
async def get_work_purpose(
raw_oa_work_id: Annotated[str, Path(description="The raw OpenAlex work id.")],
) -> SpecificWorkPurpose:
return await purpose_service.get_work_purpose(raw_oa_work_id=raw_oa_work_id)
@router.get(
"/{raw_oa_author_id}/purposes",
operation_id="getAuthorWorkPurposes",
summary="Returns the purposes of an author based on their ID.",
)
async def get_author_work_purposes(
raw_oa_author_id: Annotated[str, Path(description="The raw OpenAlex author id.")],
) -> AuthorWorkPurposes:
return await purpose_service.get_author_work_purposes(
raw_oa_author_id=raw_oa_author_id
)
@@ -1,166 +0,0 @@
import logging
from typing import Dict, List
from inse.exceptions import NotFoundException
from inse.integrations import elasticsearch
from inse.model import ESIndex
from inse.works.model import AuthorWorkPurposes, SpecificWorkPurpose, WorkPurpose
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
async def get_work_purpose(raw_oa_work_id: str) -> SpecificWorkPurpose:
raw_oa_work_id = raw_oa_work_id.strip().upper()
response = await elasticsearch.get(
index=ESIndex.OPENALEX_WORKS_WILDCARD,
doc_id=raw_oa_work_id,
source=["title", "abstract"],
)
logger.debug(f"Elasticsearch response for work id {raw_oa_work_id}: {response}")
source = response.get("_source", {})
if not source:
raise NotFoundException(f"Work with id {raw_oa_work_id} not found.")
logger.debug(f"Found work source for id {raw_oa_work_id}: {source}")
return SpecificWorkPurpose(
raw_oa_work_id=raw_oa_work_id,
publication_year=source.get("publication_year"),
purpose=WorkPurpose.NON_RESEARCH, # TODO: Replace with actual purpose determination logic
reasoning="This is a placeholder reasoning for the purpose determination.",
)
async def get_author_work_purposes(raw_oa_author_id: str) -> AuthorWorkPurposes:
raw_oa_author_id = raw_oa_author_id.strip().upper()
logger.debug(f"Retrieving work purposes for author {raw_oa_author_id}")
relevant_work_information = await get_relevant_work_information(raw_oa_author_id)
logger.debug(
f"Retrieved work ids for author {raw_oa_author_id}: {list(relevant_work_information.keys())}"
)
work_ids = list(relevant_work_information.keys())
raw_work_ids = list(map(_extract_raw_work_id, work_ids))
logger.debug(
f"Extracted raw work ids for author {raw_oa_author_id}: {raw_work_ids}"
)
response = await elasticsearch.search(
index=ESIndex.WORK_CLASSIFICATIONS,
source=["work_id", "classification"],
query={"terms": {"work_id": raw_work_ids}},
size=10000,
)
logger.debug(f"Elasticsearch response for work classifications v2FOO: {response}")
purposes: List[SpecificWorkPurpose] = []
hits_block = response.get("hits", {})
hits = hits_block.get("hits", [])
total_hits = hits_block.get("total", {}).get("value", 0)
hitted_work_ids = []
for hit in hits:
source = hit.get("_source", {})
work_id = source.get("work_id")
classification = source.get("classification")
if work_id:
work_purpose = _primary_classification_category_to_work_purpose(
classification.get("primary_category", "")
)
purposes.append(
SpecificWorkPurpose(
raw_oa_work_id=work_id,
publication_year=relevant_work_information.get(
f"https://openalex.org/{work_id}"
),
purpose=work_purpose,
reasoning=classification.get("classification_reason"),
)
)
hitted_work_ids.append(f"https://openalex.org/{work_id}")
else:
logger.warning(f"Work hit without id for author {raw_oa_author_id}: {hit}")
for work_id in filter(lambda wid: wid not in hitted_work_ids, work_ids):
purposes.append(
SpecificWorkPurpose(
raw_oa_work_id=_extract_raw_work_id(work_id),
publication_year=relevant_work_information.get(work_id),
purpose=WorkPurpose.NOT_CLASSIFIED,
reasoning="No classification found for this work.",
)
)
return AuthorWorkPurposes(
raw_oa_author_id=raw_oa_author_id, total=total_hits, purposes=purposes
)
async def get_relevant_work_information(raw_oa_author_id: str) -> Dict[str, int]:
raw_oa_author_id = raw_oa_author_id.strip().upper()
response = await elasticsearch.search(
index=ESIndex.OPENALEX_WORKS_WILDCARD,
source=["id", "publication_year"],
query={
"nested": {
"path": "authorships",
"query": {
"bool": {
"filter": [
{
"term": {
"authorships.author.id": f"https://openalex.org/{raw_oa_author_id}"
}
},
],
},
},
},
},
size=10000,
)
logger.debug(f"Elasticsearch response for author id {raw_oa_author_id}: {response}")
hits_block = response.get("hits", {})
hits = hits_block.get("hits", [])
d: Dict[str, int] = {}
for hit in hits:
source = hit.get("_source", {})
work_id = source.get("id")
publication_year = source.get("publication_year")
if work_id:
d[work_id] = int(publication_year) if publication_year is not None else 0
else:
logger.warning(f"Work hit without id for author {raw_oa_author_id}: {hit}")
return d
def _extract_raw_work_id(work_id: str) -> str:
"""
Extracts the raw work ID from a full OpenAlex work ID.
For example, given "https://openalex.org/W1234567890", it returns "W1234567890".
"""
if not work_id:
return ""
return work_id.split("/")[-1]
def _primary_classification_category_to_work_purpose(
primary_category: str,
) -> WorkPurpose:
mapping = {
"basic_research": WorkPurpose.BASIC_RESEARCH,
"applied_research": WorkPurpose.APPLIED_RESEARCH,
"non_research": WorkPurpose.NON_RESEARCH,
"experimental_development": WorkPurpose.EXPERIMENTAL_DEVELOPMENT,
}
return mapping.get(
primary_category, WorkPurpose.NON_RESEARCH
) # Default to NON_RESEARCH if not found
+163
View File
@@ -1,4 +1,9 @@
from datetime import datetime
from enum import StrEnum
from typing import Optional, List
from pydantic import BaseModel, Field
from inse.model import Page
from inse.models.openalex.work import Work
@@ -14,3 +19,161 @@ class WorkSortBy(StrEnum):
class WorkPage(Page[Work]):
pass
class WorkPrimaryCategory(StrEnum):
"""Represents the primary category of a work."""
BASIC_RESEARCH = "basic_research"
APPLIED_RESEARCH = "applied_research"
NON_RESEARCH = "non_research"
EXPERIMENTAL_DEVELOPMENT = "experimental_development"
NOT_CLASSIFIED = "not_classified"
class WorkClassificationAuthor(BaseModel):
"""An author entry within a work classification document."""
id: Optional[str] = Field(default=None, description="The OpenAlex author id.")
display_name: Optional[str] = Field(
default=None, description="The author's display name."
)
orcid: Optional[str] = Field(default=None, description="The author's ORCID id.")
class WorkClassificationInstitution(BaseModel):
"""An institution entry within a work classification document."""
id: Optional[str] = Field(default=None, description="The OpenAlex institution id.")
display_name: Optional[str] = Field(
default=None, description="The institution's display name."
)
ror: Optional[str] = Field(default=None, description="The institution's ROR id.")
class WorkClassificationTopicGroup(BaseModel):
"""A domain/field/subfield group referenced within a classification topic."""
id: Optional[str] = Field(default=None, description="The id of the group.")
display_name: Optional[str] = Field(
default=None, description="The display name of the group."
)
class WorkClassificationTopic(BaseModel):
"""A topic entry within a work classification document."""
id: Optional[str] = Field(default=None, description="The OpenAlex topic id.")
display_name: Optional[str] = Field(
default=None, description="The topic's display name."
)
score: Optional[float] = Field(
default=None, description="The relevance score of the topic."
)
domain: Optional[WorkClassificationTopicGroup] = Field(
default=None, description="The topic's domain."
)
field: Optional[WorkClassificationTopicGroup] = Field(
default=None, description="The topic's field."
)
subfield: Optional[WorkClassificationTopicGroup] = Field(
default=None, description="The topic's subfield."
)
class WorkClassificationDetails(BaseModel):
"""The core classification result for a work."""
primary_category: Optional[WorkPrimaryCategory] = Field(
default=None,
description="The primary classification category assigned to the work.",
)
confidence: Optional[str] = Field(
default=None, description="The confidence level of the classification."
)
pasteur_quadrant: Optional[str] = Field(
default=None, description="The Pasteur quadrant classification, if applicable."
)
applied_orientation_score: Optional[int] = Field(
default=None,
description="The applied orientation score for the classification.",
)
insufficient_context: Optional[bool] = Field(
default=None,
description="Whether there was insufficient context to classify confidently.",
)
signals_used: Optional[List[str]] = Field(
default=None, description="The signals used to arrive at the classification."
)
classification_reason: Optional[str] = Field(
default=None, description="The reasoning behind the classification."
)
class WorkClassificationMeta(BaseModel):
"""Metadata about how and when a classification was produced."""
model: Optional[str] = Field(
default=None, description="The model used to produce the classification."
)
prompt_version: Optional[str] = Field(
default=None,
description="The version of the prompt used to produce the classification.",
)
classified_at: Optional[datetime] = Field(
default=None,
description="The timestamp at which the classification was produced.",
)
class WorkClassificationValidation(BaseModel):
"""Validation results for a classification."""
valid: Optional[bool] = Field(
default=None, description="Whether the classification passed validation."
)
errors: Optional[List[str]] = Field(
default=None, description="Validation errors, if any."
)
corrections: Optional[List[str]] = Field(
default=None, description="Corrections applied, if any."
)
class WorkClassification(BaseModel):
"""Represents a full work-classification document."""
work_id: str = Field(description="The full OpenAlex work id/URL.")
doi: Optional[str] = Field(default=None, description="The DOI of the work.")
title: Optional[str] = Field(default=None, description="The title of the work.")
publication_year: Optional[int] = Field(
default=None, description="The publication year of the work."
)
authors: List[WorkClassificationAuthor] = Field(
default_factory=list, description="The authors of the work."
)
institutions: List[WorkClassificationInstitution] = Field(
default_factory=list, description="The institutions associated with the work."
)
topics: List[WorkClassificationTopic] = Field(
default_factory=list, description="The topics associated with the work."
)
classification: Optional[WorkClassificationDetails] = Field(
default=None, description="The classification result for the work."
)
classification_meta: Optional[WorkClassificationMeta] = Field(
default=None, description="Metadata about the classification."
)
validation: Optional[WorkClassificationValidation] = Field(
default=None, description="Validation results for the classification."
)
@classmethod
def from_dict(cls, source: dict) -> Optional["WorkClassification"]:
if not source or "work_id" not in source:
return None
return cls.model_validate(source)
class WorkClassificationPage(Page[WorkClassification]):
pass
+133 -3
View File
@@ -1,16 +1,27 @@
from typing import Annotated, List
import logging
from typing import Annotated, List, Optional
from fastapi import APIRouter, Path, Query
from inse.tags import Tags
from inse.model import SortDirection
from inse.works.v2.model import WorkPage, WorkSortBy
from inse.works.v2.model import (
WorkClassification,
WorkClassificationPage,
WorkPage,
WorkSortBy,
)
from inse.models.openalex.work_topic import WorkTopic
from inse.models.openalex.institution import Institution
from inse.models.openalex.author import Author
from inse.models.openalex.topic import Topic
WORKS_v2_PREFIX = "/api/v2/works"
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/v2/works", tags=[Tags.WORKS_V2])
router = APIRouter(prefix=WORKS_v2_PREFIX, tags=[Tags.WORKS_V2])
@router.get(
@@ -183,3 +194,122 @@ async def get_authors_by_ids(
from inse.works.v2.service import get_work_authors_by_ids
return await get_work_authors_by_ids(author_ids=author_ids or [])
@router.get(
"/topics/autocomplete",
operation_id="getTopicAutocomplete",
summary="Returns a list of work topics based on a search term for autocomplete functionality.",
)
async def get_topic_autocomplete(
query: Annotated[
str,
Query(
description="A search term to filter topics by (partial matches allowed)."
),
] = "",
) -> List[Topic]:
from inse.works.v2.service import search_topics
return await search_topics(query=query)
@router.get(
"/institutions/autocomplete",
operation_id="getInstitutionAutocomplete",
summary="Returns a list of institutions based on a search term for autocomplete functionality.",
)
async def get_institution_autocomplete(
query: Annotated[
str,
Query(
description="A search term to filter institutions by (partial matches allowed)."
),
] = "",
) -> List[Institution]:
from inse.works.v2.service import search_institutions
return await search_institutions(query=query)
@router.get(
"/authors/autocomplete",
operation_id="getAuthorAutocomplete",
summary="Returns a list of authors based on a search term for autocomplete functionality.",
)
async def get_author_autocomplete(
query: Annotated[
str,
Query(
description="A search term to filter authors by (partial matches allowed)."
),
] = "",
) -> List[Author]:
from inse.works.v2.service import search_authors
return await search_authors(query=query)
@router.get(
"/classification/author/{raw_oa_author_id}",
operation_id="getAuthorWorkClassifications",
summary="Returns the classifications of an author's works based on their ID.",
)
async def get_author_work_classifications(
raw_oa_author_id: Annotated[str, Path(description="The raw OpenAlex author id.")],
) -> WorkClassificationPage:
from inse.works.v2.service import get_work_classifications_by_author_id
return await get_work_classifications_by_author_id(
raw_oa_author_id=raw_oa_author_id
)
@router.get(
"/classification/work/{work_id}",
operation_id="getWorkClassificationByWorkId",
summary="Returns the classifications of a work based on its ID.",
)
async def get_work_classification_by_work_id(
work_id: Annotated[str, Path(description="The OpenAlex work id.")],
) -> Optional[WorkClassification]:
from inse.works.v2.service import get_work_classification_by_work_id
return await get_work_classification_by_work_id(work_id=work_id)
@router.get(
"/classification/works/search",
operation_id="getWorkClassificationsByWorkIds",
summary="Returns the classifications of works based on their IDs.",
)
async def get_work_classifications_by_work_ids(
work_ids: Annotated[
list[str],
Query(
description="A list of OpenAlex work IDs to retrieve classifications for."
),
] = [],
page: Annotated[
int, Query(description="The page number to retrieve. (0-based)", ge=0)
] = 0,
size: Annotated[
int,
Query(
description="The number of classifications to retrieve per page.",
ge=1,
le=100,
),
] = 10,
) -> WorkClassificationPage:
from inse.works.v2.service import get_work_classifications_by_work_ids
logger.debug(
f"Fetching work classifications for work IDs: {work_ids}, page: {page}, size: {size}"
)
return await get_work_classifications_by_work_ids(
work_ids=work_ids or [],
page=page,
size=size,
)
+226 -3
View File
@@ -4,6 +4,8 @@ from typing import List, Optional
from inse.integrations import elasticsearch
from inse.model import ESIndex, SortDirection
from inse.works.v2.model import (
WorkClassification,
WorkClassificationPage,
WorkPage,
WorkSortBy,
)
@@ -11,9 +13,10 @@ from inse.models.openalex.work_topic import WorkTopic
from inse.models.openalex.institution import Institution
from inse.models.openalex.work import Work
from inse.models.openalex.author import Author
from inse.models.openalex.topic import Topic
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
logger.setLevel(logging.DEBUG)
def _authors_nested_query(author_ids: List[str]) -> dict:
@@ -247,7 +250,14 @@ async def get_work_institutions_by_ids(institution_ids: List[str]) -> List[Insti
response = await elasticsearch.search(
ESIndex.OPENALEX_INSTITUTIONS,
source=["id", "display_name", "country_code"],
source=[
"id",
"display_name",
"display_name_alternatives",
"country_code",
"type",
"ror",
],
query={"bool": {"must": must}},
size=len(institution_ids),
)
@@ -274,7 +284,13 @@ async def get_work_authors_by_ids(author_ids: List[str]) -> List[Author]:
response = await elasticsearch.search(
ESIndex.OPENALEX_AUTHORS,
source=["id", "display_name", "orcid"],
source=[
"id",
"display_name",
"orcid",
"last_known_institutions",
"works_count",
],
query={"bool": {"must": must}},
size=len(author_ids),
)
@@ -290,6 +306,213 @@ async def get_work_authors_by_ids(author_ids: List[str]) -> List[Author]:
return authors
async def search_topics(
query: str,
size: int = 10,
) -> List[Topic]:
response = await elasticsearch.search(
ESIndex.OPENALEX_TOPICS,
source=[
"id",
"display_name",
"subfield",
"field",
"domain",
],
query={"match_bool_prefix": {"display_name": query}},
size=min(size, 10),
)
hits_block = response.get("hits", {})
elements: List[Topic] = []
for hit in hits_block.get("hits", []):
topic = Topic.from_dict(hit.get("_source", {})) # type: ignore
if topic is not None:
elements.append(topic)
return elements
async def search_institutions(
query: str,
size: int = 10,
) -> List[Institution]:
response = await elasticsearch.search(
ESIndex.OPENALEX_INSTITUTIONS,
source=[
"id",
"display_name",
"display_name_alternatives",
"country_code",
"type",
"ror",
],
query={
"bool": {
"should": [
{"match_bool_prefix": {"display_name": query}},
{"match_bool_prefix": {"display_name_alternatives": query}},
],
"minimum_should_match": 1,
}
},
size=min(size, 10),
)
hits_block = response.get("hits", {})
elements: List[Institution] = []
for hit in hits_block.get("hits", []):
institution = Institution.from_dict(hit.get("_source", {})) # type: ignore
if institution is not None:
elements.append(institution)
return elements
async def search_authors(
query: str,
size: int = 10,
) -> List[Author]:
response = await elasticsearch.search(
ESIndex.OPENALEX_AUTHORS,
source=[
"id",
"display_name",
"orcid",
"last_known_institutions",
"works_count",
],
query={"match_phrase_prefix": {"display_name": query}},
size=min(size, 10),
)
hits_block = response.get("hits", {})
elements: List[Author] = []
for hit in hits_block.get("hits", []):
author = Author.from_dict(hit.get("_source", {})) # type: ignore
if author is not None:
elements.append(author)
return elements
async def get_work_classifications_by_author_id(
raw_oa_author_id: str,
page: int = 0,
size: int = 10000,
) -> WorkClassificationPage:
must = [
{
"nested": {
"path": "authors",
"query": {"term": {"authors.id": f"{_prefix_id(raw_oa_author_id)}"}},
}
}
]
response = await elasticsearch.search(
ESIndex.WORK_CLASSIFICATIONS,
source=[
"work_id",
"doi",
"title",
"publication_year",
"authors",
"institutions",
"topics",
"classification",
],
query={"bool": {"must": must}},
size=size,
offset=page * size,
)
hits_block = response.get("hits", {})
total = hits_block.get("total", {}).get("value", 0)
elements = []
for hit in hits_block.get("hits", []):
classification = WorkClassification.from_dict(hit.get("_source", {})) # type: ignore
if classification is not None:
elements.append(classification)
return WorkClassificationPage(
elements=elements,
total=total,
page=page,
size=size,
)
async def get_work_classification_by_work_id(
work_id: str,
) -> Optional[WorkClassification]:
response = await elasticsearch.search(
ESIndex.WORK_CLASSIFICATIONS,
source=[
"work_id",
"doi",
"title",
"publication_year",
"authors",
"institutions",
"topics",
"classification",
"classification_meta",
"validation",
],
query={"term": {"work_id": f"{_prefix_id(work_id)}"}},
size=1,
)
hits = response.get("hits", {}).get("hits", [])
if not hits:
return None
return WorkClassification.from_dict(hits[0].get("_source", {}))
async def get_work_classifications_by_work_ids(
work_ids: List[str],
page: int = 0,
size: int = 10000,
) -> WorkClassificationPage:
prefixed = [_prefix_id(wid) for wid in work_ids]
logger.debug(f"Fetching work classifications for work IDs: {prefixed}")
response = await elasticsearch.search(
ESIndex.WORK_CLASSIFICATIONS,
source=[
"work_id",
"doi",
"title",
"publication_year",
"authors",
"institutions",
"topics",
"classification",
"classification_meta",
"validation",
],
query={"terms": {"work_id": prefixed}},
size=size,
offset=page * size,
)
hits_block = response.get("hits", {})
total = hits_block.get("total", {}).get("value", 0)
elements: List[WorkClassification] = []
for hit in hits_block.get("hits", []):
classification = WorkClassification.from_dict(hit.get("_source", {}))
if classification is not None:
elements.append(classification)
p = WorkClassificationPage(elements=elements, total=total, page=page, size=size)
logger.debug(f"Returning WorkClassificationPage: {p}")
return p
def _prefix_id(raw_id: str) -> str:
if not raw_id.startswith("https://openalex.org/"):
return f"https://openalex.org/{raw_id}"