ts-136-patent-to-researchers-v2 #260

Merged
khalti merged 4 commits from ts-136-patent-to-researchers-v2 into dev 2026-08-04 10:40:33 +02:00
16 changed files with 559 additions and 1319 deletions
+14 -448
View File
@@ -1,4 +1,4 @@
"""Find patents for extracted OpenAlex keywords via patents_openalex_keywords index."""
"""Find patents for extracted OpenAlex keywords via IPC/CPC reverse lookup."""
from __future__ import annotations
import asyncio
@@ -31,7 +31,6 @@ from inse.patents.ipc_lookup import (
)
from inse.patents.ipc_search_client import IpcSearchClient
from inse.patents.keywords.model import (
KeywordEvidence,
KeywordPatentMappingStatus,
KeywordPatentMatch,
KeywordPatentSearchDiagnostics,
@@ -76,13 +75,7 @@ _MIN_LEADER_RELATIVE_MASS = 0.20
_MIN_LEADER_MASS_RATIO = 1.5
_TARGET_CUMULATIVE_CLUSTER_MASS = 0.75
_MIN_PATENT_MATCH_SCORE = 0.50
_MIN_TEXT_PATENT_MATCH_SCORE = 0.30
_DEFAULT_SCORE_WEIGHTS = {"ipc": 0.60, "topic": 0.25, "text": 0.15}
# When IPC mapping is abstained, score only topic + text evidence.
_TEXT_SCORE_WEIGHTS = {"ipc": 0.0, "topic": 0.45, "text": 0.55}
# Also try title/abstract search when IPC mapping produced terms but scoring
# returned no patents (empty retrieval or over-filtering).
_TEXT_SEARCH_AFTER_EMPTY_IPC = True
_TOPIC_SCORE_TOPIC_ID = 1.0
_TOPIC_SCORE_SUBFIELD = 0.7
_TOPIC_SCORE_COMPATIBLE_FIELD = 0.3
@@ -618,12 +611,6 @@ class TopicEvidence:
score: float
@dataclass(frozen=True)
class TextGateDecision:
accepted: bool
reason: str
def _compute_topic_evidence(
patent_topics: list[MappedOpenAlexTopic],
keyword_topic_ids: frozenset[str],
@@ -702,16 +689,6 @@ def _tokenize_words(text: str) -> list[str]:
return re.findall(r"[a-z0-9äöüß]+", (text or "").casefold())
def _contains_token_sequence(haystack: list[str], needle: list[str]) -> bool:
if not needle or len(needle) > len(haystack):
return False
width = len(needle)
for index in range(len(haystack) - width + 1):
if haystack[index : index + width] == needle:
return True
return False
def _token_set(tokens: list[str]) -> set[str]:
return set(tokens)
@@ -735,23 +712,6 @@ def _text_search_terms(items: list[KeywordPatentSearchItem]) -> list[str]:
return terms
def _text_search_phrases(items: list[KeywordPatentSearchItem]) -> list[str]:
"""Full phrases for ES title/abstract retrieval (text path)."""
phrases: list[str] = []
seen: set[str] = set()
for item in items:
for value in (item.keyword, item.topic_display_name):
cleaned = " ".join((value or "").strip().split())
if len(cleaned) < 3:
continue
key = cleaned.casefold()
if key in seen:
continue
seen.add(key)
phrases.append(cleaned)
return phrases
def _text_overlap_score(
patent: model.PatentEntry,
search_terms: list[str],
@@ -772,173 +732,6 @@ def _text_overlap_score(
return min(hits / 3, 1.0)
def _text_match_kind(
*,
phrase_in_title: bool,
phrase_in_abstract: bool,
full_token_match: bool,
partial_token_match: bool,
) -> str:
if phrase_in_title:
return "phrase_title"
if phrase_in_abstract:
return "phrase_abstract"
if full_token_match:
return "full_token"
if partial_token_match:
return "partial_token"
return "none"
def _collect_keyword_text_evidence(
patent: model.PatentEntry,
phrases: list[str],
search_terms: list[str],
) -> KeywordEvidence:
"""Record phrase / full-token / partial-token evidence separately."""
title_tokens = _tokenize_words(patent.title or "")
abstract_tokens = _tokenize_words(patent.abstract or "")
combined_tokens = _token_set(title_tokens + abstract_tokens)
phrase_in_title = False
phrase_in_abstract = False
full_token_match = False
partial_token_match = False
matched_phrases: list[str] = []
for phrase in phrases:
phrase_tokens = _tokenize_words(phrase)
if not phrase_tokens:
continue
if _contains_token_sequence(title_tokens, phrase_tokens):
phrase_in_title = True
matched_phrases.append(phrase)
elif _contains_token_sequence(abstract_tokens, phrase_tokens):
phrase_in_abstract = True
matched_phrases.append(phrase)
present = [token for token in phrase_tokens if token in combined_tokens]
if present and len(present) == len(phrase_tokens):
full_token_match = True
elif present:
partial_token_match = True
matched_words = [term for term in search_terms if term in combined_tokens]
if matched_words and not full_token_match and not partial_token_match:
# Lone search-term hits without a covering phrase count as partial.
partial_token_match = True
word_match_score = (
min(len(matched_words) / 3, 1.0) if search_terms and matched_words else 0.0
)
kind = _text_match_kind(
phrase_in_title=phrase_in_title,
phrase_in_abstract=phrase_in_abstract,
full_token_match=full_token_match,
partial_token_match=partial_token_match,
)
return KeywordEvidence(
phrase_in_title=phrase_in_title,
phrase_in_abstract=phrase_in_abstract,
full_token_match=full_token_match,
partial_token_match=partial_token_match,
word_match_score=round(word_match_score, 4),
matched_phrases=list(dict.fromkeys(matched_phrases)),
matched_words=matched_words,
text_match_kind=kind,
)
def _keyword_text_score(evidence: KeywordEvidence) -> float:
if evidence.phrase_in_title:
return 1.0
if evidence.phrase_in_abstract:
return 0.85
if evidence.full_token_match:
return 0.55
if evidence.partial_token_match:
return 0.25
return 0.0
def _exact_topic_or_subfield_match(
patent_topics: list[MappedOpenAlexTopic],
keyword_topic_ids: frozenset[str],
keyword_subfield_names: frozenset[str],
) -> bool:
evidence = _compute_topic_evidence(
patent_topics,
keyword_topic_ids,
keyword_subfield_names,
frozenset(),
)
return evidence.match_kind in {"topic_id", "subfield"}
def _keyword_text_passes_relevance_gate(
evidence: KeywordEvidence,
*,
topic_evidence: TopicEvidence,
) -> TextGateDecision:
"""Keyword text acceptance policy (no domain hardcoding).
Accept:
- phrase in title (strong)
- phrase in abstract (medium)
- exact topic/subfield together with full token text evidence
Reject:
- partial/general words alone
- compatible field alone
- exact topic/subfield without text evidence
"""
exact = topic_evidence.match_kind in {"topic_id", "subfield"}
if evidence.phrase_in_title:
return TextGateDecision(True, "phrase_in_title")
if evidence.phrase_in_abstract:
return TextGateDecision(True, "phrase_in_abstract")
if exact and evidence.full_token_match:
return TextGateDecision(
True,
f"{topic_evidence.match_kind}_with_full_token_match",
)
if exact and evidence.partial_token_match:
return TextGateDecision(False, "exact_topic_with_partial_tokens_only")
if exact:
return TextGateDecision(False, "exact_topic_without_text")
if topic_evidence.match_kind == "compatible_field":
return TextGateDecision(False, "compatible_field_only")
if evidence.partial_token_match or evidence.matched_words:
return TextGateDecision(False, "partial_or_loose_words_only")
return TextGateDecision(False, "insufficient_evidence")
def _matched_keyword_labels_from_evidence(
items: list[KeywordPatentSearchItem],
evidence: KeywordEvidence,
) -> list[str]:
matched: list[str] = []
seen: set[str] = set()
phrase_keys = {phrase.casefold() for phrase in evidence.matched_phrases}
word_keys = set(evidence.matched_words)
for item in items:
for value in (item.keyword, item.topic_display_name):
label = (value or "").strip()
if not label:
continue
key = label.casefold()
if key in seen:
continue
label_tokens = _tokenize_words(label)
if key in phrase_keys or any(token in word_keys for token in label_tokens):
seen.add(key)
matched.append(label)
break
return matched
def _patent_passes_relevance_gate(
patent_topics: list[MappedOpenAlexTopic],
*,
@@ -1261,210 +1054,6 @@ async def _score_patents_with_ipc(
}
async def _score_patents_text_search(
*,
raw_patents: list[model.PatentEntry],
search_keywords: list[KeywordPatentSearchItem],
phrases: list[str],
text_search_terms: list[str],
keyword_topic_ids: frozenset[str],
keyword_subfield_names: frozenset[str],
keyword_soft_field_names: frozenset[str],
resolver: PatentOpenAlexMappingResolver,
) -> tuple[list[KeywordPatentMatch], dict[str, int]]:
"""Score patents without IPC using graded topic + structured text evidence."""
patent_topics_by_key = await resolver.resolve_topics_for_patents(raw_patents)
scored: list[KeywordPatentMatch] = []
filtered_by_relevance_gate = 0
filtered_by_min_score = 0
passed_relevance_gate = 0
for patent in raw_patents:
patent_topics = patent_topics_by_key.get(patent_map_key(patent), [])
evidence = _collect_keyword_text_evidence(patent, phrases, text_search_terms)
topic_evidence = _compute_topic_evidence(
patent_topics,
keyword_topic_ids,
keyword_subfield_names,
keyword_soft_field_names,
)
decision = _keyword_text_passes_relevance_gate(
evidence,
topic_evidence=topic_evidence,
)
if not decision.accepted:
filtered_by_relevance_gate += 1
logger.info(
"Text reject: id=%s title=%s topic_kind=%s topic_score=%.2f "
"text_kind=%s phrase_title=%s phrase_abstract=%s "
"full_token=%s partial_token=%s reason=%s",
patent.patent_id,
patent.title,
topic_evidence.match_kind,
topic_evidence.score,
evidence.text_match_kind,
evidence.phrase_in_title,
evidence.phrase_in_abstract,
evidence.full_token_match,
evidence.partial_token_match,
decision.reason,
)
continue
passed_relevance_gate += 1
text_score = _keyword_text_score(evidence)
# Field-only remains a weak ranking signal when already accepted via phrase.
score = _compute_final_score(
0.0,
topic_evidence.score,
text_score,
weights=_TEXT_SCORE_WEIGHTS,
)
if score < _MIN_TEXT_PATENT_MATCH_SCORE:
filtered_by_min_score += 1
logger.info(
"Text reject: id=%s reason=below_min_score score=%.4f",
patent.patent_id,
score,
)
continue
logger.info(
"Text accept: id=%s title=%s topic_kind=%s topic_score=%.2f "
"text_kind=%s text_score=%.2f final_score=%.4f reason=%s",
patent.patent_id,
patent.title,
topic_evidence.match_kind,
topic_evidence.score,
evidence.text_match_kind,
text_score,
score,
decision.reason,
)
scored.append(
KeywordPatentMatch(
patent=patent,
match_score=score,
ipc_score=0.0,
topic_score=topic_evidence.score,
text_score=text_score,
matched_keywords=_matched_keyword_labels_from_evidence(
search_keywords,
evidence,
),
matched_ipc_symbols=[],
text_retrieval=True,
keyword_evidence=evidence,
topic_match_kind=topic_evidence.match_kind,
)
)
logger.info(
"Keyword patent text search: filtered_by_relevance_gate=%d "
"filtered_by_min_score=%d passed_relevance_gate=%d scored=%d",
filtered_by_relevance_gate,
filtered_by_min_score,
passed_relevance_gate,
len(scored),
)
return scored, {
"filtered_by_relevance_gate": filtered_by_relevance_gate,
"filtered_by_min_score": filtered_by_min_score,
"passed_relevance_gate": passed_relevance_gate,
}
async def _search_patents_text_search(
*,
client: BasePatentSearchClient,
queries: IpcPatentSearchQueries,
ipc_search: IpcSearchClient,
resolver: PatentOpenAlexMappingResolver,
search_keywords: list[KeywordPatentSearchItem],
keyword_topic_ids: frozenset[str],
keyword_subfield_names: frozenset[str],
keyword_soft_field_names: frozenset[str],
mapping_status: KeywordPatentMappingStatus,
ipc_cluster_selections: list[dict] | None = None,
) -> PatentsByKeywordsResponse:
cluster_dicts = list(ipc_cluster_selections or [])
phrases = _text_search_phrases(search_keywords)
text_search_terms = _text_search_terms(search_keywords)
if not phrases:
logger.info(
"Keyword patent text search: no phrases for keywords %s",
[item.keyword for item in search_keywords],
)
return PatentsByKeywordsResponse(
patent_count=0,
patents=[],
mapping_status="no_patents_found",
diagnostics=_empty_diagnostics(
search_path="text",
ipc_cluster_selections=cluster_dicts,
),
)
logger.info(
"Keyword patent text search: mapping_status=%s phrases=%s",
mapping_status,
phrases,
)
raw_patents = await _fetch_patents_for_queries(
client,
queries.epo_query_by_text_phrases(phrases, size=_MAX_PATENTS),
queries.uspto_query_by_text_phrases(phrases, size=_MAX_PATENTS),
)
if raw_patents is None:
return PatentsByKeywordsResponse(
patent_count=0,
patents=[],
mapping_status="search_error",
diagnostics=_empty_diagnostics(
search_path="text",
ipc_cluster_selections=cluster_dicts,
),
)
logger.info("Keyword patent text search: raw_patents=%d", len(raw_patents))
scored, filter_counts = await _score_patents_text_search(
raw_patents=raw_patents,
search_keywords=search_keywords,
phrases=phrases,
text_search_terms=text_search_terms,
keyword_topic_ids=keyword_topic_ids,
keyword_subfield_names=keyword_subfield_names,
keyword_soft_field_names=keyword_soft_field_names,
resolver=resolver,
)
scored, diagnostics = _finalize_scored_patents(
scored,
raw_count=len(raw_patents),
filtered_by_ipc=0,
filtered_by_relevance_gate=filter_counts["filtered_by_relevance_gate"],
filtered_by_min_score=filter_counts["filtered_by_min_score"],
passed_relevance_gate=filter_counts["passed_relevance_gate"],
search_path="text",
ipc_cluster_selections=cluster_dicts,
)
await enrich_patents_classifications([item.patent for item in scored], ipc_search)
if not scored:
return PatentsByKeywordsResponse(
patent_count=0,
patents=[],
mapping_status="no_patents_found",
diagnostics=diagnostics,
)
return PatentsByKeywordsResponse(
patent_count=len(scored),
patents=scored,
mapping_status=mapping_status,
diagnostics=diagnostics,
)
async def get_patents_by_keywords(
request: PatentsByKeywordsRequest,
*,
@@ -1528,21 +1117,18 @@ async def get_patents_by_keywords(
)
logger.info(
"Keyword patent search: no IPC search terms for keywords %s "
"(mapping_status=%s) — trying keyword text search",
"(mapping_status=%s)",
[item.keyword for item in search_keywords],
mapping_status,
)
return await _search_patents_text_search(
client=client,
queries=queries,
ipc_search=ipc_search,
resolver=resolver,
search_keywords=search_keywords,
keyword_topic_ids=keyword_topic_ids,
keyword_subfield_names=keyword_subfield_names,
keyword_soft_field_names=keyword_soft_field_names,
return PatentsByKeywordsResponse(
patent_count=0,
patents=[],
mapping_status=mapping_status,
ipc_cluster_selections=cluster_dicts,
diagnostics=_empty_diagnostics(
search_path="none",
ipc_cluster_selections=cluster_dicts,
),
)
text_search_terms = _text_search_terms(search_keywords)
@@ -1594,31 +1180,11 @@ async def get_patents_by_keywords(
diagnostics=diagnostics,
)
if not _TEXT_SEARCH_AFTER_EMPTY_IPC:
return PatentsByKeywordsResponse(
patent_count=0,
patents=[],
mapping_status="no_patents_found",
diagnostics=diagnostics,
)
logger.info(
"Keyword patent search: IPC path yielded no scored patents — "
"trying keyword text search (policy=_TEXT_SEARCH_AFTER_EMPTY_IPC)"
)
return await _search_patents_text_search(
client=client,
queries=queries,
ipc_search=ipc_search,
resolver=resolver,
search_keywords=search_keywords,
keyword_topic_ids=keyword_topic_ids,
keyword_subfield_names=keyword_subfield_names,
keyword_soft_field_names=keyword_soft_field_names,
# IPC was selected but produced no usable hits; UI treats this like
# uncertain IPC evidence and labels patents via text_retrieval.
mapping_status="uncertain",
ipc_cluster_selections=cluster_dicts,
return PatentsByKeywordsResponse(
patent_count=0,
patents=[],
mapping_status="no_patents_found",
diagnostics=diagnostics,
)
@@ -46,19 +46,12 @@ _USPTO_SOURCE_FIELDS = [
]
_MIN_MATCH_TERM_LEN = 4
_MIN_TEXT_PHRASE_LEN = 3
# Prefer concrete group/subgroup hits over broad subclass prefixes.
_BOOST_SUBGROUP = 4.0
_BOOST_MAIN_GROUP = 2.5
_BOOST_SUBCLASS = 1.0
# Text search: prefer exact phrases in title over abstract / loose match.
_BOOST_TEXT_PHRASE_TITLE = 5.0
_BOOST_TEXT_PHRASE_ABSTRACT = 3.0
_BOOST_TEXT_MATCH_TITLE = 1.5
_BOOST_TEXT_MATCH_ABSTRACT = 1.0
def _add_term_boost(weights: dict[str, float], term: str, boost: float) -> None:
cleaned = term.strip()
@@ -157,76 +150,6 @@ def _ipc_match_clauses(field: str, term_boosts: dict[str, float]) -> list[dict[s
return clauses
def _normalize_text_phrases(phrases: list[str]) -> list[str]:
cleaned: list[str] = []
seen: set[str] = set()
for phrase in phrases:
value = " ".join((phrase or "").strip().split())
if len(value) < _MIN_TEXT_PHRASE_LEN:
continue
key = value.casefold()
if key in seen:
continue
seen.add(key)
cleaned.append(value)
return cleaned
def _text_match_clauses(
phrases: list[str],
*,
title_fields: tuple[str, ...],
abstract_field: str,
) -> list[dict[str, Any]]:
"""Build title/abstract should-clauses with phrase boosts over loose match."""
clauses: list[dict[str, Any]] = []
for phrase in _normalize_text_phrases(phrases):
for field in title_fields:
clauses.append(
{
"match_phrase": {
field: {
"query": phrase,
"boost": _BOOST_TEXT_PHRASE_TITLE,
}
}
}
)
clauses.append(
{
"match": {
field: {
"query": phrase,
"operator": "and",
"boost": _BOOST_TEXT_MATCH_TITLE,
}
}
}
)
clauses.append(
{
"match_phrase": {
abstract_field: {
"query": phrase,
"boost": _BOOST_TEXT_PHRASE_ABSTRACT,
}
}
}
)
clauses.append(
{
"match": {
abstract_field: {
"query": phrase,
"operator": "and",
"boost": _BOOST_TEXT_MATCH_ABSTRACT,
}
}
}
)
return clauses
class IpcPatentSearchQueries:
def epo_query_by_ipc_terms(
self,
@@ -299,55 +222,3 @@ class IpcPatentSearchQueries:
size: int = DEFAULT_SEARCH_SIZE,
) -> dict[str, Any]:
return self.uspto_query_by_ipc_terms(_merge_term_boosts(symbols), size=size)
def epo_query_by_text_phrases(
self,
phrases: list[str],
size: int = DEFAULT_SEARCH_SIZE,
) -> dict[str, Any]:
should = _text_match_clauses(
phrases,
title_fields=("title_en", "title_de"),
abstract_field="abstract",
)
query: dict[str, Any] = (
{"match_none": {}}
if not should
else {"bool": {"should": should, "minimum_should_match": 1}}
)
return {
"size": size,
"track_total_hits": True,
"sort": [
{"_score": {"order": "desc"}},
{"date_publication": {"order": "desc", "missing": "_last"}},
],
"_source": _PATENT_SOURCE_FIELDS,
"query": query,
}
def uspto_query_by_text_phrases(
self,
phrases: list[str],
size: int = DEFAULT_SEARCH_SIZE,
) -> dict[str, Any]:
should = _text_match_clauses(
phrases,
title_fields=("title",),
abstract_field="abstract",
)
query: dict[str, Any] = (
{"match_none": {}}
if not should
else {"bool": {"should": should, "minimum_should_match": 1}}
)
return {
"size": size,
"track_total_hits": True,
"sort": [
{"_score": {"order": "desc"}},
{"publication_date": {"order": "desc", "missing": "_last"}},
],
"_source": _USPTO_SOURCE_FIELDS,
"query": query,
}
@@ -10,21 +10,17 @@ from inse.patents.authors.ipc_openalex_mapping import MappedOpenAlexTopic
from inse.patents.common import model
from inse.patents.keywords.logic import (
TopicEvidence,
_aggregate_subclass_clusters,
_collect_keyword_text_evidence,
_compute_final_score,
_compute_topic_evidence,
_exact_topic_or_subfield_match,
_filter_keywords_for_patent_search,
_ipc_hierarchy_quality,
_keyword_is_patent_searchable,
_keyword_text_passes_relevance_gate,
_keyword_text_score,
_patent_passes_relevance_gate,
_patent_search_terms,
_score_ipc_match,
_score_patent,
_select_dominant_clusters,
_aggregate_subclass_clusters,
_term_from_ipc_match,
_text_overlap_score,
_text_search_terms,
@@ -34,10 +30,6 @@ from inse.patents.keywords.logic import (
get_patents_by_keywords,
select_ipc_matches_by_cluster_mass,
)
from inse.patents.keywords.model import (
KeywordPatentSearchItem,
PatentsByKeywordsRequest,
)
from inse.patents.keywords.reverse_lookup import (
IpcCodeMatch,
_dedupe_ipc_matches,
@@ -45,6 +37,7 @@ from inse.patents.keywords.reverse_lookup import (
_weighted_score,
clear_reverse_lookup_caches,
)
from inse.patents.keywords.model import KeywordPatentSearchItem, PatentsByKeywordsRequest
from inse.patents.keywords.search_queries import (
IpcPatentSearchQueries,
_search_terms_for_symbol,
@@ -646,132 +639,6 @@ def test_text_overlap_score_uses_word_boundaries_not_substrings() -> None:
assert _text_overlap_score(patent, ["chemistry", "organic"]) == 0.0
def test_fallback_rejects_mechanical_patent_for_organic_chemistry() -> None:
"""Soft field / loose words must not accept a mechanical separator patent."""
patent = model.PatentEntry(
patent_id="EP-MECH",
source="EPO",
title=(
"Rotating machine for separating materials in different "
"states of aggregation"
),
abstract="Apparatus for mechanical separation of materials.",
ipc=["B01D45/12"],
)
phrases = ["Organic Chemistry", "organische Chemie"]
terms = ["organic", "chemistry", "organische", "chemie"]
evidence = _collect_keyword_text_evidence(patent, phrases, terms)
assert evidence.phrase_in_title is False
assert evidence.phrase_in_abstract is False
assert evidence.full_token_match is False
assert evidence.matched_phrases == []
assert evidence.matched_words == []
field_only = TopicEvidence(match_kind="compatible_field", score=0.3)
assert not _keyword_text_passes_relevance_gate(
evidence,
topic_evidence=field_only,
).accepted
exact = TopicEvidence(match_kind="topic_id", score=1.0)
assert not _keyword_text_passes_relevance_gate(
evidence,
topic_evidence=exact,
).accepted
def test_fallback_accepts_strong_phrase_or_exact_topic_with_full_tokens() -> None:
phrase_patent = model.PatentEntry(
patent_id="EP-PHRASE",
source="EPO",
title="Process for organic chemistry synthesis",
abstract="Catalytic reactions.",
)
phrases = ["organic chemistry"]
terms = ["organic", "chemistry"]
evidence = _collect_keyword_text_evidence(phrase_patent, phrases, terms)
assert evidence.phrase_in_title is True
assert evidence.text_match_kind == "phrase_title"
assert _keyword_text_score(evidence) == 1.0
assert _keyword_text_passes_relevance_gate(
evidence,
topic_evidence=TopicEvidence(match_kind="none", score=0.0),
).accepted
full_token_patent = model.PatentEntry(
patent_id="EP-WORDS",
source="EPO",
title="Catalytic organic synthesis method",
abstract="Uses chemistry laboratory techniques.",
)
full_evidence = _collect_keyword_text_evidence(
full_token_patent,
phrases,
terms,
)
assert full_evidence.phrase_in_title is False
assert full_evidence.phrase_in_abstract is False
assert full_evidence.full_token_match is True
assert not _keyword_text_passes_relevance_gate(
full_evidence,
topic_evidence=TopicEvidence(match_kind="none", score=0.0),
).accepted
assert _keyword_text_passes_relevance_gate(
full_evidence,
topic_evidence=TopicEvidence(match_kind="topic_id", score=1.0),
).accepted
partial_patent = model.PatentEntry(
patent_id="EP-PARTIAL",
source="EPO",
title="Organic polymer blend",
abstract="Industrial materials processing.",
)
partial_evidence = _collect_keyword_text_evidence(
partial_patent,
phrases,
terms,
)
assert partial_evidence.partial_token_match is True
assert partial_evidence.full_token_match is False
decision = _keyword_text_passes_relevance_gate(
partial_evidence,
topic_evidence=TopicEvidence(match_kind="topic_id", score=1.0),
)
assert not decision.accepted
assert decision.reason == "exact_topic_with_partial_tokens_only"
assert _exact_topic_or_subfield_match(
[
MappedOpenAlexTopic(
topic_id="https://openalex.org/TORG",
topic_display_name="Organic Chemistry",
subfield_name="Organic Chemistry",
field_name="Chemistry",
)
],
frozenset({"TORG"}),
frozenset({"organic chemistry"}),
)
def test_token_match_rejects_machine_inside_micromachined() -> None:
patent = model.PatentEntry(
patent_id="EP-MICRO",
source="EPO",
title="Micromachined sensor device",
abstract="Fabrication of micromachined structures.",
)
assert _text_overlap_score(patent, ["machine", "learning"]) == 0.0
evidence = _collect_keyword_text_evidence(
patent,
["Machine Learning"],
["machine", "learning"],
)
assert evidence.matched_words == []
assert evidence.full_token_match is False
def test_patent_passes_relevance_gate_with_text_but_no_topics() -> None:
patent = model.PatentEntry(
patent_id="EP1",
@@ -914,8 +781,7 @@ def test_get_patents_by_keywords_uses_symbol_queries() -> None:
uspto_symbols.assert_called_once()
assert epo_symbols.call_args.args[0][0] == "C07C243/08"
assert "C07C" in epo_symbols.call_args.args[0]
# IPC search returns empty → text fallback also queries EPO/USPTO.
assert captured == ["epo", "uspto", "epo", "uspto"]
assert captured == ["epo", "uspto"]
def test_text_search_terms_include_topic_metadata() -> None:
@@ -993,64 +859,84 @@ def test_epo_and_uspto_queries_boost_specific_symbols_over_subclass() -> None:
assert uspto["sort"][0] == {"_score": {"order": "desc"}}
def test_text_queries_prefer_phrase_match_in_title() -> None:
queries = IpcPatentSearchQueries()
epo = queries.epo_query_by_text_phrases(["organic chemistry"])
uspto = queries.uspto_query_by_text_phrases(["organic chemistry"])
epo_should = epo["query"]["bool"]["should"]
uspto_should = uspto["query"]["bool"]["should"]
def clause_boost(clauses: list[dict], kind: str, field: str) -> float | None:
for clause in clauses:
payload = clause.get(kind, {}).get(field)
if isinstance(payload, dict) and payload.get("query") == "organic chemistry":
return float(payload.get("boost", 1.0))
return None
assert clause_boost(epo_should, "match_phrase", "title_en") == 5.0
assert clause_boost(epo_should, "match_phrase", "abstract") == 3.0
assert clause_boost(epo_should, "match", "title_en") == 1.5
assert clause_boost(uspto_should, "match_phrase", "title") == 5.0
assert epo["sort"][0] == {"_score": {"order": "desc"}}
def test_uncertain_mapping_uses_text_fallback_not_empty_list() -> None:
"""Fragmented IPC abstention must fall back to title/abstract search."""
patent = model.PatentEntry(
patent_id="EP123",
source="EPO",
title="Process for organic chemistry synthesis",
abstract="A catalytic method in organic chemistry.",
publication_date="20240101",
ipc=["C07C243/08"],
cpc=[],
def test_technical_search_failure_returns_search_error_not_no_patents_found() -> None:
request = PatentsByKeywordsRequest(
keywords=[
KeywordPatentSearchItem(
keyword="organische Chemie",
keyword_level="coarse",
topic_id="https://openalex.org/TORG",
topic_display_name="Organic Chemistry",
field_name="Chemistry",
relevance_score=1.0,
)
]
)
ipc_matches = [
IpcCodeMatch(
"subgroup",
"C07C243/08",
0.90,
"organische Chemie",
"topic",
"TORG",
)
]
async def fake_search_epo(query):
assert "match_phrase" in str(query) or "title_en" in str(query)
return {
"hits": {
"hits": [
{
"_source": {
"doc_number": "123",
"country": "EP",
"kind": "A1",
"date_publication": "20240101",
"title_en": patent.title,
"abstract": patent.abstract,
"ipc": patent.ipc,
"cpc": [],
}
}
]
}
}
with patch(
"inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes",
new=AsyncMock(return_value=ipc_matches),
), patch(
"inse.patents.keywords.logic.BasePatentSearchClient.search_epo",
new=AsyncMock(side_effect=httpx.HTTPError("boom")),
), patch(
"inse.patents.keywords.logic.BasePatentSearchClient.search_uspto",
new=AsyncMock(return_value={"hits": {"hits": []}}),
):
response = asyncio.run(get_patents_by_keywords(request))
async def fake_search_uspto(query):
return {"hits": {"hits": []}}
assert response.mapping_status == "search_error"
assert response.patent_count == 0
def test_no_ipc_search_terms_returns_without_text_fallback() -> None:
"""Without usable IPC symbols the search abstains — no title/abstract path."""
request = PatentsByKeywordsRequest(
keywords=[
KeywordPatentSearchItem(
keyword="organische Chemie",
keyword_level="coarse",
topic_id="https://openalex.org/TORG",
topic_display_name="Organic Chemistry",
field_name="Chemistry",
relevance_score=1.0,
)
]
)
search_epo = AsyncMock(return_value={"hits": {"hits": []}})
search_uspto = AsyncMock(return_value={"hits": {"hits": []}})
with patch(
"inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes",
new=AsyncMock(return_value=[]),
), patch(
"inse.patents.keywords.logic.BasePatentSearchClient.search_epo",
new=search_epo,
), patch(
"inse.patents.keywords.logic.BasePatentSearchClient.search_uspto",
new=search_uspto,
):
response = asyncio.run(get_patents_by_keywords(request))
assert response.mapping_status == "no_mapping"
assert response.patent_count == 0
assert response.patents == []
search_epo.assert_not_called()
search_uspto.assert_not_called()
def test_uncertain_ipc_cluster_abstention_returns_without_text_fallback() -> None:
"""Fragmented IPC mapping abstains without falling back to text retrieval."""
fragmented = [
IpcCodeMatch(
"subgroup",
@@ -1074,113 +960,31 @@ def test_uncertain_mapping_uses_text_fallback_not_empty_list() -> None:
)
]
)
search_epo = AsyncMock(return_value={"hits": {"hits": []}})
with patch(
"inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes",
new=AsyncMock(return_value=fragmented),
), patch(
"inse.patents.keywords.logic.BasePatentSearchClient.search_epo",
new=AsyncMock(side_effect=fake_search_epo),
), patch(
"inse.patents.keywords.logic.BasePatentSearchClient.search_uspto",
new=AsyncMock(side_effect=fake_search_uspto),
), patch(
"inse.patents.keywords.logic.PatentOpenAlexMappingResolver.resolve_topics_for_patents",
new=AsyncMock(return_value={}),
), patch(
"inse.patents.keywords.logic.enrich_patents_classifications",
new=AsyncMock(),
), patch.object(
IpcPatentSearchQueries,
"epo_query_by_text_phrases",
wraps=IpcPatentSearchQueries().epo_query_by_text_phrases,
) as epo_text:
response = asyncio.run(get_patents_by_keywords(request))
epo_text.assert_called_once()
assert response.mapping_status == "uncertain"
assert response.patent_count == 1
assert response.patents[0].text_retrieval is True
assert response.patents[0].ipc_score == 0.0
assert response.patents[0].text_score > 0.0
assert response.patents[0].matched_ipc_symbols == []
assert response.patents[0].keyword_evidence is not None
assert response.patents[0].keyword_evidence.phrase_in_title is True
assert response.patents[0].keyword_evidence.text_match_kind == "phrase_title"
def test_text_fallback_empty_yields_no_patents_found() -> None:
request = PatentsByKeywordsRequest(
keywords=[
KeywordPatentSearchItem(
keyword="organische Chemie",
keyword_level="coarse",
topic_id="https://openalex.org/TORG",
topic_display_name="Organic Chemistry",
field_name="Chemistry",
relevance_score=1.0,
)
]
)
with patch(
"inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes",
new=AsyncMock(return_value=[]),
), patch(
"inse.patents.keywords.logic.BasePatentSearchClient.search_epo",
new=AsyncMock(return_value={"hits": {"hits": []}}),
new=search_epo,
), patch(
"inse.patents.keywords.logic.BasePatentSearchClient.search_uspto",
new=AsyncMock(return_value={"hits": {"hits": []}}),
), patch(
"inse.patents.keywords.logic.PatentOpenAlexMappingResolver.resolve_topics_for_patents",
new=AsyncMock(return_value={}),
), patch(
"inse.patents.keywords.logic.enrich_patents_classifications",
new=AsyncMock(),
):
response = asyncio.run(get_patents_by_keywords(request))
assert response.mapping_status == "no_patents_found"
assert response.mapping_status == "uncertain"
assert response.patent_count == 0
assert response.patents == []
def test_technical_search_failure_returns_search_error_not_no_patents_found() -> None:
request = PatentsByKeywordsRequest(
keywords=[
KeywordPatentSearchItem(
keyword="organische Chemie",
keyword_level="coarse",
topic_id="https://openalex.org/TORG",
topic_display_name="Organic Chemistry",
field_name="Chemistry",
relevance_score=1.0,
)
]
)
with patch(
"inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes",
new=AsyncMock(return_value=[]),
), patch(
"inse.patents.keywords.logic.BasePatentSearchClient.search_epo",
new=AsyncMock(side_effect=httpx.HTTPError("boom")),
), patch(
"inse.patents.keywords.logic.BasePatentSearchClient.search_uspto",
new=AsyncMock(return_value={"hits": {"hits": []}}),
):
response = asyncio.run(get_patents_by_keywords(request))
assert response.mapping_status == "search_error"
assert response.patent_count == 0
search_epo.assert_not_called()
def test_json_lookup_returns_empty_without_mapping(monkeypatch) -> None:
clear_reverse_lookup_caches()
monkeypatch.setattr(
"inse.patents.keywords.reverse_lookup.load_patents_openalex_keywords_json",
dict,
lambda: {},
)
clear_reverse_lookup_caches()
@@ -103,24 +103,29 @@
{{ getMatchTypeLabel(patent) }}
</span>
</td>
<td class="cell-authors">
@if (
patent.matched_authors && patent.matched_authors.length
) {
@for (
author of patent.matched_authors.slice(0, 2);
track author.openalex_author_id
<td>
<div class="cell-authors">
@if (
patent.matched_authors && patent.matched_authors.length
) {
<a
class="author-link"
[routerLink]="['/person', author.openalex_author_id]"
(click)="$event.stopPropagation()">
{{ author.author_name }}
</a>
@for (
author of patent.matched_authors.slice(0, 2);
track author.openalex_author_id
) {
<a
class="author-link"
[routerLink]="[
'/person',
author.openalex_author_id,
]"
(click)="$event.stopPropagation()">
{{ author.author_name }}
</a>
}
} @else {
<span>-</span>
}
} @else {
<span>-</span>
}
</div>
</td>
</tr>
}
@@ -60,21 +60,14 @@ app-query-param-paginator {
table {
width: 100%;
border-collapse: separate;
border-spacing: 0;
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm);
overflow: hidden;
border-collapse: collapse;
th {
text-align: left;
padding: 12px 16px;
background: var(--sg-surface-muted);
border-bottom: 1px solid var(--sg-border);
font-size: 12px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.02em;
font-size: 13px;
font-weight: 600;
color: var(--sg-text-muted);
}
@@ -90,10 +83,6 @@ app-query-param-paginator {
&.selected td {
background: var(--sg-primary-soft);
}
&:last-child td {
border-bottom: 0;
}
}
td {
@@ -107,10 +96,9 @@ app-query-param-paginator {
.patent-title {
color: var(--sg-text);
font-weight: 600;
max-width: 280px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 320px;
white-space: normal;
word-break: break-word;
}
.cell-preview {
@@ -1,46 +1,63 @@
@if (loading()) {
<div class="patents-container">
<ng-container *ngTemplateOutlet="patentsHeader" />
<app-loading
text="Patentdaten werden geladen..."
icon="workspace_premium"
[size]="150"
[diameter]="150" />
</div>
<app-loading
text="Patentdaten werden geladen..."
icon="workspace_premium"
[size]="150"
[diameter]="150" />
} @else if (error()) {
<div class="patents-container">
<ng-container *ngTemplateOutlet="patentsHeader" />
<p class="message">Fehler beim Laden der Patente.</p>
</div>
<p class="message">Fehler beim Laden der Patente.</p>
} @else if (matches().length === 0) {
<div class="patents-container">
<ng-container *ngTemplateOutlet="patentsHeader" />
<p class="message">{{ emptyMessage() }}</p>
</div>
<p class="message">{{ emptyMessage() }}</p>
} @else {
<div class="patents-container">
<ng-container *ngTemplateOutlet="patentsHeader" />
<div class="patents-content">
<div class="patents-list">
<div class="patents-list-toolbar">
<mat-form-field
class="patents-toolbar-field"
subscriptSizing="dynamic">
<mat-icon matPrefix fontIcon="filter_alt"></mat-icon>
<mat-select
[value]="activeFilter()"
(selectionChange)="setFilter($event.value)">
<mat-select-trigger>Filter nach Quelle</mat-select-trigger>
<mat-option value="all">Alle</mat-option>
<mat-option value="EPO">EPO</mat-option>
<mat-option value="USPTO">USPTO</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field
class="patents-toolbar-field"
subscriptSizing="dynamic">
<mat-icon matPrefix fontIcon="sort"></mat-icon>
<mat-select
[value]="sortMode()"
(selectionChange)="setSortMode($event.value)">
<mat-select-trigger>Sortieren nach</mat-select-trigger>
<mat-option value="date">Datum</mat-option>
<mat-option value="title">Titel</mat-option>
</mat-select>
</mat-form-field>
</div>
<table>
<thead>
<tr>
<th>Patent</th>
<th>Score</th>
<th>Quelle</th>
<th>Jahr</th>
<th>Erfinder</th>
<th>Anmelder</th>
</tr>
</thead>
<tbody>
@for (item of pagedMatches(); track trackMatch($index, item)) {
@for (item of getPagedMatches(); track trackMatch($index, item)) {
<tr
[class.selected]="selectedMatch() === item"
(click)="selectMatch(item)">
<td class="patent-title">
{{ item.patent.title ?? item.patent.patent_id }}
</td>
<td class="match-score">{{ formatScore(item.match_score) }}</td>
<td>
<span
class="source-badge source-badge--{{
@@ -50,50 +67,33 @@
</span>
</td>
<td>{{ item.patent.publication_year ?? '-' }}</td>
<td
class="patent-people"
[title]="getInventorsLabel(item.patent)">
{{ getInventorsLabel(item.patent) }}
</td>
<td
class="patent-people"
[title]="getAssigneesLabel(item.patent)">
{{ getAssigneesLabel(item.patent) }}
</td>
</tr>
}
</tbody>
</table>
@if (hasPagination()) {
<div class="pagination">
<button
[disabled]="selectedPage() === 1"
(click)="setPage(selectedPage() - 1)">
Zurück
</button>
<span>Seite {{ selectedPage() }} von {{ pageCount() }}</span>
<button
[disabled]="selectedPage() === pageCount()"
(click)="setPage(selectedPage() + 1)">
Weiter
</button>
</div>
}
<app-query-param-paginator
[total]="filteredMatches().length"
queryParamPageKey="page"
queryParamSizeKey="size"
[pageSizeOptions]="[10, 25, 50]"
(handlePageChange)="onPatentPageChange($event)" />
</div>
@if (selectedMatch(); as match) {
<div class="patent-detail">
<h3>{{ match.patent.title ?? match.patent.patent_id }}</h3>
<div class="detail-stats">
<div class="stat">
<span class="stat-label">Match-Score</span>
<span class="stat-value">{{
formatScore(match.match_score)
}}</span>
</div>
<div class="stat">
<span class="stat-label">Gematchte Keywords</span>
<span class="stat-value">{{
formatMatchList(match.matched_keywords)
}}</span>
</div>
<div class="stat">
<span class="stat-label">Gematchte IPC/CPC</span>
<span class="stat-value">{{
formatMatchList(match.matched_ipc_symbols)
}}</span>
</div>
<div class="stat">
<span class="stat-label">Quelle</span>
<span class="stat-value">
@@ -123,6 +123,10 @@
}
</div>
@if (getAbstractPreview(match.patent.abstract); as abstractPreview) {
<p class="patent-detail-preview">{{ abstractPreview }}</p>
}
<button
type="button"
class="patent-detail-action"
@@ -132,40 +136,33 @@
>
<mat-icon aria-hidden="true">chevron_right</mat-icon>
</button>
<p class="patent-detail-hint">
Abstract, Erfinder, Anmelder und IPC/CPC-Klassifikation
</p>
</div>
} @else {
<div class="patent-detail overview">
<p class="overview-title">Patentübersicht</p>
<p class="overview-subtitle">Patente mit passenden Keywords.</p>
<div class="overview-stats">
<div class="overview-stat overview-stat--total">
<span class="overview-value">{{ matches().length }}</span>
<span class="overview-label">Patente</span>
</div>
<div class="overview-stat overview-stat--epo">
<span class="overview-value">{{ getEpoCount() }}</span>
<span class="overview-label">EPO</span>
</div>
<div class="overview-stat overview-stat--uspto">
<span class="overview-value">{{ getUsptoCount() }}</span>
<span class="overview-label">USPTO</span>
</div>
</div>
<p class="overview-hint">
Wähle links ein Patent aus, um Details zu sehen.
</p>
</div>
}
</div>
</div>
}
<ng-template #patentsHeader>
<div class="patents-header">
<h2 class="section-title">Passende Patente</h2>
<div class="patents-header-actions">
@if (matches().length > 0) {
<label class="sort-control">
<span>Filter nach Quelle:</span>
<select
[value]="activeFilter()"
(change)="setFilter($any($event.target).value)">
<option value="all">Alle</option>
<option value="EPO">EPO</option>
<option value="USPTO">USPTO</option>
</select>
</label>
}
@if (showReload()) {
<button
mat-stroked-button
type="button"
class="reload-btn"
[disabled]="reloadDisabled()"
(click)="onReload()">
<mat-icon>refresh</mat-icon>
Neu laden
</button>
}
</div>
</div>
</ng-template>
@@ -25,24 +25,25 @@
background: var(--sg-card-bg);
border: 1px solid var(--sg-border);
box-shadow: var(--sg-shadow-sm);
display: flex;
flex-direction: column;
gap: 16px;
}
.patents-header {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 16px;
flex-direction: column;
gap: 16px;
}
.patents-header-actions {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: flex-end;
gap: 10px;
margin-left: auto;
app-query-param-paginator {
display: block;
margin-top: 14px;
}
.patents-toolbar-field {
width: fit-content;
min-width: 180px;
}
.reload-btn {
@@ -77,10 +78,66 @@
.patents-list {
flex: 1;
min-width: 0;
.patents-list-toolbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
margin-bottom: 18px;
flex-wrap: wrap;
}
table {
width: 100%;
border-collapse: collapse;
th {
text-align: left;
padding: 12px 16px;
border-bottom: 1px solid var(--sg-border);
font-size: 13px;
font-weight: 600;
color: var(--sg-text-muted);
}
tr {
cursor: pointer;
transition: background-color 0.15s ease;
&:hover td {
background: rgba(16, 26, 61, 0.04);
}
&.selected td {
background: var(--sg-primary-soft);
}
}
td {
padding: 12px 16px;
border-bottom: 1px solid var(--sg-border);
color: var(--sg-text);
font-size: 13px;
transition: background-color 0.15s ease;
}
.patent-title {
color: var(--sg-text);
font-weight: 600;
max-width: 400px;
white-space: normal;
word-break: break-word;
}
.patent-people {
max-width: 220px;
color: var(--sg-text-muted);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
}
th {
@@ -114,42 +171,161 @@
}
.source-badge {
display: inline-block;
padding: 2px 8px;
display: inline-flex;
align-items: center;
padding: 3px 10px;
border-radius: 999px;
font-size: 12px;
font-weight: 600;
font-size: 0.75rem;
font-weight: 700;
&--epo {
background: var(--sg-primary-soft);
color: var(--sg-blue-highlight);
background: #effaf3;
color: #24834f;
border: 1px solid #bdebcf;
}
&--uspto {
background: var(--sg-success-soft);
color: var(--sg-success);
background: #f0f6ff;
color: #0b63ce;
border: 1px solid #bdd4ff;
}
}
.pagination {
display: flex;
align-items: center;
gap: 12px;
margin-top: 12px;
}
.patent-detail {
flex: 0 0 320px;
padding: 16px;
border-radius: 12px;
background: var(--sg-surface-muted);
border: 1px solid var(--sg-border);
width: 440px;
padding: 24px;
background: var(--sg-surface);
box-shadow: var(--sg-shadow-sm);
border-radius: var(--sg-radius-sm);
&.overview {
display: flex;
flex-direction: column;
gap: 12px;
.overview-title {
font-size: 15px;
font-weight: 700;
color: var(--sg-text);
margin: 0;
}
.overview-subtitle {
font-size: 13px;
color: var(--sg-text-muted);
margin: 0;
}
.overview-stats {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 10px;
margin-top: 4px;
}
.overview-stat {
background: var(--sg-surface);
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm);
padding: 12px 8px;
text-align: center;
.overview-value {
display: block;
font-size: 22px;
font-weight: 700;
color: var(--sg-text);
}
.overview-label {
display: block;
font-size: 12px;
color: var(--sg-text-muted);
margin-top: 4px;
}
&--total {
.overview-value,
.overview-label {
color: #7255d9;
}
}
&--epo {
.overview-value,
.overview-label {
color: #24834f;
}
}
&--uspto {
.overview-value,
.overview-label {
color: #0b63ce;
}
}
}
.overview-hint {
font-size: 12px;
color: var(--sg-text-muted);
margin: 0;
}
}
h3 {
margin: 0 0 16px 0;
font-size: 16px;
font-weight: 700;
color: var(--sg-text);
line-height: 1.4;
}
}
.detail-stats {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
margin: 12px 0;
.stat {
background: var(--sg-surface);
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm);
padding: 10px;
text-align: center;
.stat-label {
display: block;
font-size: 11px;
color: var(--sg-text-muted);
margin-bottom: 4px;
text-transform: uppercase;
letter-spacing: 0.03em;
}
.stat-value {
display: block;
font-size: 15px;
font-weight: bold;
color: var(--sg-text);
}
}
}
.patent-detail-preview {
margin: 14px 0 0;
font-size: 13px;
line-height: 1.55;
color: var(--sg-text-muted);
}
.match-score {
@@ -174,6 +350,7 @@
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
width: 100%;
margin-top: 12px;
padding: 10px 12px;
@@ -181,26 +358,45 @@
border-radius: 8px;
background: var(--sg-primary);
color: var(--sg-card-bg);
margin-top: 16px;
padding: 12px 14px;
border: 1px solid #bdd4ff;
border-radius: 10px;
background: linear-gradient(180deg, #f8fbff 0%, #eef4ff 100%);
color: #0b63ce;
font-size: 14px;
font-weight: 600;
cursor: pointer;
transition:
border-color 0.15s,
background 0.15s,
box-shadow 0.15s;
&:hover {
border-color: #0b63ce;
background: #f0f6ff;
box-shadow: 0 2px 8px rgba(11, 99, 206, 0.12);
}
.material-icons {
font-size: 20px;
}
}
@media (max-width: 900px) {
.patents-header {
flex-direction: column;
align-items: stretch;
}
.patents-header-actions {
margin-left: 0;
justify-content: space-between;
}
.patent-detail-hint {
margin: 8px 0 0;
font-size: 12px;
line-height: 1.4;
color: #888;
text-align: center;
}
@media (max-width: 960px) {
.patents-content {
flex-direction: column;
}
.patent-detail {
flex: 1;
width: 100%;
}
}
@@ -1,11 +1,14 @@
import { NgTemplateOutlet } from '@angular/common';
import { Component, input, output, signal } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { Component, computed, inject, input, output, signal } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { Router } from '@angular/router';
import { MatSelectModule } from '@angular/material/select';
import { PageEvent } from '@angular/material/paginator';
import { ActivatedRoute, Router } from '@angular/router';
import { PatentEntry } from '../../../api/model/patentEntry';
import { KeywordPatentMatch } from '../../../api/model/keywordPatentMatch';
import { LoadingComponent } from '../../../shared/ui/loading/loading.component';
import { QueryParamPaginatorComponent } from '../../../shared/ui/query-param-paginator/query-param-paginator.component';
import {
formatPatentDate,
getPublicationStageLabel,
@@ -13,14 +16,25 @@ import {
import { KeywordPatentMappingStatus } from '../../../api';
type SourceFilter = 'all' | 'EPO' | 'USPTO';
type SortMode = 'date' | 'title';
@Component({
selector: 'app-keywords-patents',
imports: [NgTemplateOutlet, MatButtonModule, MatIconModule, LoadingComponent],
imports: [
MatFormFieldModule,
MatIconModule,
MatSelectModule,
LoadingComponent,
QueryParamPaginatorComponent,
],
templateUrl: './keywords-patents.component.html',
styleUrl: './keywords-patents.component.scss',
})
export class KeywordsPatentsComponent {
private readonly route = inject(ActivatedRoute);
private readonly router = inject(Router);
private readonly queryParams = toSignal(this.route.queryParams);
readonly matches = input<KeywordPatentMatch[]>([]);
readonly mappingStatus = input<KeywordPatentMappingStatus | null>(null);
readonly loading = input(false);
@@ -30,54 +44,65 @@ export class KeywordsPatentsComponent {
readonly reload = output<void>();
activeFilter = signal<SourceFilter>('all');
sortMode = signal<SortMode>('date');
selectedMatch = signal<KeywordPatentMatch | null>(null);
selectedPage = signal(1);
readonly pageSize = 10;
constructor(private readonly router: Router) {}
readonly pageIndex = computed(() => {
const params = this.queryParams();
return params?.['page'] ? +params['page'] || 0 : 0;
});
readonly pageSize = computed(() => {
const params = this.queryParams();
return params?.['size'] ? +params['size'] || 10 : 10;
});
readonly filteredMatches = computed(() => {
const filter = this.activeFilter();
let items = this.matches();
if (filter !== 'all') {
items = items.filter((item) => item.patent.source === filter);
}
return this.sortMatches(items);
});
emptyMessage(): string {
switch (this.mappingStatus()) {
case 'search_error':
return 'Die Patentrecherche ist technisch fehlgeschlagen. Bitte später erneut versuchen.';
default:
return 'Keine passenden Patente gefunden';
return 'Keine passenden Patente gefunden.';
}
}
filteredMatches(): KeywordPatentMatch[] {
const filter = this.activeFilter();
const items = this.matches();
if (filter === 'all') {
return items;
}
return items.filter((item) => item.patent.source === filter);
}
pagedMatches(): KeywordPatentMatch[] {
const start = (this.selectedPage() - 1) * this.pageSize;
return this.filteredMatches().slice(start, start + this.pageSize);
}
pageCount(): number {
return Math.max(
1,
Math.ceil(this.filteredMatches().length / this.pageSize),
);
}
hasPagination(): boolean {
return this.pageCount() > 1;
getPagedMatches(): KeywordPatentMatch[] {
const start = this.pageIndex() * this.pageSize();
return this.filteredMatches().slice(start, start + this.pageSize());
}
setFilter(filter: SourceFilter): void {
this.activeFilter.set(filter);
this.selectedPage.set(1);
this.selectedMatch.set(null);
this.resetPage();
}
setSortMode(sortMode: SortMode): void {
this.sortMode.set(sortMode);
this.selectedMatch.set(null);
this.resetPage();
}
onPatentPageChange(_event: PageEvent): void {
this.selectedMatch.set(null);
}
setPage(page: number): void {
this.selectedPage.set(Math.min(Math.max(page, 1), this.pageCount()));
private resetPage(): void {
void this.router.navigate([], {
relativeTo: this.route,
queryParams: { page: 0 },
queryParamsHandling: 'merge',
replaceUrl: true,
});
}
selectMatch(item: KeywordPatentMatch): void {
@@ -90,8 +115,21 @@ export class KeywordsPatentsComponent {
void this.router.navigate(['/patent', match.patent.patent_id]);
}
onReload(): void {
this.reload.emit();
getEpoCount(): number {
return this.matches().filter((item) => item.patent.source === 'EPO').length;
}
getUsptoCount(): number {
return this.matches().filter((item) => item.patent.source === 'USPTO')
.length;
}
getInventorsLabel(patent: PatentEntry): string {
return patent.inventors?.length ? patent.inventors.join(', ') : '-';
}
getAssigneesLabel(patent: PatentEntry): string {
return patent.assignees?.length ? patent.assignees.join(', ') : '-';
}
formatDate(date: string | null | undefined): string {
@@ -102,18 +140,15 @@ export class KeywordsPatentsComponent {
return getPublicationStageLabel(patent);
}
formatScore(score: number | null | undefined): string {
if (score == null || Number.isNaN(score)) {
return '-';
getAbstractPreview(abstract: string | null | undefined): string | null {
if (!abstract?.trim()) {
return null;
}
return score.toFixed(2);
}
formatMatchList(values: string[] | null | undefined): string {
if (!values || values.length === 0) {
return '-';
const text = abstract.trim();
if (text.length <= 160) {
return text;
}
return values.join(', ');
return `${text.slice(0, 160).trimEnd()}…`;
}
trackMatch(_index: number, item: KeywordPatentMatch): string {
@@ -126,4 +161,18 @@ export class KeywordsPatentsComponent {
item.match_score,
].join('|');
}
private sortMatches(items: KeywordPatentMatch[]): KeywordPatentMatch[] {
const mode = this.sortMode();
return [...items].sort((a, b) => {
if (mode === 'date') {
return (b.patent.publication_date ?? '').localeCompare(
a.patent.publication_date ?? '',
);
}
return (a.patent.title ?? '').localeCompare(b.patent.title ?? '', 'de', {
sensitivity: 'base',
});
});
}
}
@@ -108,81 +108,3 @@ function sameKeywordSet(a: string[], b: string[]): boolean {
const setA = new Set(a.map((keyword) => normalizeKeyword(keyword)));
return b.every((keyword) => setA.has(normalizeKeyword(keyword)));
}
export interface PatentScoreWeights {
ipc: number;
topic: number;
text: number;
}
export const DEFAULT_PATENT_SCORE_WEIGHTS: PatentScoreWeights = {
ipc: 0.6,
topic: 0.25,
text: 0.15,
};
export function normalizePatentScoreWeights(
raw: Record<string, number>,
): PatentScoreWeights {
const ipc = raw['ipc'] ?? DEFAULT_PATENT_SCORE_WEIGHTS.ipc;
const topic = raw['topic'] ?? DEFAULT_PATENT_SCORE_WEIGHTS.topic;
const text = raw['text'] ?? DEFAULT_PATENT_SCORE_WEIGHTS.text;
const sum = ipc + topic + text;
if (sum <= 0) {
return { ...DEFAULT_PATENT_SCORE_WEIGHTS };
}
return { ipc: ipc / sum, topic: topic / sum, text: text / sum };
}
export function computePatentMatchScore(
match: Pick<KeywordPatentMatch, 'ipc_score' | 'topic_score' | 'text_score'>,
weights: PatentScoreWeights,
): number {
return (
Math.round(
(weights.ipc * match.ipc_score +
weights.topic * match.topic_score +
weights.text * match.text_score) *
10000,
) / 10000
);
}
export function applyPatentScoreWeights(
matches: KeywordPatentMatch[],
weights: PatentScoreWeights,
): KeywordPatentMatch[] {
return [...matches]
.map((match) => ({
...match,
match_score: computePatentMatchScore(match, weights),
}))
.sort((a, b) => {
const scoreDiff = b.match_score - a.match_score;
if (scoreDiff !== 0) {
return scoreDiff;
}
const dateA = a.patent.publication_date ?? '';
const dateB = b.patent.publication_date ?? '';
if (dateA !== dateB) {
return dateB.localeCompare(dateA);
}
return a.patent.patent_id.localeCompare(b.patent.patent_id);
});
}
function hasPatentComponentScores(match: KeywordPatentMatch): boolean {
return (
typeof match.ipc_score === 'number' &&
typeof match.topic_score === 'number' &&
typeof match.text_score === 'number'
);
}
export function canReweightPatentMatches(
matches: KeywordPatentMatch[],
): boolean {
return matches.length > 0 && matches.every(hasPatentComponentScores);
}
@@ -1,24 +1,4 @@
<div class="result-layout">
<mat-card class="weights-card">
<mat-card-content>
<app-weights-sliders
[options]="weightOptions"
[initialWeights]="defaultWeights"
title="Patenten-Gewichtung"
description="Steuert die Gewichtung von IPC/CPC-Match, OpenAlex-Topic und Text-Match für den Gesamt-Score."
resetLabel="Standard"
applyLabel="Neu gewichten"
normalizedTitle="Normalisiert"
queryParamPrefix="patentW_"
[persistInQueryParams]="true"
[showApplyButton]="true"
[showResetButton]="true"
[showNormalizedPreview]="true"
(weightsChange)="onWeightsChange($event)"
(applyWeights)="onApplyWeights($event)" />
</mat-card-content>
</mat-card>
<div class="results-card">
<app-keywords-patents
[matches]="patentMatches()"
@@ -1,20 +1,8 @@
/* ============================================================
RESULT LAYOUT
============================================================ */
.result-layout {
display: grid;
grid-template-columns: minmax(280px, 360px) minmax(0, 1fr);
grid-template-areas: 'summary results';
gap: 0.75rem;
align-items: start;
}
.weights-card {
grid-area: summary;
display: block;
}
.results-card {
grid-area: results;
min-width: 0;
}
@@ -1,26 +1,12 @@
import { Component, inject, OnInit, signal } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatIconModule } from '@angular/material/icon';
import { KeywordsService } from '../../../../api/api/keywords.service';
import { KeywordPatentMatch } from '../../../../api/model/keywordPatentMatch';
import { PatentsByKeywordsResponse } from '../../../../api/model/patentsByKeywordsResponse';
import {
WeightMap,
WeightSliderOption,
WeightsSlidersComponent,
WeightsSlidersValue,
} from '../../../../shared/ui/weights-sliders/weights-sliders.component';
import { KeywordsPatentsComponent } from '../../keywords-patents/keywords-patents.component';
import {
applyPatentScoreWeights,
buildPatentSearchItemsFromPayload,
canReweightPatentMatches,
clearPatentsCache,
DEFAULT_PATENT_SCORE_WEIGHTS,
normalizePatentScoreWeights,
readPatentsCache,
writePatentsCache,
} from '../../patent-search.utils';
@@ -29,13 +15,7 @@ import { KeywordPatentMappingStatus } from '../../../../api';
@Component({
selector: 'app-patents-results',
imports: [
MatCardModule,
MatIconModule,
MatButtonModule,
WeightsSlidersComponent,
KeywordsPatentsComponent,
],
imports: [KeywordsPatentsComponent],
templateUrl: './patents-results.component.html',
styleUrl: './patents-results.component.scss',
})
@@ -43,53 +23,11 @@ export class KeywordsToPatentsResultsComponent implements OnInit {
protected readonly state = inject(SearchResultsStateService);
private readonly keywordsService = inject(KeywordsService);
readonly defaultWeights: WeightMap = { ...DEFAULT_PATENT_SCORE_WEIGHTS };
readonly weightOptions: WeightSliderOption[] = [
{
key: 'ipc',
label: 'IPC/CPC-Match',
icon: 'category',
description:
'Gewichtet die Übereinstimmung der Patent-Klassifikation (IPC/CPC) mit den Keywords.',
defaultValue: DEFAULT_PATENT_SCORE_WEIGHTS.ipc,
queryParamName: 'wIpc',
},
{
key: 'topic',
label: 'OpenAlex-Topic',
icon: 'hub',
description:
'Gewichtet die thematische Übereinstimmung über OpenAlex-Topics und Fachgebiete.',
defaultValue: DEFAULT_PATENT_SCORE_WEIGHTS.topic,
queryParamName: 'wTopic',
},
{
key: 'text',
label: 'Text-Match',
icon: 'article',
description:
'Gewichtet Treffer der Keywords im Patenttitel und in der Zusammenfassung.',
defaultValue: DEFAULT_PATENT_SCORE_WEIGHTS.text,
queryParamName: 'wText',
},
];
readonly currentWeights = signal<WeightsSlidersValue>({
raw: this.defaultWeights,
normalized: { ...DEFAULT_PATENT_SCORE_WEIGHTS },
rawSum: 1,
normalizedSum: 1,
valid: true,
});
readonly patentMatches = signal<KeywordPatentMatch[]>([]);
readonly mappingStatus = signal<KeywordPatentMappingStatus | null>(null);
readonly loadingPatents = signal(false);
readonly patentsError = signal(false);
private readonly patentMatchesBase = signal<KeywordPatentMatch[]>([]);
ngOnInit(): void {
const cached = readPatentsCache(this.state.keywords());
if (cached) {
@@ -100,19 +38,6 @@ export class KeywordsToPatentsResultsComponent implements OnInit {
this.loadMatchingPatents();
}
onWeightsChange(value: WeightsSlidersValue): void {
this.currentWeights.set(value);
}
onApplyWeights(value: WeightsSlidersValue): void {
this.currentWeights.set(value);
if (!canReweightPatentMatches(this.patentMatchesBase())) {
this.reloadPatents();
return;
}
this.updateDisplayedMatches();
}
reloadPatents(): void {
clearPatentsCache();
this.loadMatchingPatents();
@@ -149,26 +74,8 @@ export class KeywordsToPatentsResultsComponent implements OnInit {
matches: KeywordPatentMatch[],
mappingStatus: KeywordPatentMappingStatus | null = null,
): void {
this.patentMatchesBase.set(matches);
this.patentMatches.set(matches);
this.mappingStatus.set(mappingStatus);
this.updateDisplayedMatches();
writePatentsCache(
this.state.keywords(),
this.patentMatchesBase(),
mappingStatus,
);
}
private updateDisplayedMatches(): void {
const base = this.patentMatchesBase();
if (!canReweightPatentMatches(base)) {
this.patentMatches.set(base);
return;
}
const weights = normalizePatentScoreWeights(
this.currentWeights().normalized,
);
this.patentMatches.set(applyPatentScoreWeights(base, weights));
writePatentsCache(this.state.keywords(), matches, mappingStatus);
}
}
@@ -123,22 +123,22 @@
<h4>Publikationen</h4>
<ul class="publication-list">
@for (id of getSelectedPublicationIdsPage(); track id) {
<li class="publication-item" (click)="togglePublication(id)">
<li class="publication-item">
<span class="publication-title">
{{ getPublicationTitle(id) }}
@if (expandedPublicationId === id) {
<a
class="publication-more-info"
title="Publikationsdetails öffnen"
[routerLink]="['/publication', getShortPublicationId(id)]"
[state]="{
returnUrl: getCurrentUrl(),
returnLabel: 'Förderungen',
}"
(click)="$event.stopPropagation()">
<span class="material-icons">open_in_new</span>
</a>
}
<a
class="publication-more-info"
title="Publikationsdetails öffnen"
[routerLink]="[
'/publication',
getShortPublicationId(id),
]"
[state]="{
returnUrl: getCurrentUrl(),
returnLabel: 'Förderungen',
}">
<span class="material-icons">open_in_new</span>
</a>
</span>
</li>
}
@@ -39,21 +39,14 @@ app-query-param-paginator {
table {
width: 100%;
border-collapse: separate;
border-spacing: 0;
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm);
overflow: hidden;
border-collapse: collapse;
th {
text-align: left;
padding: 12px 16px;
background: var(--sg-surface-muted);
border-bottom: 1px solid var(--sg-border);
font-size: 12px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.02em;
font-size: 13px;
font-weight: 600;
color: var(--sg-text-muted);
}
@@ -68,10 +61,6 @@ app-query-param-paginator {
&.selected td {
background: var(--sg-primary-soft);
}
&:last-child td {
border-bottom: 0;
}
}
td {
@@ -97,24 +86,19 @@ app-query-param-paginator {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 26px;
padding: 2px 8px;
border-radius: 999px;
font-size: 12px;
min-width: 20px;
font-size: 13px;
font-weight: 700;
&--first {
background: #effaf3;
color: #24834f;
}
&--middle {
background: #f6f0ff;
color: #7255d9;
}
&--last {
background: #fff1f2;
color: #be123c;
}
}
@@ -396,7 +380,6 @@ app-query-param-paginator {
.publication-item {
padding: 10px 14px;
border-bottom: 1px solid var(--sg-border);
cursor: pointer;
transition: background-color 0.15s ease;
&:last-child {
@@ -56,7 +56,6 @@ export class PersonFundingComponent implements OnInit {
sortMode: SortMode = 'name';
loading = true;
error = false;
expandedPublicationId: string | null = null;
ngOnInit(): void {
this.route.parent?.paramMap.subscribe((params) => {
@@ -345,10 +344,6 @@ export class PersonFundingComponent implements OnInit {
return parts[parts.length - 1] ?? publicationId;
}
togglePublication(id: string): void {
this.expandedPublicationId = this.expandedPublicationId === id ? null : id;
}
getCurrentUrl(): string {
return this.router.url;
}
@@ -44,21 +44,14 @@ app-query-param-paginator {
table {
width: 100%;
border-collapse: separate;
border-spacing: 0;
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm);
overflow: hidden;
border-collapse: collapse;
th {
text-align: left;
padding: 12px 16px;
background: var(--sg-surface-muted);
border-bottom: 1px solid var(--sg-border);
font-size: 12px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.02em;
font-size: 13px;
font-weight: 600;
color: var(--sg-text-muted);
}
@@ -74,10 +67,6 @@ app-query-param-paginator {
&.selected td {
background: var(--sg-primary-soft);
}
&:last-child td {
border-bottom: 0;
}
}
td {