diff --git a/service/src/main/inse/patents/authors/identity.py b/service/src/main/inse/patents/authors/identity.py new file mode 100644 index 00000000..1de0f927 --- /dev/null +++ b/service/src/main/inse/patents/authors/identity.py @@ -0,0 +1,138 @@ +"""Identity signals used to decide whether a patent really belongs to a person. + +These are the *strong* signals (name specificity, institution/assignee overlap) +that distinguish one same-named person from another. Topic/IPC similarity is only +a supporting plausibility signal and lives in ``ipc_topic_matching``. +""" +from __future__ import annotations + +from inse.models.openalex.author import Author +from inse.patents.authors.name_matching import ( + first_name_match_kind_for_person, + name_matches_person, +) +from inse.patents.authors.name_variants import parse_person_name +from inse.patents.common import model +from inse.patents.institutions.name_matching import assignee_matches_institution_name + +# Ambiguity is derived purely from data that already exists in the project (the +# number of patent hits for the name and the number of same-named authors in the +# local OpenAlex index) — no external name database is used. +# +# Thresholds are starting values and should be validated against a handful of +# test persons. +PATENT_HIT_COUNT_THRESHOLD = 300 +OPENALEX_FULL_NAME_COUNT_THRESHOLD = 2 +OPENALEX_LAST_NAME_COUNT_THRESHOLD = 100 + + +def is_ambiguous_name( + display_name: str | None, + *, + patent_hit_count: int = 0, + 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. + + A name is treated as ambiguous (and therefore handled strictly) 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. + + 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. + """ + parsed = parse_person_name(display_name) + if parsed is None or parsed.is_single_token: + return True + + if ( + openalex_full_name_count is not None + and openalex_full_name_count >= OPENALEX_FULL_NAME_COUNT_THRESHOLD + ): + return True + + if ( + openalex_last_name_count is not None + and openalex_last_name_count >= OPENALEX_LAST_NAME_COUNT_THRESHOLD + ): + return True + + if patent_hit_count >= PATENT_HIT_COUNT_THRESHOLD: + return True + + return False + + +def author_institution_names(author: Author) -> list[str]: + names: list[str] = [] + seen: set[str] = set() + + def _add(display_name: str | None) -> None: + if not display_name or not display_name.strip(): + return + key = display_name.casefold() + if key in seen: + return + seen.add(key) + names.append(display_name.strip()) + + for institution in author.last_known_institutions or []: + _add(getattr(institution, "display_name", None)) + + for affiliation in author.affiliations or []: + institution = getattr(affiliation, "institution", None) + if institution is not None: + _add(getattr(institution, "display_name", None)) + + return names + + +def patent_institution_match( + patent: model.PatentEntry, + institution_names: list[str], +) -> bool: + if not institution_names: + return False + for assignee in patent.assignees: + if not assignee: + continue + for institution_name in institution_names: + if assignee_matches_institution_name(assignee, institution_name): + return True + return False + + +def patent_personal_assignee_match( + patent: model.PatentEntry, + display_name: str, +) -> bool: + """True when the person themselves is listed as an applicant/assignee. + + Being the personal applicant of a patent is a strong identity signal + (organisation assignees like companies/universities will not match a + full person name). + """ + if not display_name or not display_name.strip(): + return False + for assignee in patent.assignees: + if assignee and name_matches_person(assignee, display_name): + return True + return False + + +def best_name_match_kind(patent: model.PatentEntry, display_name: str) -> str: + """Best given-name match across all inventors: 'full' > 'initial' > 'none'.""" + best = "none" + for inventor in patent.inventors: + if not inventor: + continue + kind = first_name_match_kind_for_person(inventor, display_name) + if kind == "full": + return "full" + if kind == "initial": + best = "initial" + return best diff --git a/service/src/main/inse/patents/authors/ipc_topic_matching.py b/service/src/main/inse/patents/authors/ipc_topic_matching.py new file mode 100644 index 00000000..2296ce03 --- /dev/null +++ b/service/src/main/inse/patents/authors/ipc_topic_matching.py @@ -0,0 +1,191 @@ +"""Semantic comparison of patent text and classifications with author OpenAlex topics.""" +from __future__ import annotations + +from dataclasses import dataclass +from typing import Literal + +import numpy as np + +from inse.patents.common import model +from inse.util import get_model + +STRONG_SIMILARITY_THRESHOLD = 0.82 +WEAK_SIMILARITY_THRESHOLD = 0.78 +CONFLICT_SIMILARITY_THRESHOLD = 0.78 + +TopicMatchLevel = Literal["strong", "weak", "none"] + + +@dataclass(frozen=True) +class TopicMatchResult: + level: TopicMatchLevel + similarity: float + topic_conflict: bool + + +def author_topic_names(author) -> list[str]: + topics: list[tuple[str, float]] = [] + for topic in author.topics or []: + if not topic.display_name: + continue + topics.append((topic.display_name, float(topic.score or 0.0))) + topics.sort(key=lambda item: item[1], reverse=True) + return [name for name, _score in topics[:15]] + + +def _label_from_classification_field(field: str) -> str: + cleaned = field.strip() + if " - " in cleaned: + return cleaned.split(" - ", 1)[1].strip() + return cleaned + + +def classification_description_labels(patent: model.PatentEntry) -> list[str]: + labels: list[str] = [] + seen: set[str] = set() + + for classification in (*patent.ipc_descriptions, *patent.cpc_descriptions): + for field in ( + classification.section, + classification.ipc_class, + classification.subclass, + classification.main_group, + classification.subgroup, + ): + if not field: + continue + label = _label_from_classification_field(field) + key = label.casefold() + if not label or key in seen: + continue + seen.add(key) + labels.append(label) + + return labels + + +def patent_topic_text(patent: model.PatentEntry) -> str: + parts: list[str] = [] + + if patent.title and patent.title.strip(): + parts.append(patent.title.strip()) + + if patent.abstract and patent.abstract.strip(): + parts.append(patent.abstract.strip()) + + classification_labels = classification_description_labels(patent) + if classification_labels: + parts.append(f"IPC/CPC: {', '.join(classification_labels)}") + + return " ".join(parts) + + +def patent_has_topic_signal(patent: model.PatentEntry) -> bool: + return bool(patent_topic_text(patent).strip()) + + +def _encode_texts(texts: list[str]) -> np.ndarray: + if not texts: + return np.empty((0, 0)) + model_instance = get_model() + return model_instance.encode(texts, normalize_embeddings=True) + + +def _max_cosine_similarity(left: np.ndarray, right: np.ndarray) -> float: + if left.size == 0 or right.size == 0: + return 0.0 + if left.ndim == 1: + left = left.reshape(1, -1) + if right.ndim == 1: + right = right.reshape(1, -1) + return float(np.max(left @ right.T)) + + +def _match_level(similarity: float) -> TopicMatchLevel: + if similarity >= STRONG_SIMILARITY_THRESHOLD: + return "strong" + if similarity >= WEAK_SIMILARITY_THRESHOLD: + return "weak" + return "none" + + +def match_patent_to_topics( + patent: model.PatentEntry, + topic_names: list[str], + *, + patent_vector: np.ndarray | None = None, + topic_vectors: np.ndarray | None = None, +) -> TopicMatchResult: + if not topic_names: + return TopicMatchResult(level="none", similarity=0.0, topic_conflict=False) + + patent_text = patent_topic_text(patent) + if not patent_text: + return TopicMatchResult(level="none", similarity=0.0, topic_conflict=False) + + patent_embedding = patent_vector + if patent_embedding is None: + patent_embedding = _encode_texts([patent_text])[0] + + topic_embedding = topic_vectors + if topic_embedding is None: + topic_embedding = _encode_texts(topic_names) + + similarity = _max_cosine_similarity(patent_embedding, topic_embedding) + topic_conflict = similarity < CONFLICT_SIMILARITY_THRESHOLD + + return TopicMatchResult( + level=_match_level(similarity), + similarity=round(similarity, 3), + topic_conflict=topic_conflict, + ) + + +def match_patents_to_topics( + patents: list[model.PatentEntry], + topic_names: list[str], +) -> list[TopicMatchResult]: + if not patents: + return [] + if not topic_names: + return [ + TopicMatchResult(level="none", similarity=0.0, topic_conflict=False) + for _patent in patents + ] + + patent_texts = [patent_topic_text(patent) for patent in patents] + texts_to_encode = [text for text in patent_texts if text] + if not texts_to_encode: + return [ + TopicMatchResult(level="none", similarity=0.0, topic_conflict=False) + for _patent in patents + ] + + encoded = _encode_texts(texts_to_encode) + topic_vectors = _encode_texts(topic_names) + + encoded_by_text = { + text: encoded[index] + for index, text in enumerate(texts_to_encode) + } + + results: list[TopicMatchResult] = [] + for patent_text in patent_texts: + if not patent_text: + results.append( + TopicMatchResult(level="none", similarity=0.0, topic_conflict=False) + ) + continue + similarity = _max_cosine_similarity( + encoded_by_text[patent_text], + topic_vectors, + ) + topic_conflict = similarity < CONFLICT_SIMILARITY_THRESHOLD + results.append( + TopicMatchResult( + level=_match_level(similarity), + similarity=round(similarity, 3), + topic_conflict=topic_conflict, + ) + ) + return results diff --git a/service/src/main/inse/patents/authors/logic.py b/service/src/main/inse/patents/authors/logic.py index 3bf7ddff..00753674 100644 --- a/service/src/main/inse/patents/authors/logic.py +++ b/service/src/main/inse/patents/authors/logic.py @@ -7,7 +7,12 @@ from fastapi import HTTPException from starlette.status import HTTP_502_BAD_GATEWAY from starlette.status import HTTP_503_SERVICE_UNAVAILABLE +from inse.patents.authors.identity import is_ambiguous_name from inse.patents.authors.name_matching import filter_patents_by_author_name +from inse.patents.authors.topic_filter import ( + filter_patents_by_author_topics, + to_author_patent_entry, +) from inse.patents.common import model from inse.patents.common.elastic_search_client import MissingApiKeyError from inse.patents.common.parsing import ( @@ -65,15 +70,62 @@ async def get_patents_by_author_id( all_patents = parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data) all_patents = deduplicate_patents(all_patents) - matched_patents = filter_patents_by_author_name(all_patents, author_name) + patent_hit_count = len(all_patents) + name_matched = filter_patents_by_author_name(all_patents, author_name) - await enrich_patents_classifications(matched_patents, ipc_search_client) + if not name_matched: + return model.PatentsByAuthorResponse( + author_id=author_id, + author_name=author_name, + patent_count=0, + patents=[], + ) + + await enrich_patents_classifications(name_matched, ipc_search_client) + + # Ambiguity is derived only from existing project data: how many patents the + # name search returned and how many same-named authors exist in the local + # OpenAlex index. + full_name_count = await person_logic.count_authors_by_display_name(author_name) + is_ambiguous = is_ambiguous_name( + author_name, + patent_hit_count=patent_hit_count, + openalex_full_name_count=full_name_count, + ) + + # Only pay for the extra works aggregation when the author document has no + # topics of its own. + fallback_topics: list[str] = [] + if not (author.topics or []): + fallback_topics = await person_logic.get_topic_names_for_author(author_id) + + logger.info( + "Topic filtering for %s: ambiguous=%s (patent_hits=%d, openalex_same_name=%d), " + "%d author topics, %d fallback topics, %d name-matched patents", + author_name, + is_ambiguous, + patent_hit_count, + full_name_count, + len(author.topics or []), + len(fallback_topics), + len(name_matched), + ) + + # The sentence-transformer encoding is CPU-bound; run it off the event loop + # so it does not block other requests. + filtered_patents = await asyncio.to_thread( + filter_patents_by_author_topics, + name_matched, + author, + is_ambiguous=is_ambiguous, + fallback_topic_names=fallback_topics, + ) return model.PatentsByAuthorResponse( author_id=author_id, author_name=author_name, - patent_count=len(matched_patents), - patents=matched_patents, + patent_count=len(filtered_patents), + patents=[to_author_patent_entry(item) for item in filtered_patents], ) diff --git a/service/src/main/inse/patents/authors/name_matching.py b/service/src/main/inse/patents/authors/name_matching.py index 789edcfd..c849330d 100644 --- a/service/src/main/inse/patents/authors/name_matching.py +++ b/service/src/main/inse/patents/authors/name_matching.py @@ -1,5 +1,4 @@ """Inventor name normalization and matching.""" -import re from inse.patents.authors.name_variants import ( ParsedPersonName, @@ -239,6 +238,10 @@ def filter_patents_by_author_name( name_matches_person(inventor, display_name) for inventor in patent.inventors ) + or any( + name_matches_person(assignee, display_name) + for assignee in patent.assignees + ) ] @@ -265,13 +268,32 @@ def _given_name_matches(author: ParsedPersonName, inventor: ParsedPersonName) -> if not inventor.given_names: return False - primary = author.primary_given_name - if primary and any( - tokens_equal(primary, inventor_given, allow_initial=True) + # 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". + if any( + any( + tokens_equal(author_given, inventor_given, allow_initial=False) + for author_given in author.given_names + ) for inventor_given in inventor.given_names ): return True + inventor_tokens_full = [ + token for token in inventor.given_names + if _initial_letter(token) is None + ] + + # Prevent false positives like "Karem C Weber" for "Christian Weber": + # if inventor has full given-name tokens but none matches the author, + # we reject even if one initial overlaps. + if inventor_tokens_full: + return False + + # Initials-only inventor names (e.g. "C. Weber", "P. J. Marrón") + # are considered a match only when every initial maps to one of + # the author's given names. return all( any( tokens_equal(author_given, inventor_given, allow_initial=True) diff --git a/service/src/main/inse/patents/authors/test_identity.py b/service/src/main/inse/patents/authors/test_identity.py new file mode 100644 index 00000000..a4ac8a05 --- /dev/null +++ b/service/src/main/inse/patents/authors/test_identity.py @@ -0,0 +1,51 @@ +from inse.patents.authors.identity import ( + OPENALEX_FULL_NAME_COUNT_THRESHOLD, + OPENALEX_LAST_NAME_COUNT_THRESHOLD, + PATENT_HIT_COUNT_THRESHOLD, + is_ambiguous_name, +) + + +def test_mononym_is_always_ambiguous() -> None: + assert is_ambiguous_name("Weber") is True + assert is_ambiguous_name("") is True + assert is_ambiguous_name(None) is True + + +def test_two_token_name_not_ambiguous_without_signals() -> None: + assert is_ambiguous_name("Pedro Marrón") is False + + +def test_full_name_collision_makes_name_ambiguous() -> None: + assert ( + is_ambiguous_name( + "Christian Weber", + openalex_full_name_count=OPENALEX_FULL_NAME_COUNT_THRESHOLD, + ) + is True + ) + # A single OpenAlex author with that exact name is not a collision. + assert ( + is_ambiguous_name("Christian Weber", openalex_full_name_count=1) is False + ) + + +def test_last_name_collision_makes_name_ambiguous() -> None: + assert ( + is_ambiguous_name( + "Christian Weber", + openalex_last_name_count=OPENALEX_LAST_NAME_COUNT_THRESHOLD, + ) + is True + ) + assert ( + is_ambiguous_name("Christian Weber", openalex_last_name_count=10) is False + ) + + +def test_many_patent_hits_make_name_ambiguous() -> None: + assert ( + is_ambiguous_name("Christian Weber", patent_hit_count=PATENT_HIT_COUNT_THRESHOLD) + is True + ) + assert is_ambiguous_name("Christian Weber", patent_hit_count=5) is False diff --git a/service/src/main/inse/patents/authors/test_ipc_topic_matching.py b/service/src/main/inse/patents/authors/test_ipc_topic_matching.py new file mode 100644 index 00000000..60599cc5 --- /dev/null +++ b/service/src/main/inse/patents/authors/test_ipc_topic_matching.py @@ -0,0 +1,145 @@ +import numpy as np +import pytest + +from inse.patents.authors import ipc_topic_matching +from inse.patents.authors.ipc_topic_matching import ( + CONFLICT_SIMILARITY_THRESHOLD, + STRONG_SIMILARITY_THRESHOLD, + WEAK_SIMILARITY_THRESHOLD, + classification_description_labels, + match_patents_to_topics, + patent_topic_text, +) +from inse.patents.common import model + + +def _cluster_vector(label: str) -> np.ndarray: + vectors = { + "medical": np.array([1.0, 0.0, 0.0]), + "automotive": np.array([0.0, 1.0, 0.0]), + "wireless": np.array([0.95, 0.05, 0.0]), + } + vector = vectors[label] + return vector / np.linalg.norm(vector) + + +def _label_text(text: str) -> str: + lowered = text.lower() + if any(word in lowered for word in ("vehicle", "automotive", "tyre", "tire", "rubber tread")): + return "automotive" + if any(word in lowered for word in ("medical", "cardiac", "heart", "atherosclerosis")): + return "medical" + if any(word in lowered for word in ("wireless", "sensor", "network")): + return "wireless" + return "medical" + + +@pytest.fixture(autouse=True) +def mock_sentence_transformer(monkeypatch: pytest.MonkeyPatch) -> None: + def fake_encode(texts: list[str], normalize_embeddings: bool = True) -> np.ndarray: + return np.stack([_cluster_vector(_label_text(text)) for text in texts]) + + monkeypatch.setattr(ipc_topic_matching, "_encode_texts", fake_encode) + + +def _classification(**fields: str) -> model.IpcClassification: + return model.IpcClassification(symbol="A61B 5/00", **fields) + + +def _patent(**kwargs) -> model.PatentEntry: + return model.PatentEntry( + patent_id="EP1", + source="EPO", + **kwargs, + ) + + +def test_patent_topic_text_includes_title_abstract_and_classifications() -> None: + patent = _patent( + title="Vehicle pneumatic tyre and rubber mixture for a tread", + abstract="Pneumatic vehicle tire in radial design with profiled tread.", + ipc_descriptions=[ + _classification( + section="B - Performing operations; transporting", + ipc_class="B60 - Vehicles in general", + main_group="B60C - Tyres; tyre inflation", + ) + ], + ) + text = patent_topic_text(patent) + assert "Vehicle pneumatic tyre" in text + assert "Pneumatic vehicle tire" in text + assert "IPC/CPC:" in text + assert "Tyres" in text + assert "Vehicles in general" in text + + +def test_classification_description_labels_extracts_readable_names() -> None: + patent = _patent( + ipc_descriptions=[ + _classification( + section="A - Human necessities", + ipc_class="A61 - Medical science", + main_group="A61B 5/00 - Measuring for diagnostic purposes", + ) + ] + ) + labels = classification_description_labels(patent) + assert "Human necessities" in labels + assert "Medical science" in labels + assert "Measuring for diagnostic purposes" in labels + + +def test_match_patents_to_topics_strong_for_related_domain() -> None: + patent = _patent( + title="Cardiac arrhythmia monitoring system", + abstract="Heart rhythm monitoring for coronary artery disease.", + ipc_descriptions=[ + _classification( + section="A - Human necessities", + ipc_class="A61 - Medical or veterinary science", + ) + ], + ) + results = match_patents_to_topics( + [patent], + ["Cardiac arrhythmia and coronary artery disease"], + ) + assert results[0].level == "strong" + assert results[0].similarity >= STRONG_SIMILARITY_THRESHOLD + assert not results[0].topic_conflict + + +def test_match_patents_to_topics_conflict_for_unrelated_domain() -> None: + patent = _patent( + title="Vehicle pneumatic tyre and rubber mixture for a tread", + abstract="Automotive tire tread composition for pneumatic tyres.", + ipc_descriptions=[ + _classification( + section="B - Performing operations", + ipc_class="B60 - Vehicles", + main_group="B60C - Tyres", + ) + ], + ) + results = match_patents_to_topics( + [patent], + ["Cardiac arrhythmia and coronary artery disease"], + ) + assert results[0].topic_conflict + assert results[0].similarity < CONFLICT_SIMILARITY_THRESHOLD + + +def test_match_patents_without_author_topics_is_neutral() -> None: + patent = _patent( + title="Vehicle pneumatic tyre", + ipc_descriptions=[_classification(section="B60 - Vehicles")], + ) + results = match_patents_to_topics([patent], []) + assert results[0].level == "none" + assert not results[0].topic_conflict + + +def test_threshold_ordering() -> None: + assert CONFLICT_SIMILARITY_THRESHOLD <= WEAK_SIMILARITY_THRESHOLD + assert WEAK_SIMILARITY_THRESHOLD < STRONG_SIMILARITY_THRESHOLD diff --git a/service/src/main/inse/patents/authors/test_topic_filter.py b/service/src/main/inse/patents/authors/test_topic_filter.py new file mode 100644 index 00000000..bf8d79c0 --- /dev/null +++ b/service/src/main/inse/patents/authors/test_topic_filter.py @@ -0,0 +1,256 @@ +import numpy as np +import pytest + +from inse.models.openalex.author import Author +from inse.models.openalex.dehydrated_institution import DehydratedInstitution +from inse.models.openalex.work_topic import WorkTopic +from inse.patents.authors import ipc_topic_matching +from inse.patents.authors.ipc_topic_matching import TopicMatchResult +from inse.patents.authors.topic_filter import ( + decide_patent, + filter_patents_by_author_topics, + to_author_patent_entry, +) +from inse.patents.common import model + + +def _cluster_vector(label: str) -> np.ndarray: + vectors = { + "medical": np.array([1.0, 0.0, 0.0]), + "automotive": np.array([0.0, 1.0, 0.0]), + } + vector = vectors[label] + return vector / np.linalg.norm(vector) + + +def _label_text(text: str) -> str: + lowered = text.lower() + if any(word in lowered for word in ("vehicle", "automotive", "tyre", "tire")): + return "automotive" + return "medical" + + +@pytest.fixture(autouse=True) +def mock_sentence_transformer(monkeypatch: pytest.MonkeyPatch) -> None: + def fake_encode(texts: list[str], normalize_embeddings: bool = True) -> np.ndarray: + return np.stack([_cluster_vector(_label_text(text)) for text in texts]) + + monkeypatch.setattr(ipc_topic_matching, "_encode_texts", fake_encode) + + +def _author( + display_name: str, + *topics: str, + institutions: list[str] | None = None, +) -> Author: + return Author( + display_name=display_name, + topics=[ + WorkTopic(display_name=topic, score=1.0 - index * 0.1) + for index, topic in enumerate(topics) + ], + last_known_institutions=[ + DehydratedInstitution(display_name=name) + for name in (institutions or []) + ], + ) + + +def _tire_patent(*, inventors: list[str], assignees: list[str] | None = None) -> model.PatentEntry: + return model.PatentEntry( + patent_id="EP1", + source="EPO", + title="Vehicle pneumatic tyre and rubber mixture for a tread", + abstract="Automotive tire tread composition for pneumatic tyres.", + inventors=inventors, + assignees=assignees or [], + ipc_descriptions=[ + model.IpcClassification(symbol="B60C", ipc_class="B60 - Vehicles and tyres") + ], + ) + + +def _medical_patent(*, inventors: list[str], assignees: list[str] | None = None) -> model.PatentEntry: + return model.PatentEntry( + patent_id="EP2", + source="EPO", + title="Cardiac arrhythmia monitoring system", + abstract="Heart rhythm monitoring for coronary artery disease.", + inventors=inventors, + assignees=assignees or [], + ipc_descriptions=[ + model.IpcClassification(symbol="A61B", ipc_class="A61 - Medical or veterinary science") + ], + ) + + +# --- rare names: lenient ------------------------------------------------------ + +def test_rare_name_conflict_rejected() -> None: + author = _author("Xaver Uncommon", "Cardiac arrhythmia disorders") + patents = [_tire_patent(inventors=["Uncommon, Xaver"])] + filtered = filter_patents_by_author_topics(patents, author) + assert filtered == [] + + +def test_rare_name_related_topic_kept() -> None: + author = _author("Xaver Uncommon", "Cardiac arrhythmia disorders") + patents = [_medical_patent(inventors=["Uncommon, Xaver"])] + filtered = filter_patents_by_author_topics(patents, author) + assert len(filtered) == 1 + assert filtered[0].decision == "keep" + + +# --- common names: strict ----------------------------------------------------- + +def test_common_name_full_name_and_strong_topic_kept() -> None: + author = _author("Christian Weber", "Cardiac arrhythmia disorders") + patents = [_medical_patent(inventors=["Weber, Christian"])] + filtered = filter_patents_by_author_topics(patents, author, is_ambiguous=True) + assert len(filtered) == 1 + assert filtered[0].decision == "keep" + + +def test_common_name_initial_only_rejected_even_with_strong_topic() -> None: + author = _author("Christian Weber", "Cardiac arrhythmia disorders") + patents = [_medical_patent(inventors=["Weber, C."])] + filtered = filter_patents_by_author_topics(patents, author, is_ambiguous=True) + assert filtered == [] + + +def test_common_name_conflict_rejected_without_institution() -> None: + author = _author("Christian Weber", "Cardiac arrhythmia disorders") + patents = [_tire_patent(inventors=["Weber, Christian"])] + filtered = filter_patents_by_author_topics(patents, author, is_ambiguous=True) + assert filtered == [] + + +def test_common_name_institution_match_wins_over_conflict() -> None: + author = _author( + "Christian Weber", + "Cardiac arrhythmia disorders", + institutions=["Boston University"], + ) + patents = [ + _tire_patent(inventors=["Weber, C."], assignees=["Boston University"]) + ] + filtered = filter_patents_by_author_topics(patents, author, is_ambiguous=True) + assert len(filtered) == 1 + assert filtered[0].institution_match + assert filtered[0].decision == "keep" + + +# --- personal applicant (assignee) ------------------------------------------- + +def test_personal_assignee_match_keeps_patent_via_name_filter() -> None: + from inse.patents.authors.name_matching import filter_patents_by_author_name + + display_name = "Pedro José Marrón" + patent = model.PatentEntry( + patent_id="EP2867692", + source="EPO", + title="Method for generating and using a map", + abstract="Indoor localization map for wireless sensor networks.", + inventors=["Someone Else"], + assignees=["Marrón, Pedro José, Dr."], + ipc_descriptions=[ + model.IpcClassification(symbol="H04W", ipc_class="H04W - Wireless networks") + ], + ) + # Name filter keeps it because the person is the applicant. + assert filter_patents_by_author_name([patent], display_name) == [patent] + + +def test_personal_assignee_is_strong_identity_signal() -> None: + author = _author( + "Pedro José Marrón", + "Energy Efficient Wireless Sensor Networks", + ) + patent = model.PatentEntry( + patent_id="EP2867692", + source="EPO", + title="Method for generating and using a map", + abstract="Indoor localization map for wireless sensor networks.", + inventors=["Someone Else"], + assignees=["Marrón, Pedro José, Dr."], + ipc_descriptions=[ + model.IpcClassification(symbol="H04W", ipc_class="H04W - Wireless networks") + ], + ) + filtered = filter_patents_by_author_topics([patent], author) + assert len(filtered) == 1 + assert filtered[0].personal_assignee_match + assert filtered[0].decision == "keep" + + +# --- fallback topics ---------------------------------------------------------- + +def test_fallback_topics_enable_conflict_detection() -> None: + author = _author("Xaver Uncommon") # no topics on author document + patents = [_tire_patent(inventors=["Uncommon, Xaver"])] + + without_fallback = filter_patents_by_author_topics(patents, author) + assert len(without_fallback) == 1 # cannot judge topic -> lenient keep + + with_fallback = filter_patents_by_author_topics( + patents, + author, + fallback_topic_names=["Cardiac arrhythmia disorders"], + ) + assert with_fallback == [] # fallback reveals the conflict + + +# --- decision unit tests ------------------------------------------------------ + +def _match(level: str, conflict: bool) -> TopicMatchResult: + return TopicMatchResult(level=level, similarity=0.9, topic_conflict=conflict) + + +def test_decide_common_requires_strong_identity() -> None: + assert decide_patent( + is_common=True, + name_match="full", + institution_match=False, + topic_match=_match("weak", False), + can_judge_topic=True, + ) == "reject" + + assert decide_patent( + is_common=True, + name_match="full", + institution_match=False, + topic_match=_match("strong", False), + can_judge_topic=True, + ) == "keep" + + +def test_decide_institution_always_keeps() -> None: + assert decide_patent( + is_common=True, + name_match="initial", + institution_match=True, + topic_match=_match("none", True), + can_judge_topic=True, + ) == "keep" + + +def test_decide_rare_without_topic_judgement_keeps() -> None: + assert decide_patent( + is_common=False, + name_match="initial", + institution_match=False, + topic_match=_match("none", False), + can_judge_topic=False, + ) == "weaken" + + +# --- response mapping --------------------------------------------------------- + +def test_to_author_patent_entry_exposes_topic_metadata() -> None: + author = _author("Christian Weber", "Cardiac arrhythmia disorders") + patents = [_medical_patent(inventors=["Weber, Christian"])] + filtered = filter_patents_by_author_topics(patents, author)[0] + entry = to_author_patent_entry(filtered) + assert entry.topic_match_level == "strong" + assert entry.topic_filter_decision == "keep" + assert entry.topic_similarity is not None diff --git a/service/src/main/inse/patents/authors/topic_filter.py b/service/src/main/inse/patents/authors/topic_filter.py new file mode 100644 index 00000000..49787fd0 --- /dev/null +++ b/service/src/main/inse/patents/authors/topic_filter.py @@ -0,0 +1,221 @@ +"""Attribute name-matched patents to a person using identity + topic signals. + +Identity signals (institution/assignee match, full given-name match) decide +*whether the patent belongs to the person*. IPC/CPC topic similarity is only a +supporting plausibility signal. The gating is adaptive: + +- rare names: lenient (only clear topic conflicts are dropped) +- common names: strict (a strong identity signal is required) +""" +from __future__ import annotations + +from dataclasses import dataclass +from typing import Literal + +from inse.models.openalex.author import Author +from inse.patents.authors.identity import ( + author_institution_names, + best_name_match_kind, + patent_institution_match, + patent_personal_assignee_match, +) +from inse.patents.authors.ipc_topic_matching import ( + TopicMatchResult, + author_topic_names, + match_patents_to_topics, + patent_has_topic_signal, +) +from inse.patents.common import model + +TopicFilterDecision = Literal["keep", "weaken", "reject"] +NameMatchKind = Literal["full", "initial", "none"] + + +@dataclass(frozen=True) +class FilteredPatent: + patent: model.PatentEntry + topic_match: TopicMatchResult + decision: TopicFilterDecision + name_match: NameMatchKind + institution_match: bool + personal_assignee_match: bool = False + + +def decide_patent( + *, + is_common: bool, + name_match: NameMatchKind, + institution_match: bool, + topic_match: TopicMatchResult, + can_judge_topic: bool, + personal_assignee_match: bool = False, +) -> TopicFilterDecision: + topic_conflict = topic_match.topic_conflict if can_judge_topic else False + topic_strong = (topic_match.level == "strong") if can_judge_topic else False + + # Institution/assignee overlap or the person being the personal applicant + # are the strongest identity signals we have. + if institution_match or personal_assignee_match: + return "keep" + + if is_common: + # Common names need a strong identity signal. A full given-name match + # together with a clearly matching research field is the minimum. + if name_match == "full" and topic_strong: + return "keep" + return "reject" + + # Rare names: lenient. Only drop clear thematic conflicts. + if topic_conflict: + return "reject" + if topic_strong or name_match == "full": + return "keep" + return "weaken" + + +def resolve_topic_names( + author: Author, + fallback_topic_names: list[str] | None = None, +) -> list[str]: + topic_names = author_topic_names(author) + if topic_names: + return topic_names + if fallback_topic_names: + return [name for name in fallback_topic_names if name and name.strip()] + return [] + + +_NEUTRAL_TOPIC = TopicMatchResult(level="none", similarity=0.0, topic_conflict=False) + + +def _needs_topic_judgement( + *, + is_common: bool, + name_match: NameMatchKind, + strong_identity: bool, + can_judge_topic: bool, +) -> bool: + # A strong identity signal already decides "keep" without the topic. + if strong_identity: + return False + if not can_judge_topic: + return False + if is_common: + # Common names are only rescued by (full name + strong topic); + # without a full name they are rejected regardless of topic. + return name_match == "full" + # Rare names always consult the topic (conflict / strong check). + return True + + +def filter_patents_by_author_topics( + patents: list[model.PatentEntry], + author: Author, + *, + is_ambiguous: bool = False, + fallback_topic_names: list[str] | None = None, +) -> list[FilteredPatent]: + topic_names = resolve_topic_names(author, fallback_topic_names) + common_name = is_ambiguous + institution_names = author_institution_names(author) + display_name = author.display_name or "" + has_author_topics = bool(topic_names) + + # Pre-compute the cheap identity signals so we only run the expensive + # sentence-transformer encoding for patents whose decision truly depends + # on the research topic. + signals = [] + patents_to_encode: list[model.PatentEntry] = [] + for patent in patents: + name_match = best_name_match_kind(patent, display_name) + 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 + can_judge_topic = has_author_topics and patent_has_topic_signal(patent) + + needs_topic = _needs_topic_judgement( + is_common=common_name, + name_match=name_match, + strong_identity=strong_identity, + can_judge_topic=can_judge_topic, + ) + if needs_topic: + patents_to_encode.append(patent) + signals.append( + (name_match, institution_match, personal_assignee_match, can_judge_topic, needs_topic) + ) + + topic_by_patent_id = {} + if patents_to_encode: + encoded_matches = match_patents_to_topics(patents_to_encode, topic_names) + topic_by_patent_id = { + id(patent): match + for patent, match in zip(patents_to_encode, encoded_matches) + } + + filtered: list[FilteredPatent] = [] + for patent, signal in zip(patents, signals): + name_match, institution_match, personal_assignee_match, can_judge_topic, needs_topic = signal + topic_match = topic_by_patent_id.get(id(patent), _NEUTRAL_TOPIC) if needs_topic else _NEUTRAL_TOPIC + + decision = decide_patent( + is_common=common_name, + name_match=name_match, + institution_match=institution_match, + personal_assignee_match=personal_assignee_match, + topic_match=topic_match, + can_judge_topic=can_judge_topic and needs_topic, + ) + if decision == "reject": + continue + filtered.append( + FilteredPatent( + patent=patent, + topic_match=topic_match, + decision=decision, + name_match=name_match, + institution_match=institution_match, + personal_assignee_match=personal_assignee_match, + ) + ) + + filtered.sort( + key=lambda item: ( + item.decision != "keep", + not (item.institution_match or item.personal_assignee_match), + -item.topic_match.similarity, + item.patent.publication_date or "", + ), + ) + return filtered + + +def to_author_patent_entry(filtered: FilteredPatent) -> model.AuthorPatentEntry: + return model.AuthorPatentEntry( + **filtered.patent.model_dump(), + topic_similarity=filtered.topic_match.similarity or None, + topic_match_level=_response_match_level(filtered), + topic_filter_decision=( + "keep" if filtered.decision == "keep" else "weaken" + ), + ) + + +def patent_from_filtered(entry: model.AuthorPatentEntry) -> model.PatentEntry: + return model.PatentEntry( + **entry.model_dump( + exclude={ + "topic_similarity", + "topic_match_level", + "topic_filter_decision", + } + ) + ) + + +def _response_match_level(filtered: FilteredPatent) -> model.TopicMatchLevel: + if filtered.decision == "keep": + return "strong" + if filtered.decision == "weaken": + return "weak" + return "unknown" diff --git a/service/src/main/inse/patents/common/model.py b/service/src/main/inse/patents/common/model.py index b3cc97a4..783f6189 100644 --- a/service/src/main/inse/patents/common/model.py +++ b/service/src/main/inse/patents/common/model.py @@ -1,3 +1,5 @@ +from typing import Literal + from pydantic import BaseModel, ConfigDict, Field @@ -34,11 +36,21 @@ class PatentEntry(BaseModel): country: str | None = None +TopicMatchLevel = Literal["strong", "weak", "unknown"] +TopicFilterDecision = Literal["keep", "weaken"] + + +class AuthorPatentEntry(PatentEntry): + topic_similarity: float | None = None + topic_match_level: TopicMatchLevel | None = None + topic_filter_decision: TopicFilterDecision | None = None + + class PatentsByAuthorResponse(BaseModel): author_id: str author_name: str | None = None patent_count: int - patents: list[PatentEntry] + patents: list[AuthorPatentEntry] class PatentsByInstitutionResponse(BaseModel): diff --git a/service/src/main/inse/patents/org/logic.py b/service/src/main/inse/patents/org/logic.py index ad77a79e..67f0175e 100644 --- a/service/src/main/inse/patents/org/logic.py +++ b/service/src/main/inse/patents/org/logic.py @@ -12,7 +12,9 @@ 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.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 ( @@ -225,6 +227,7 @@ def fetch_authors_for_institution(institution_id: str) -> list[Author]: async def _search_patents_by_author( author: Author, search_client: PatentSearchClient, + ipc_client: IpcSearchClient, ) -> list[PatentEntry]: author_name = author.display_name if not author_name: @@ -250,7 +253,35 @@ async def _search_patents_by_author( patents = parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data) patents = deduplicate_patents(patents) - return filter_patents_by_author_name(patents, author_name) + patent_hit_count = len(patents) + name_matched = filter_patents_by_author_name(patents, author_name) + if not name_matched: + return [] + + await enrich_patents_classifications(name_matched, ipc_client) + + from inse.persons import logic as person_logic + + # Ambiguity is derived only from existing project data. + full_name_count = await person_logic.count_authors_by_display_name(author_name) + is_ambiguous = is_ambiguous_name( + author_name, + patent_hit_count=patent_hit_count, + openalex_full_name_count=full_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] async def build_org_patents_for_institution( @@ -288,7 +319,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, patent_client) + patents = await _search_patents_by_author(author, patent_client, ipc_search_client) return author, patents author_results = await asyncio.gather( diff --git a/service/src/main/inse/patents/test_name_matching.py b/service/src/main/inse/patents/test_name_matching.py index 1c086842..92af655f 100644 --- a/service/src/main/inse/patents/test_name_matching.py +++ b/service/src/main/inse/patents/test_name_matching.py @@ -132,6 +132,7 @@ def test_first_name_match_kind() -> None: ("López, Juan", "Juan Carlos García López", True), ("Mohamed Ali Hassan", "Mohamed Ali Hassan", True), ("Ali Hassan", "Mohamed Ali Hassan", True), + ("Karem C Weber", "Christian Weber", False), ], ) def test_name_matches_person_multi_part( diff --git a/service/src/main/inse/persons/logic.py b/service/src/main/inse/persons/logic.py index baeded67..754f3fa1 100644 --- a/service/src/main/inse/persons/logic.py +++ b/service/src/main/inse/persons/logic.py @@ -153,6 +153,40 @@ async def search_persons( return AuthorsListResponse(results=authors, meta=Meta(count=len(authors))) +async def _count_authors(query: dict) -> int: + """Return the total number of authors matching a query (no documents fetched).""" + data = await elasticsearch.search( + index=ESIndex.OPENALEX_AUTHORS, + query=query, + size=0, + track_total_hits=True, + ) + total = data.get("hits", {}).get("total", {}) + if isinstance(total, dict): + return int(total.get("value", 0)) + return int(total or 0) + + +async def count_authors_by_display_name(display_name: str) -> int: + """Count authors in the local OpenAlex index whose full name collides. + + Used purely as an internal ambiguity signal: a value >= 2 means at least one + other author shares the exact name. + """ + if not display_name or not display_name.strip(): + return 0 + query = {"match_phrase": {"display_name": display_name.strip()}} + return await _count_authors(query) + + +async def count_authors_by_last_name(last_name: str) -> int: + """Count authors in the local OpenAlex index sharing a family name.""" + if not last_name or not last_name.strip(): + return 0 + query = {"match": {"display_name": last_name.strip()}} + return await _count_authors(query) + + async def _fetch_author_display_name(author_id: str) -> Optional[str]: query = { @@ -249,6 +283,24 @@ async def _fetch_works_and_topics(author_id: str) -> tuple[list, list]: return works, topics +async def get_topic_names_for_author(author_id: str) -> list[str]: + """Return the author's primary research topic names from the works aggregation. + + Used as a fallback when the author document has no populated ``topics`` field. + """ + short_id = author_id.replace("https://openalex.org/", "").strip() + try: + _works, topics = await _fetch_works_and_topics(short_id) + except Exception as exc: # noqa: BLE001 + logger.warning("Failed to fetch fallback topics for author %s: %s", short_id, exc) + return [] + return [ + topic["display_name"] + for topic in topics + if topic.get("display_name") + ] + + async def _get_publication_years_for_author(author_id: str) -> list[int]: author_url = f"https://openalex.org/{author_id.strip()}" diff --git a/webapp/src/app/api/model/patentEntry.ts b/webapp/src/app/api/model/patentEntry.ts index 5565ab9a..f7f2f2df 100644 --- a/webapp/src/app/api/model/patentEntry.ts +++ b/webapp/src/app/api/model/patentEntry.ts @@ -32,3 +32,12 @@ export interface PatentEntry { country?: string | null; } +export type TopicMatchLevel = 'strong' | 'weak' | 'unknown'; +export type TopicFilterDecision = 'keep' | 'weaken'; + +export interface AuthorPatentEntry extends PatentEntry { + topic_similarity?: number | null; + topic_match_level?: TopicMatchLevel | null; + topic_filter_decision?: TopicFilterDecision | null; +} + diff --git a/webapp/src/app/api/model/patentsByAuthorResponse.ts b/webapp/src/app/api/model/patentsByAuthorResponse.ts index 622d3920..70eef4bc 100644 --- a/webapp/src/app/api/model/patentsByAuthorResponse.ts +++ b/webapp/src/app/api/model/patentsByAuthorResponse.ts @@ -7,12 +7,12 @@ * https://openapi-generator.tech * Do not edit the class manually. */ -import { PatentEntry } from './patentEntry'; +import { AuthorPatentEntry } from './patentEntry'; export interface PatentsByAuthorResponse { author_id: string; author_name?: string | null; patent_count: number; - patents: Array; + patents: Array; } diff --git a/webapp/src/app/modules/person-patents/person-patents.component.ts b/webapp/src/app/modules/person-patents/person-patents.component.ts index 1af39c0f..8d9b20c9 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.ts +++ b/webapp/src/app/modules/person-patents/person-patents.component.ts @@ -1,194 +1,194 @@ -import { Component, OnInit, inject } from '@angular/core'; -import { CommonModule } from '@angular/common'; -import { ActivatedRoute, Router } from '@angular/router'; -import { PatentsService } from '../../api/api/patents.service'; -import { PatentEntry } from '../../api/model/patentEntry'; -import { - formatPatentDate, - getPublicationStageLabel, -} from '../patent-detail/patent-detail.utils'; - -type SortMode = 'date' | 'title'; -type SourceFilter = 'all' | 'EPO' | 'USPTO'; - -@Component({ - selector: 'app-person-patents', - imports: [CommonModule], - templateUrl: './person-patents.component.html', - styleUrl: './person-patents.component.scss', -}) -export class PersonPatentsComponent implements OnInit { - private route = inject(ActivatedRoute); - private router = inject(Router); - private patentsApi = inject(PatentsService); - - patents: PatentEntry[] = []; - filteredPatents: PatentEntry[] = []; - authorName: string | null = null; - selectedPatent: PatentEntry | null = null; - - loading = true; - error = false; - - activeFilter: SourceFilter = 'all'; - sortMode: SortMode = 'date'; - - selectedPage = 1; - readonly pageSize = 10; - - ngOnInit(): void { - this.route.parent?.paramMap.subscribe((params) => { - const authorId = params.get('id') ?? ''; - - const filterFromUrl = this.route.snapshot.queryParamMap.get('filter'); - const sortFromUrl = this.route.snapshot.queryParamMap.get('sortBy'); - - if (this.isValidFilter(filterFromUrl)) { - this.activeFilter = filterFromUrl; - } - if (this.isValidSortMode(sortFromUrl)) { - this.sortMode = sortFromUrl; - } - - if (authorId) { - this.patentsApi.getPatentsByAuthor(authorId, 'body').subscribe({ - next: (result) => { - this.patents = result.patents ?? []; - this.authorName = result.author_name ?? null; - this.applyFilter(); - this.loading = false; - }, - error: () => { - this.error = true; - this.loading = false; - }, - }); - } - }); - } - - setFilter(filter: SourceFilter): void { - this.activeFilter = filter; - this.selectedPage = 1; - this.selectedPatent = null; - this.applyFilter(); - this.updateQueryParams(); - } - - setSortMode(sortMode: SortMode): void { - this.sortMode = sortMode; - this.applyFilter(); - this.updateQueryParams(); - } - - selectPatent(patent: PatentEntry): void { - this.selectedPatent = patent; - this.updateQueryParams(); - } - - openDetail(): void { - if (!this.selectedPatent) return; - this.router.navigate(['/patent', this.selectedPatent.patent_id]); - } - - private applyFilter(): void { - let patents = this.patents; - - if (this.activeFilter !== 'all') { - patents = patents.filter((p) => p.source === this.activeFilter); - } - - this.filteredPatents = this.sortPatents(patents); - } - - private sortPatents(patents: PatentEntry[]): PatentEntry[] { - return [...patents].sort((a, b) => { - if (this.sortMode === 'date') { - return (b.publication_date ?? '').localeCompare( - a.publication_date ?? '', - ); - } - return (a.title ?? '').localeCompare(b.title ?? '', 'de', { - sensitivity: 'base', - }); - }); - } - - private updateQueryParams(): void { - this.router.navigate([], { - relativeTo: this.route, - queryParams: { - filter: this.activeFilter, - sortBy: this.sortMode, - }, - queryParamsHandling: 'merge', - replaceUrl: true, - }); - } - - private isValidFilter(value: string | null): value is SourceFilter { - return value === 'all' || value === 'EPO' || value === 'USPTO'; - } - - private isValidSortMode(value: string | null): value is SortMode { - return value === 'date' || value === 'title'; - } - - getPagedPatents(): PatentEntry[] { - const start = (this.selectedPage - 1) * this.pageSize; - return this.filteredPatents.slice(start, start + this.pageSize); - } - - getPageCount(): number { - return Math.max(1, Math.ceil(this.filteredPatents.length / this.pageSize)); - } - - hasPagination(): boolean { - return this.getPageCount() > 1; - } - - setPage(page: number): void { - this.selectedPage = Math.min(Math.max(page, 1), this.getPageCount()); - this.updateQueryParams(); - } - - formatDate(date: string | null | undefined): string { - return formatPatentDate(date); - } - - getEpoCount(): number { - return this.patents.filter((p) => p.source === 'EPO').length; - } - - getUsptoCount(): number { - return this.patents.filter((p) => p.source === 'USPTO').length; - } - - trackPatent(_index: number, patent: PatentEntry): string { - return [ - patent.source, - patent.patent_id, - patent.publication_date ?? '', - patent.kind ?? patent.application_type ?? '', - ].join('|'); - } - - getAbstractPreview(abstract: string | null | undefined): string | null { - if (!abstract?.trim()) { - return null; - } - const text = abstract.trim(); - if (text.length <= 160) { - return text; - } - return `${text.slice(0, 160).trimEnd()}…`; - } - - getPublicationStageLabel(patent: PatentEntry): string | null { - return getPublicationStageLabel(patent); - } - - getEmptyMessage(): string { - return 'Keine Patente gefunden.'; - } -} +import { Component, OnInit, inject } from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { ActivatedRoute, Router } from '@angular/router'; +import { PatentsService } from '../../api/api/patents.service'; +import { AuthorPatentEntry } from '../../api/model/patentEntry'; +import { + formatPatentDate, + getPublicationStageLabel, +} from '../patent-detail/patent-detail.utils'; + +type SortMode = 'date' | 'title'; +type SourceFilter = 'all' | 'EPO' | 'USPTO'; + +@Component({ + selector: 'app-person-patents', + imports: [CommonModule], + templateUrl: './person-patents.component.html', + styleUrl: './person-patents.component.scss', +}) +export class PersonPatentsComponent implements OnInit { + private route = inject(ActivatedRoute); + private router = inject(Router); + private patentsApi = inject(PatentsService); + + patents: AuthorPatentEntry[] = []; + filteredPatents: AuthorPatentEntry[] = []; + authorName: string | null = null; + selectedPatent: AuthorPatentEntry | null = null; + + loading = true; + error = false; + + activeFilter: SourceFilter = 'all'; + sortMode: SortMode = 'date'; + + selectedPage = 1; + readonly pageSize = 10; + + ngOnInit(): void { + this.route.parent?.paramMap.subscribe((params) => { + const authorId = params.get('id') ?? ''; + + const filterFromUrl = this.route.snapshot.queryParamMap.get('filter'); + const sortFromUrl = this.route.snapshot.queryParamMap.get('sortBy'); + + if (this.isValidFilter(filterFromUrl)) { + this.activeFilter = filterFromUrl; + } + if (this.isValidSortMode(sortFromUrl)) { + this.sortMode = sortFromUrl; + } + + if (authorId) { + this.patentsApi.getPatentsByAuthor(authorId, 'body').subscribe({ + next: (result) => { + this.patents = result.patents ?? []; + this.authorName = result.author_name ?? null; + this.applyFilter(); + this.loading = false; + }, + error: () => { + this.error = true; + this.loading = false; + }, + }); + } + }); + } + + setFilter(filter: SourceFilter): void { + this.activeFilter = filter; + this.selectedPage = 1; + this.selectedPatent = null; + this.applyFilter(); + this.updateQueryParams(); + } + + setSortMode(sortMode: SortMode): void { + this.sortMode = sortMode; + this.applyFilter(); + this.updateQueryParams(); + } + + selectPatent(patent: AuthorPatentEntry): void { + this.selectedPatent = patent; + this.updateQueryParams(); + } + + openDetail(): void { + if (!this.selectedPatent) return; + this.router.navigate(['/patent', this.selectedPatent.patent_id]); + } + + private applyFilter(): void { + let patents = this.patents; + + if (this.activeFilter !== 'all') { + patents = patents.filter((p) => p.source === this.activeFilter); + } + + this.filteredPatents = this.sortPatents(patents); + } + + private sortPatents(patents: AuthorPatentEntry[]): AuthorPatentEntry[] { + return [...patents].sort((a, b) => { + if (this.sortMode === 'date') { + return (b.publication_date ?? '').localeCompare( + a.publication_date ?? '', + ); + } + return (a.title ?? '').localeCompare(b.title ?? '', 'de', { + sensitivity: 'base', + }); + }); + } + + private updateQueryParams(): void { + this.router.navigate([], { + relativeTo: this.route, + queryParams: { + filter: this.activeFilter, + sortBy: this.sortMode, + }, + queryParamsHandling: 'merge', + replaceUrl: true, + }); + } + + private isValidFilter(value: string | null): value is SourceFilter { + return value === 'all' || value === 'EPO' || value === 'USPTO'; + } + + private isValidSortMode(value: string | null): value is SortMode { + return value === 'date' || value === 'title'; + } + + getPagedPatents(): AuthorPatentEntry[] { + const start = (this.selectedPage - 1) * this.pageSize; + return this.filteredPatents.slice(start, start + this.pageSize); + } + + getPageCount(): number { + return Math.max(1, Math.ceil(this.filteredPatents.length / this.pageSize)); + } + + hasPagination(): boolean { + return this.getPageCount() > 1; + } + + setPage(page: number): void { + this.selectedPage = Math.min(Math.max(page, 1), this.getPageCount()); + this.updateQueryParams(); + } + + formatDate(date: string | null | undefined): string { + return formatPatentDate(date); + } + + getEpoCount(): number { + return this.patents.filter((p) => p.source === 'EPO').length; + } + + getUsptoCount(): number { + return this.patents.filter((p) => p.source === 'USPTO').length; + } + + trackPatent(_index: number, patent: AuthorPatentEntry): string { + return [ + patent.source, + patent.patent_id, + patent.publication_date ?? '', + patent.kind ?? patent.application_type ?? '', + ].join('|'); + } + + getAbstractPreview(abstract: string | null | undefined): string | null { + if (!abstract?.trim()) { + return null; + } + const text = abstract.trim(); + if (text.length <= 160) { + return text; + } + return `${text.slice(0, 160).trimEnd()}…`; + } + + getPublicationStageLabel(patent: AuthorPatentEntry): string | null { + return getPublicationStageLabel(patent); + } + + getEmptyMessage(): string { + return 'Keine Patente gefunden.'; + } +}