feat(keywords): IPC clustering
LocationBasedServices/smartguide/pipeline/head This commit looks good

This commit is contained in:
2026-07-17 10:08:29 +02:00
parent 807a32eb5a
commit a25b2ce248
14 changed files with 2212 additions and 404 deletions
File diff suppressed because it is too large Load Diff
@@ -5,6 +5,13 @@ from pydantic import BaseModel, Field
from inse.patents.common.model import PatentEntry
KeywordPatentLevel = Literal["broad", "coarse", "fine", "custom"]
KeywordPatentMappingStatus = Literal[
"mapped",
"uncertain",
"no_mapping",
"no_patents_found",
"search_error",
]
class KeywordPatentSearchItem(BaseModel):
@@ -42,16 +49,86 @@ class PatentsByKeywordsRequest(BaseModel):
)
class KeywordEvidence(BaseModel):
"""Traceable title/abstract evidence for keyword text retrieval."""
phrase_in_title: bool = False
phrase_in_abstract: bool = False
full_token_match: bool = False
partial_token_match: bool = False
word_match_score: float = 0.0
matched_phrases: list[str] = Field(default_factory=list)
matched_words: list[str] = Field(default_factory=list)
text_match_kind: str = Field(
default="none",
description=(
"phrase_title | phrase_abstract | full_token | partial_token | none"
),
)
class KeywordPatentMatch(BaseModel):
patent: PatentEntry
match_score: float = Field(description="Combined match quality score.")
ipc_score: float = Field(description="IPC/CPC classification match score.")
topic_score: float = Field(description="OpenAlex topic overlap score (0 or 1).")
topic_score: float = Field(
description=(
"Graded OpenAlex topic overlap: 1.0 topic_id, 0.7 subfield, "
"0.3 compatible field, 0.0 none."
),
)
text_score: float = Field(description="Title/abstract keyword overlap score.")
matched_keywords: list[str] = Field(default_factory=list)
matched_ipc_symbols: list[str] = Field(default_factory=list)
text_retrieval: bool = Field(
default=False,
description=(
"True when the patent was retrieved via title/abstract keyword search "
"because IPC mapping was uncertain, missing, or yielded no hits."
),
)
keyword_evidence: KeywordEvidence | None = Field(
default=None,
description="Structured text evidence when text_retrieval is true.",
)
topic_match_kind: str | None = Field(
default=None,
description="topic_id | subfield | compatible_field | none",
)
class KeywordPatentSearchDiagnostics(BaseModel):
"""Pipeline counters for evaluation (no effect on ranking thresholds)."""
search_path: str = Field(
description="ipc | text | none",
)
es_query_size_per_index: int = 0
raw_patents_after_dedupe: int = 0
filtered_by_ipc: int = 0
filtered_by_relevance_gate: int = 0
filtered_by_min_score: int = 0
passed_relevance_gate: int = 0
scored_before_cap: int = 0
returned: int = 0
max_patents_cap: int = 0
hit_return_cap: bool = False
ipc_cluster_selections: list[dict] = Field(default_factory=list)
class PatentsByKeywordsResponse(BaseModel):
patent_count: int
patents: list[KeywordPatentMatch]
mapping_status: KeywordPatentMappingStatus = Field(
description=(
"IPC mapping outcome: mapped (IPC used), uncertain (fragmented evidence; "
"may include text-retrieved patents), no_mapping (no usable IPC evidence; "
"may include text-retrieved patents), no_patents_found (neither IPC nor "
"keyword text search produced relevant patents), or search_error (technical "
"failure talking to the search backend)."
),
)
diagnostics: KeywordPatentSearchDiagnostics | None = Field(
default=None,
description="Optional search-pipeline counters for evaluation/debugging.",
)
@@ -24,10 +24,11 @@ logger = logging.getLogger(__name__)
_LEVEL_WEIGHTS = {
"subgroup": 1.0,
"group": 0.92,
"subclass": 0.85,
"class": 0.75,
"section": 0.6,
# Subclass is allowed but clearly weaker than group/subgroup.
"subclass": 0.70,
# Section/class are excluded from keyword→patent retrieval.
}
_EXCLUDED_IPC_LEVELS = frozenset({"section", "class"})
@dataclass(frozen=True)
@@ -37,6 +38,7 @@ class IpcCodeMatch:
match_score: float
source_keyword: str
match_type: str
topic_id: str | None = None
def _keyword_variants(keyword: str) -> list[str]:
@@ -83,7 +85,11 @@ def _weighted_score(
relevance_score 0.0 while still mapping to valid OpenAlex topics.
"""
_ = relevance_score
level_weight = _LEVEL_WEIGHTS.get(ipc_level, 0.7)
if ipc_level in _EXCLUDED_IPC_LEVELS:
return 0.0
level_weight = _LEVEL_WEIGHTS.get(ipc_level)
if level_weight is None:
return 0.0
return round(base_score * level_weight, 4)
@@ -138,15 +144,46 @@ def clear_reverse_lookup_caches() -> None:
_build_json_inverted_index.cache_clear()
def _item_topic_id(item: KeywordPatentSearchItem) -> str | None:
variants = _topic_id_variants_for_item(item)
if not variants:
return None
for variant in variants:
short = normalize_openalex_id(variant)
if short:
return short
return variants[0]
def _topic_group_key(topic_id: str | None, source_keyword: str = "") -> str:
"""Stable topic bucket for evidence; must stay aligned with cluster grouping."""
if topic_id:
short = normalize_openalex_id(topic_id)
return short or topic_id.strip()
keyword = (source_keyword or "").strip()
return f"keyword:{keyword.casefold() or 'unknown'}"
def _merge_ipc_match(
matches: dict[tuple[str, str], IpcCodeMatch],
matches: dict[tuple[str, str, str], IpcCodeMatch],
level: str,
symbol: str,
score: float,
source_keyword: str,
match_type: str,
topic_id: str | None = None,
) -> None:
key = (level, normalize_symbol(symbol))
"""Merge by topic × level × symbol so evidence for distinct topics is preserved.
Global symbol collapse happens only after per-topic cluster selection.
"""
if level in _EXCLUDED_IPC_LEVELS or score <= 0:
return
key = (
_topic_group_key(topic_id, source_keyword),
level,
normalize_symbol(symbol),
)
existing = matches.get(key)
if existing is None or score > existing.match_score:
matches[key] = IpcCodeMatch(
@@ -155,6 +192,7 @@ def _merge_ipc_match(
match_score=score,
source_keyword=source_keyword,
match_type=match_type,
topic_id=topic_id,
)
@@ -166,10 +204,13 @@ def _matches_from_doc(
ipc_symbol = normalize_symbol(str(doc.get("ipc_symbol") or ""))
if not ipc_level or not ipc_symbol:
return []
if ipc_level in _EXCLUDED_IPC_LEVELS:
return []
keyword_variants = set(_keyword_variants(item.keyword))
topic_variants = set(_topic_id_variants_for_item(item))
topic_name = (item.topic_display_name or "").strip().casefold()
topic_id = _item_topic_id(item)
found: list[IpcCodeMatch] = []
for match in doc.get("keyword_matches") or []:
@@ -183,6 +224,8 @@ def _matches_from_doc(
float(match.get("match_score") or 0.0),
item.relevance_score,
)
if score <= 0:
break
found.append(
IpcCodeMatch(
ipc_level=ipc_level,
@@ -190,6 +233,7 @@ def _matches_from_doc(
match_score=score,
source_keyword=item.keyword,
match_type="keyword",
topic_id=topic_id,
)
)
break
@@ -206,6 +250,8 @@ def _matches_from_doc(
float(match.get("match_score") or 0.0),
item.relevance_score,
)
if score <= 0:
break
found.append(
IpcCodeMatch(
ipc_level=ipc_level,
@@ -213,6 +259,7 @@ def _matches_from_doc(
match_score=score,
source_keyword=item.keyword,
match_type="topic",
topic_id=topic_id,
)
)
break
@@ -222,15 +269,22 @@ def _matches_from_doc(
def _json_lookup(items: list[KeywordPatentSearchItem]) -> list[IpcCodeMatch]:
by_keyword, by_topic = _build_json_inverted_index()
merged: dict[tuple[str, str], IpcCodeMatch] = {}
merged: dict[tuple[str, str, str], IpcCodeMatch] = {}
for item in items:
topic_id = _item_topic_id(item)
for level, symbol, base_score, source_keyword, match_type in by_keyword.get(
item.keyword.strip().casefold(), []
):
score = _weighted_score(level, base_score, item.relevance_score)
_merge_ipc_match(
merged, level, symbol, score, item.keyword, match_type
merged,
level,
symbol,
score,
item.keyword,
match_type,
topic_id=topic_id,
)
for variant in _topic_id_variants_for_item(item):
@@ -239,14 +293,20 @@ def _json_lookup(items: list[KeywordPatentSearchItem]) -> list[IpcCodeMatch]:
):
score = _weighted_score(level, base_score, item.relevance_score)
_merge_ipc_match(
merged, level, symbol, score, item.keyword, match_type
merged,
level,
symbol,
score,
item.keyword,
match_type,
topic_id=topic_id,
)
return sorted(merged.values(), key=lambda match: match.match_score, reverse=True)
def _dedupe_ipc_matches(matches: list[IpcCodeMatch]) -> list[IpcCodeMatch]:
merged: dict[tuple[str, str], IpcCodeMatch] = {}
merged: dict[tuple[str, str, str], IpcCodeMatch] = {}
for match in matches:
_merge_ipc_match(
merged,
@@ -255,6 +315,7 @@ def _dedupe_ipc_matches(matches: list[IpcCodeMatch]) -> list[IpcCodeMatch]:
match.match_score,
match.source_keyword,
match.match_type,
topic_id=match.topic_id,
)
return sorted(merged.values(), key=lambda match: match.match_score, reverse=True)
@@ -336,8 +397,13 @@ class KeywordIpcReverseLookup:
self,
items: list[KeywordPatentSearchItem],
*,
max_codes: int = 40,
max_codes: int | None = 200,
) -> list[IpcCodeMatch]:
"""Return mapping candidates for downstream cluster selection.
``max_codes`` caps raw candidates *after* dedupe. Pass a high value (or
``None``) so relative cluster mass is not distorted by early truncation.
"""
if not items:
return []
@@ -360,6 +426,8 @@ class KeywordIpcReverseLookup:
)
matches = _dedupe_ipc_matches(matches)
if max_codes is None:
return matches
return matches[:max_codes]
async def _lookup_via_elasticsearch(
@@ -394,7 +462,7 @@ class KeywordIpcReverseLookup:
response.raise_for_status()
data = response.json()
merged: dict[tuple[str, str], IpcCodeMatch] = {}
merged: dict[tuple[str, str, str], IpcCodeMatch] = {}
for hit in data.get("hits", {}).get("hits", []):
doc = hit.get("_source", {})
for item in items:
@@ -406,6 +474,7 @@ class KeywordIpcReverseLookup:
match.match_score,
match.source_keyword,
match.match_type,
topic_id=match.topic_id,
)
return sorted(merged.values(), key=lambda match: match.match_score, reverse=True)
@@ -4,7 +4,7 @@ from __future__ import annotations
from typing import Any
from inse.patents.common.elastic_search_client import DEFAULT_SEARCH_SIZE
from inse.patents.ipc_lookup import parse_ipc_symbol
from inse.patents.ipc_lookup import display_ipc_symbol, parse_ipc_symbol
from inse.patents.patents_openalex_keywords.ipc_entries import infer_subclass, normalize_symbol
_PATENT_SOURCE_FIELDS = [
@@ -43,60 +43,201 @@ _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 _search_terms_for_symbol(symbol: str) -> list[str]:
"""Derive EPO/USPTO `match` terms from an IPC/CPC symbol.
def _add_term_boost(weights: dict[str, float], term: str, boost: float) -> None:
cleaned = term.strip()
if len(cleaned) < _MIN_MATCH_TERM_LEN:
return
weights[cleaned] = max(weights.get(cleaned, 0.0), boost)
def _weighted_search_terms_for_symbol(symbol: str) -> dict[str, float]:
"""Derive EPO/USPTO `match` terms with specificity boosts.
Patent indices store IPC values like ``B60L 53/14 20060101AFI...``.
Wildcard/prefix on normalized symbols (``B60L*``) does not match; ``match``
on subclass codes (``B60L``) does.
on subclass / group tokens does. Concrete group/subgroup terms are boosted
above broad subclass prefixes.
"""
normalized = normalize_symbol(symbol)
if not normalized:
return []
terms: list[str] = []
subclass = infer_subclass(normalized)
if subclass and len(subclass) >= _MIN_MATCH_TERM_LEN:
terms.append(subclass)
return {}
weights: dict[str, float] = {}
keys = parse_ipc_symbol(normalized)
subclass = infer_subclass(normalized)
if not subclass and keys is not None and keys.subclass:
subclass = normalize_symbol(keys.subclass)
def add_symbol_forms(value: str | None, boost: float) -> None:
if not value:
return
norm = normalize_symbol(value)
if not norm:
return
_add_term_boost(weights, norm, boost)
display = display_ipc_symbol(norm)
if display and display != norm:
_add_term_boost(weights, display, boost)
if keys is not None:
if keys.subclass and len(keys.subclass) >= _MIN_MATCH_TERM_LEN:
terms.append(normalize_symbol(keys.subclass))
if keys.main_group and len(normalize_symbol(keys.main_group)) >= _MIN_MATCH_TERM_LEN:
terms.append(normalize_symbol(keys.main_group))
if keys.subgroup:
add_symbol_forms(keys.subgroup, _BOOST_SUBGROUP)
if keys.main_group:
main_group = normalize_symbol(keys.main_group)
# Short subgroup digits are folded into main_group by the parser
# (e.g. C07C243/08) — treat those leaf symbols as subgroup-level.
if keys.subgroup is None and "/" in main_group:
add_symbol_forms(main_group, _BOOST_SUBGROUP)
else:
add_symbol_forms(main_group, _BOOST_MAIN_GROUP)
if len(normalized) >= _MIN_MATCH_TERM_LEN:
prefix = normalized[:_MIN_MATCH_TERM_LEN]
if prefix not in terms:
terms.append(prefix)
if subclass:
add_symbol_forms(subclass, _BOOST_SUBCLASS)
elif len(normalized) >= _MIN_MATCH_TERM_LEN:
_add_term_boost(weights, normalized[:_MIN_MATCH_TERM_LEN], _BOOST_SUBCLASS)
return list(dict.fromkeys(term for term in terms if len(term) >= _MIN_MATCH_TERM_LEN))
return weights
def _ipc_match_clauses(field: str, terms: list[str]) -> list[dict[str, Any]]:
def _search_terms_for_symbol(symbol: str) -> list[str]:
"""Derive EPO/USPTO `match` terms from an IPC/CPC symbol (boost order)."""
weights = _weighted_search_terms_for_symbol(symbol)
return [
term
for term, _boost in sorted(
weights.items(),
key=lambda item: (-item[1], -len(item[0]), item[0]),
)
]
def _merge_term_boosts(symbols: list[str]) -> dict[str, float]:
merged: dict[str, float] = {}
for symbol in symbols:
for term, boost in _weighted_search_terms_for_symbol(symbol).items():
merged[term] = max(merged.get(term, 0.0), boost)
return merged
def _ipc_match_clauses(field: str, term_boosts: dict[str, float]) -> list[dict[str, Any]]:
clauses: list[dict[str, Any]] = []
seen: set[tuple[str, str]] = set()
for term in terms:
for term, boost in sorted(
term_boosts.items(),
key=lambda item: (-item[1], -len(item[0]), item[0]),
):
if len(term) < _MIN_MATCH_TERM_LEN:
continue
key = (field, term)
clauses.append(
{
"match": {
field: {
"query": term,
"boost": boost,
}
}
}
)
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)
clauses.append({"match": {field: term}})
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,
terms: list[str],
terms: list[str] | dict[str, float],
size: int = DEFAULT_SEARCH_SIZE,
) -> dict[str, Any]:
should = _ipc_match_clauses("ipc", terms) + _ipc_match_clauses("cpc", terms)
term_boosts = (
terms
if isinstance(terms, dict)
else {term: _BOOST_SUBCLASS for term in terms}
)
should = _ipc_match_clauses("ipc", term_boosts) + _ipc_match_clauses(
"cpc", term_boosts
)
query: dict[str, Any] = (
{"match_none": {}}
if not should
@@ -106,8 +247,8 @@ class IpcPatentSearchQueries:
"size": size,
"track_total_hits": True,
"sort": [
{"_score": {"order": "desc"}},
{"date_publication": {"order": "desc", "missing": "_last"}},
"_doc",
],
"_source": _PATENT_SOURCE_FIELDS,
"query": query,
@@ -115,10 +256,17 @@ class IpcPatentSearchQueries:
def uspto_query_by_ipc_terms(
self,
terms: list[str],
terms: list[str] | dict[str, float],
size: int = DEFAULT_SEARCH_SIZE,
) -> dict[str, Any]:
should = _ipc_match_clauses("ipcr", terms) + _ipc_match_clauses("cpc", terms)
term_boosts = (
terms
if isinstance(terms, dict)
else {term: _BOOST_SUBCLASS for term in terms}
)
should = _ipc_match_clauses("ipcr", term_boosts) + _ipc_match_clauses(
"cpc", term_boosts
)
query: dict[str, Any] = (
{"match_none": {}}
if not should
@@ -128,8 +276,8 @@ class IpcPatentSearchQueries:
"size": size,
"track_total_hits": True,
"sort": [
{"_score": {"order": "desc"}},
{"publication_date": {"order": "desc", "missing": "_last"}},
"_doc",
],
"_source": _USPTO_SOURCE_FIELDS,
"query": query,
@@ -140,27 +288,63 @@ class IpcPatentSearchQueries:
symbols: list[str],
size: int = DEFAULT_SEARCH_SIZE,
) -> dict[str, Any]:
terms: list[str] = []
seen: set[str] = set()
for symbol in symbols:
for term in _search_terms_for_symbol(symbol):
if term in seen:
continue
seen.add(term)
terms.append(term)
return self.epo_query_by_ipc_terms(terms, size=size)
return self.epo_query_by_ipc_terms(_merge_term_boosts(symbols), size=size)
def uspto_query_by_ipc_symbols(
self,
symbols: list[str],
size: int = DEFAULT_SEARCH_SIZE,
) -> dict[str, Any]:
terms: list[str] = []
seen: set[str] = set()
for symbol in symbols:
for term in _search_terms_for_symbol(symbol):
if term in seen:
continue
seen.add(term)
terms.append(term)
return self.uspto_query_by_ipc_terms(terms, size=size)
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,
}
@@ -4,32 +4,49 @@ from __future__ import annotations
import asyncio
from unittest.mock import AsyncMock, patch
import httpx
from inse.patents.authors.ipc_openalex_mapping import MappedOpenAlexTopic
from inse.patents.common import model
from inse.patents.keywords.logic import (
TopicEvidence,
_compute_final_score,
_compute_topic_evidence,
_collect_keyword_text_evidence,
_exact_topic_or_subfield_match,
_keyword_text_passes_relevance_gate,
_keyword_text_score,
_filter_keywords_for_patent_search,
_ipc_hierarchy_quality,
_keyword_is_patent_searchable,
_limit_matches_per_keyword,
_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,
_topic_passes_relevance_gate,
_topics_overlap_keywords,
_usable_ipc_matches,
get_patents_by_keywords,
select_ipc_matches_by_cluster_mass,
)
from inse.patents.keywords.reverse_lookup import (
IpcCodeMatch,
_dedupe_ipc_matches,
_json_lookup,
_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
from inse.patents.keywords.search_queries import (
IpcPatentSearchQueries,
_search_terms_for_symbol,
_weighted_search_terms_for_symbol,
)
def test_ipc_hierarchy_quality_exact_match() -> None:
@@ -74,7 +91,166 @@ def test_patent_search_terms_deduplicates_chemistry_subclasses() -> None:
IpcCodeMatch("subgroup", "B01J2219/00709", 0.8679, "Organische Chemie", "keyword"),
]
terms = _patent_search_terms(ipc_matches)
assert terms == ["C25B", "C07C", "C09B", "D06L", "C02F", "B01J"]
assert "C25B3/03" in terms
assert "C07C243/08" in terms
assert "C09B68/48" in terms
assert terms.count("C09B68/48") == 1
def test_usable_ipc_matches_excludes_section_and_class() -> None:
matches = [
IpcCodeMatch("section", "C", 0.99, "Topic", "topic"),
IpcCodeMatch("class", "C07", 0.95, "Topic", "topic"),
IpcCodeMatch("subclass", "C07C", 0.80, "Topic", "topic"),
IpcCodeMatch("subgroup", "C07C243/08", 0.88, "Topic", "topic"),
]
usable = _usable_ipc_matches(matches)
levels = {match.ipc_level for match in usable}
assert "section" not in levels
assert "class" not in levels
assert levels <= {"subclass", "group", "subgroup"}
def test_cluster_mass_prefers_dense_subclass_over_single_outlier() -> None:
"""Many related subgroups in one subclass beat one high-score foreign outlier."""
matches = [
IpcCodeMatch("subgroup", "G01Q60/36", 0.95, "Robotics", "topic"),
IpcCodeMatch("subgroup", "B25J9/16", 0.78, "Robotics", "topic"),
IpcCodeMatch("subgroup", "B25J13/08", 0.76, "Robotics", "topic"),
IpcCodeMatch("subgroup", "B25J19/02", 0.74, "Robotics", "topic"),
IpcCodeMatch("group", "B25J9", 0.72, "Robotics", "topic"),
]
selected, selections = select_ipc_matches_by_cluster_mass(matches)
by_subclass = {selection.subclass: selection for selection in selections}
assert "B25J" in by_subclass
g01q = by_subclass.get("G01Q")
assert g01q is None or by_subclass["B25J"].cluster_mass > g01q.cluster_mass
assert by_subclass["B25J"].relative_mass == max(s.relative_mass for s in selections)
assert selected
assert all(match.match_type != "domain_preference" for match in selected)
def test_cluster_selection_works_for_unseen_battery_topic() -> None:
matches = [
IpcCodeMatch("subgroup", "H01M10/052", 0.88, "Battery technology", "topic", "TBAT"),
IpcCodeMatch("subgroup", "H01M4/58", 0.84, "Battery technology", "topic", "TBAT"),
IpcCodeMatch("subgroup", "H01M10/44", 0.80, "Battery technology", "topic", "TBAT"),
IpcCodeMatch("subgroup", "G01R31/36", 0.79, "Battery technology", "topic", "TBAT"),
]
selected, selections = select_ipc_matches_by_cluster_mass(matches)
assert selections
assert {s.topic_key for s in selections} == {"TBAT"}
assert all(s.cluster_mass > 0 for s in selections)
assert all(s.reason for s in selections)
terms = _patent_search_terms(selected)
assert terms
assert any(term.startswith("H01M") for term in terms)
def test_cluster_selection_works_for_unseen_quantum_topic() -> None:
matches = [
IpcCodeMatch("subgroup", "G06N10/00", 0.86, "Quantum computing", "topic", "TQ"),
IpcCodeMatch("subgroup", "G06N10/40", 0.83, "Quantum computing", "topic", "TQ"),
IpcCodeMatch("subclass", "G06N", 0.70, "Quantum computing", "topic", "TQ"),
IpcCodeMatch("subgroup", "H01L39/22", 0.75, "Quantum computing", "topic", "TQ"),
]
selected, selections = select_ipc_matches_by_cluster_mass(matches)
assert selections
g06n = next(s for s in selections if s.subclass == "G06N")
assert g06n.relative_mass > 0
assert all(m.ipc_level != "class" for m in selected)
assert "domain_preference" not in {m.match_type for m in selected}
def test_search_terms_prefer_specific_subgroup_symbol() -> None:
matches = [
IpcCodeMatch("subgroup", "G06N3/08", 0.84, "Neural nets", "topic", "TNN"),
]
terms = _patent_search_terms(matches)
assert terms[0] == "G06N3/08"
assert "G06N" in terms
def test_no_synthetic_matches_when_mapping_has_single_family() -> None:
"""Sole concentrated family is accepted; nothing else is invented."""
matches = [
IpcCodeMatch("subgroup", "C12Q1/68", 0.92, "Unknown Topic X", "topic", "TX"),
]
selected, selections = select_ipc_matches_by_cluster_mass(matches)
assert len(selections) == 1
assert selections[0].subclass == "C12Q"
assert selections[0].reason == "sole_cluster_evidence"
assert selected[0].match_type == "topic"
terms = _patent_search_terms(selected)
assert terms[0] == "C12Q1/68"
def test_fragmented_weak_clusters_yield_no_ipc_selection() -> None:
"""Many similarly weak subclasses must not force a fragmented pick."""
matches = [
IpcCodeMatch(
"subgroup",
f"A{index:02d}B1/00",
0.70,
"Flat Topic",
"topic",
"TFLAT",
)
for index in range(1, 16)
]
selected, selections = select_ipc_matches_by_cluster_mass(matches)
assert selections == []
assert selected == []
assert _patent_search_terms(selected) == []
def test_dedupe_preserves_same_symbol_for_distinct_topics() -> None:
"""Identical IPC symbols for different topics must not collapse before clustering."""
matches = [
IpcCodeMatch("subgroup", "G06N3/08", 0.80, "Neural nets", "topic", "TNN"),
IpcCodeMatch("subgroup", "G06N3/08", 0.75, "Robotics", "topic", "TROB"),
IpcCodeMatch("subgroup", "G06N3/08", 0.90, "Neural nets", "topic", "TNN"),
]
deduped = _dedupe_ipc_matches(matches)
by_topic = {match.topic_id: match for match in deduped}
assert set(by_topic) == {"TNN", "TROB"}
assert by_topic["TNN"].match_score == 0.90
assert by_topic["TROB"].match_score == 0.75
selected, selections = select_ipc_matches_by_cluster_mass(deduped)
assert {selection.topic_key for selection in selections} == {"TNN", "TROB"}
assert len(selected) == 1
assert selected[0].ipc_symbol == "G06N3/08"
assert selected[0].match_score == 0.90
def test_aggregate_subclass_clusters_sums_scores_without_second_level_weight() -> None:
matches = [
IpcCodeMatch("subgroup", "B60L50/50", 0.80, "EV", "topic", "TEV"),
IpcCodeMatch("subgroup", "B60L53/14", 0.80, "EV", "topic", "TEV"),
IpcCodeMatch("subclass", "B60L", 0.80, "EV", "topic", "TEV"),
]
clusters = _aggregate_subclass_clusters("TEV", matches)
assert len(clusters) == 1
assert clusters[0].subclass == "B60L"
assert abs(clusters[0].mass - 2.4) < 1e-9
def test_dominant_clusters_skip_low_mass_tail() -> None:
clusters = _aggregate_subclass_clusters(
"Topic",
[
IpcCodeMatch("subgroup", "A01B1/00", 0.90, "Topic", "topic"),
IpcCodeMatch("subgroup", "A01B3/00", 0.88, "Topic", "topic"),
IpcCodeMatch("subgroup", "A01B5/00", 0.86, "Topic", "topic"),
IpcCodeMatch("subgroup", "Z99Z1/00", 0.66, "Topic", "topic"),
],
)
selected = _select_dominant_clusters(clusters)
selected_subclasses = {cluster.subclass for cluster, _reason in selected}
assert "A01B" in selected_subclasses
# Tiny tail cluster should not be auto-selected.
assert "Z99Z" not in selected_subclasses
def test_score_ipc_match_returns_only_best_evidence() -> None:
@@ -148,6 +324,48 @@ def test_score_patent_uses_best_ipc_match() -> None:
assert "G01S" in symbols
def test_compute_topic_evidence_is_graded() -> None:
topics = [
MappedOpenAlexTopic(
topic_id="https://openalex.org/T999",
subfield_name="Organic Chemistry",
field_name="Chemistry",
)
]
exact = _compute_topic_evidence(
topics,
frozenset({"T999"}),
frozenset({"organic chemistry"}),
frozenset({"chemistry"}),
)
assert exact.match_kind == "topic_id"
assert exact.score == 1.0
subfield = _compute_topic_evidence(
topics,
frozenset({"TOTHER"}),
frozenset({"organic chemistry"}),
frozenset({"chemistry"}),
)
assert subfield.match_kind == "subfield"
assert subfield.score == 0.7
field_only = _compute_topic_evidence(
[
MappedOpenAlexTopic(
topic_id="https://openalex.org/T1",
field_name="Materials Science",
)
],
frozenset({"TOTHER"}),
frozenset({"organic chemistry"}),
frozenset({"chemistry"}),
)
assert field_only.match_kind == "compatible_field"
assert field_only.score == 0.3
assert not _topic_passes_relevance_gate(field_only)
def test_score_patent_requires_topic_overlap() -> None:
patent = model.PatentEntry(
patent_id="EP123",
@@ -205,7 +423,45 @@ def test_score_patent_accepts_compatible_engineering_and_computer_science() -> N
)
],
)
# Compatible field alone is only a ranking signal; text evidence lets it pass.
assert result is not None
score, _keywords, _symbols = result
assert score == _compute_final_score(0.9 * 0.75, 0.3, 2 / 3)
def test_score_patent_rejects_compatible_field_without_text() -> None:
patent = model.PatentEntry(
patent_id="EP456",
source="EPO",
ipc=["G06N 3/08"],
title="Unrelated apparatus",
abstract="No topical keywords here.",
)
ipc_matches = [
IpcCodeMatch("subclass", "G06N", 0.9, "Deep Learning", "keyword"),
]
result = _score_patent(
patent,
ipc_matches,
patent_topics=[
MappedOpenAlexTopic(
topic_id="https://openalex.org/T12072",
field_name="Computer Science",
)
],
keyword_topic_ids=frozenset({"T10653"}),
keyword_subfield_names=frozenset({"control and systems engineering"}),
keyword_soft_field_names=frozenset({"engineering"}),
search_keywords=[
KeywordPatentSearchItem(
keyword="Deep Learning",
topic_id="https://openalex.org/T10653",
field_name="Engineering",
relevance_score=0.9,
)
],
)
assert result is None
def test_filter_keywords_for_patent_search_prefers_coarse_and_fine_over_broad() -> None:
@@ -346,21 +602,20 @@ def test_topics_overlap_keywords_rejects_patents_without_topics() -> None:
)
def test_limit_matches_per_keyword() -> None:
def test_selection_is_computed_per_topic_then_merged() -> None:
matches = [
IpcCodeMatch("subclass", "C07C", 0.95, "Organic Chemistry", "keyword"),
IpcCodeMatch("group", "C07C31", 0.9, "Organic Chemistry", "keyword"),
IpcCodeMatch("subclass", "C01B", 0.88, "Inorganic Chemistry", "keyword"),
IpcCodeMatch("subclass", "C01C", 0.87, "Inorganic Chemistry", "keyword"),
IpcCodeMatch("subgroup", "C07C243/08", 0.90, "Organic A", "keyword", "TORG"),
IpcCodeMatch("subgroup", "C07C31/20", 0.88, "Organic B", "keyword", "TORG"),
IpcCodeMatch("subgroup", "C01B3/00", 0.90, "Inorganic A", "keyword", "TINORG"),
IpcCodeMatch("subgroup", "C01C1/00", 0.88, "Inorganic B", "keyword", "TINORG"),
]
limited = _limit_matches_per_keyword(matches, limit=2)
assert len(limited) == 4
organic = [match for match in limited if match.source_keyword == "Organic Chemistry"]
inorganic = [match for match in limited if match.source_keyword == "Inorganic Chemistry"]
assert len(organic) == 2
assert len(inorganic) == 2
assert organic[0].ipc_symbol == "C07C"
assert inorganic[0].ipc_symbol == "C01B"
selected, selections = select_ipc_matches_by_cluster_mass(matches)
topics = {selection.topic_key for selection in selections}
assert topics == {"TORG", "TINORG"}
subclasses = {selection.subclass for selection in selections}
assert "C07C" in subclasses
assert "C01B" in subclasses or "C01C" in subclasses
assert selected
def test_text_overlap_score_uses_title_and_abstract() -> None:
@@ -377,6 +632,143 @@ def test_text_overlap_score_uses_title_and_abstract() -> None:
assert score == 1.0
def test_text_overlap_score_uses_word_boundaries_not_substrings() -> None:
patent = model.PatentEntry(
patent_id="EP1",
source="EPO",
title="Biochemistry overview",
abstract="Spectrochemical analysis.",
)
# "chemistry" must not match inside "biochemistry" / "spectrochemical".
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",
@@ -517,8 +909,10 @@ def test_get_patents_by_keywords_uses_symbol_queries() -> None:
epo_symbols.assert_called_once()
uspto_symbols.assert_called_once()
assert epo_symbols.call_args.args[0] == ["C07C"]
assert captured == ["epo", "uspto"]
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"]
def test_text_search_terms_include_topic_metadata() -> None:
@@ -541,8 +935,10 @@ def test_text_search_terms_include_topic_metadata() -> None:
def test_weighted_score_applies_level_not_llm_relevance() -> None:
score_high = _weighted_score("subclass", 0.8, 1.0)
score_zero = _weighted_score("subclass", 0.8, 0.0)
assert score_high == round(0.8 * 0.85, 4)
assert score_high == round(0.8 * 0.70, 4)
assert score_zero == score_high
assert _weighted_score("section", 0.9, 1.0) == 0.0
assert _weighted_score("class", 0.9, 1.0) == 0.0
def test_search_terms_use_subclass_prefix() -> None:
@@ -550,6 +946,233 @@ def test_search_terms_use_subclass_prefix() -> None:
assert "G06N" in _search_terms_for_symbol("G06N")
def test_search_terms_include_concrete_subgroup_and_main_group() -> None:
terms = _search_terms_for_symbol("B60R2300/8086")
assert "B60R2300/8086" in terms
assert "B60R2300/80" in terms
assert "B60R" in terms
weights = _weighted_search_terms_for_symbol("G06N3/08")
assert weights["G06N3/08"] > weights["G06N"]
assert weights["G06N3/08"] >= 4.0
def _match_boost(clauses: list[dict], field: str, term: str) -> float | None:
for clause in clauses:
payload = clause.get("match", {}).get(field)
if isinstance(payload, dict) and payload.get("query") == term:
return float(payload.get("boost", 1.0))
if payload == term:
return 1.0
return None
def test_epo_and_uspto_queries_boost_specific_symbols_over_subclass() -> None:
queries = IpcPatentSearchQueries()
epo = queries.epo_query_by_ipc_symbols(["G06N3/08", "G06N"])
uspto = queries.uspto_query_by_ipc_symbols(["G06N3/08", "G06N"])
epo_should = epo["query"]["bool"]["should"]
uspto_should = uspto["query"]["bool"]["should"]
epo_specific = _match_boost(epo_should, "ipc", "G06N3/08")
epo_subclass = _match_boost(epo_should, "ipc", "G06N")
uspto_specific = _match_boost(uspto_should, "ipcr", "G06N3/08")
uspto_subclass = _match_boost(uspto_should, "ipcr", "G06N")
assert epo_specific is not None and epo_subclass is not None
assert uspto_specific is not None and uspto_subclass is not None
assert epo_specific > epo_subclass
assert uspto_specific > uspto_subclass
assert _match_boost(epo_should, "cpc", "G06N3/08") == epo_specific
assert _match_boost(uspto_should, "cpc", "G06N3/08") == uspto_specific
assert epo["sort"][0] == {"_score": {"order": "desc"}}
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=[],
)
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": [],
}
}
]
}
}
async def fake_search_uspto(query):
return {"hits": {"hits": []}}
fragmented = [
IpcCodeMatch(
"subgroup",
f"A{index:02d}B1/00",
0.70,
"organische Chemie",
"topic",
"TORG",
)
for index in range(1, 16)
]
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=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": []}}),
), 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.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
def test_json_lookup_returns_empty_without_mapping(monkeypatch) -> None:
clear_reverse_lookup_caches()
monkeypatch.setattr(
@@ -0,0 +1,10 @@
export interface KeywordEvidence {
phrase_in_title?: boolean;
phrase_in_abstract?: boolean;
full_token_match?: boolean;
partial_token_match?: boolean;
word_match_score?: number;
matched_phrases?: Array<string>;
matched_words?: Array<string>;
text_match_kind?: string;
}
+27 -19
View File
@@ -1,23 +1,31 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { PatentEntry } from './patentEntry';
import { KeywordEvidence } from './keywordEvidence';
export interface KeywordPatentMatch {
patent: PatentEntry;
/**
* Combined match quality score.
*/
match_score: number;
ipc_score: number;
topic_score: number;
text_score: number;
matched_keywords?: Array<string>;
matched_ipc_symbols?: Array<string>;
patent: PatentEntry;
/**
* Combined match quality score.
*/
match_score: number;
/**
* IPC/CPC classification match score.
*/
ipc_score: number;
/**
* OpenAlex topic overlap score (0 or 1).
*/
topic_score: number;
/**
* Title/abstract keyword overlap score.
*/
text_score: number;
matched_keywords?: Array<string>;
matched_ipc_symbols?: Array<string>;
/**
* True when retrieved via title/abstract text search because IPC mapping was uncertain, missing, or yielded no hits.
*/
text_retrieval?: boolean;
keyword_evidence?: KeywordEvidence | null;
topic_match_kind?: string | null;
}
@@ -1,7 +1,7 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
@@ -10,8 +10,15 @@
import { KeywordPatentMatch } from './keywordPatentMatch';
export type KeywordPatentMappingStatus =
| 'mapped'
| 'uncertain'
| 'no_mapping'
| 'no_patents_found'
| 'search_error';
export interface PatentsByKeywordsResponse {
patent_count: number;
patents: Array<KeywordPatentMatch>;
mapping_status: KeywordPatentMappingStatus;
}
@@ -1,7 +1,11 @@
@if (loading()) {
<div class="patents-container">
<ng-container *ngTemplateOutlet="patentsHeader" />
<p class="message">Lade passende Patente...</p>
<app-loading
text="Patentdaten werden geladen..."
icon="workspace_premium"
[size]="150"
[diameter]="150" />
</div>
} @else if (error()) {
<div class="patents-container">
@@ -11,7 +15,7 @@
} @else if (matches().length === 0) {
<div class="patents-container">
<ng-container *ngTemplateOutlet="patentsHeader" />
<p class="message">Keine passenden Patente gefunden.</p>
<p class="message">{{ emptyMessage() }}</p>
</div>
} @else {
<div class="patents-container">
@@ -23,9 +27,7 @@
<thead>
<tr>
<th>Patent</th>
<th>Score</th>
<th>Quelle</th>
<th>Jahr</th>
</tr>
</thead>
<tbody>
@@ -36,7 +38,6 @@
<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--{{
@@ -45,7 +46,6 @@
{{ item.patent.source }}
</span>
</td>
<td>{{ item.patent.publication_year ?? '-' }}</td>
</tr>
}
</tbody>
@@ -72,22 +72,6 @@
<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">
@@ -3,6 +3,15 @@
color: #666;
}
.fallback-notice {
margin: 0 0 12px;
padding: 10px 12px;
border-radius: 8px;
background: #f4f7fb;
color: #3d4f63;
font-size: 0.9rem;
}
.section-title {
margin: 0;
font-size: 1.25rem;
@@ -5,6 +5,8 @@ import { MatIconModule } from '@angular/material/icon';
import { Router } from '@angular/router';
import { PatentEntry } from '../../../api/model/patentEntry';
import { KeywordPatentMatch } from '../../../api/model/keywordPatentMatch';
import { KeywordPatentMappingStatus } from '../../../api/model/patentsByKeywordsResponse';
import { LoadingComponent } from '../../../shared/ui/loading/loading.component';
import {
formatPatentDate,
getPublicationStageLabel,
@@ -14,12 +16,13 @@ type SourceFilter = 'all' | 'EPO' | 'USPTO';
@Component({
selector: 'app-keywords-patents',
imports: [NgTemplateOutlet, MatButtonModule, MatIconModule],
imports: [NgTemplateOutlet, MatButtonModule, MatIconModule, LoadingComponent],
templateUrl: './keywords-patents.component.html',
styleUrl: './keywords-patents.component.scss',
})
export class KeywordsPatentsComponent {
readonly matches = input<KeywordPatentMatch[]>([]);
readonly mappingStatus = input<KeywordPatentMappingStatus | null>(null);
readonly loading = input(false);
readonly error = input(false);
readonly showReload = input(false);
@@ -33,6 +36,15 @@ export class KeywordsPatentsComponent {
constructor(private readonly router: Router) {}
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';
}
}
filteredMatches(): KeywordPatentMatch[] {
const filter = this.activeFilter();
const items = this.matches();
@@ -87,20 +99,6 @@ export class KeywordsPatentsComponent {
return getPublicationStageLabel(patent);
}
formatScore(score: number | null | undefined): string {
if (score == null || Number.isNaN(score)) {
return '-';
}
return score.toFixed(2);
}
formatMatchList(values: string[] | null | undefined): string {
if (!values || values.length === 0) {
return '-';
}
return values.join(', ');
}
trackMatch(_index: number, item: KeywordPatentMatch): string {
const patent = item.patent;
return [
@@ -1,6 +1,9 @@
import { KeywordEntryWithTopic } from '../../api/model/keywordEntryWithTopic';
import { KeywordPatentMatch } from '../../api/model/keywordPatentMatch';
import { KeywordPatentSearchItem } from '../../api/model/keywordPatentSearchItem';
import {
KeywordPatentMappingStatus,
} from '../../api/model/patentsByKeywordsResponse';
import {
PatentKeywordEntry,
SearchResultsPayload,
@@ -8,9 +11,17 @@ import {
export const PATENTS_CACHE_KEY = 'keywords-patents-cache';
export type { KeywordPatentMappingStatus };
export interface PatentsCache {
keywords: string[];
matches: KeywordPatentMatch[];
mappingStatus?: KeywordPatentMappingStatus | null;
}
export interface PatentsCacheResult {
matches: KeywordPatentMatch[];
mappingStatus: KeywordPatentMappingStatus | null;
}
export function buildPatentSearchItems(
@@ -56,14 +67,17 @@ export function buildPatentSearchItemsFromPayload(
return buildPatentSearchItems(fallbackEntries);
}
export function readPatentsCache(keywords: string[]): KeywordPatentMatch[] | null {
export function readPatentsCache(keywords: string[]): PatentsCacheResult | null {
const raw = sessionStorage.getItem(PATENTS_CACHE_KEY);
if (!raw) return null;
try {
const cache = JSON.parse(raw) as PatentsCache;
if (!sameKeywordSet(cache.keywords, keywords)) return null;
return cache.matches ?? [];
return {
matches: cache.matches ?? [],
mappingStatus: cache.mappingStatus ?? null,
};
} catch {
sessionStorage.removeItem(PATENTS_CACHE_KEY);
return null;
@@ -73,9 +87,10 @@ export function readPatentsCache(keywords: string[]): KeywordPatentMatch[] | nul
export function writePatentsCache(
keywords: string[],
matches: KeywordPatentMatch[],
mappingStatus: KeywordPatentMappingStatus | null = null,
): void {
try {
const cache: PatentsCache = { keywords, matches };
const cache: PatentsCache = { keywords, matches, mappingStatus };
sessionStorage.setItem(PATENTS_CACHE_KEY, JSON.stringify(cache));
} catch (error) {
console.error('Failed to cache patent results:', error);
@@ -22,6 +22,7 @@
<div class="results-card">
<app-keywords-patents
[matches]="patentMatches()"
[mappingStatus]="mappingStatus()"
[loading]="loadingPatents()"
[error]="patentsError()"
[showReload]="state.hasValidSearch()"
@@ -6,7 +6,10 @@ 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 {
KeywordPatentMappingStatus,
PatentsByKeywordsResponse,
} from '../../../../api/model/patentsByKeywordsResponse';
import {
WeightMap,
WeightSliderOption,
@@ -83,6 +86,7 @@ export class KeywordsToPatentsResultsComponent implements OnInit {
});
readonly patentMatches = signal<KeywordPatentMatch[]>([]);
readonly mappingStatus = signal<KeywordPatentMappingStatus | null>(null);
readonly loadingPatents = signal(false);
readonly patentsError = signal(false);
@@ -91,7 +95,7 @@ export class KeywordsToPatentsResultsComponent implements OnInit {
ngOnInit(): void {
const cached = readPatentsCache(this.state.keywords());
if (cached) {
this.setPatentMatches(cached);
this.setPatentMatches(cached.matches, cached.mappingStatus);
return;
}
@@ -119,7 +123,7 @@ export class KeywordsToPatentsResultsComponent implements OnInit {
private loadMatchingPatents(): void {
const keywords = buildPatentSearchItemsFromPayload(this.state.payload());
if (keywords.length === 0) {
this.setPatentMatches([]);
this.setPatentMatches([], 'no_mapping');
return;
}
@@ -128,22 +132,33 @@ export class KeywordsToPatentsResultsComponent implements OnInit {
this.keywordsService.getPatentsByKeywords({ keywords }).subscribe({
next: (response: PatentsByKeywordsResponse) => {
this.setPatentMatches(response.patents ?? []);
this.setPatentMatches(
response.patents ?? [],
response.mapping_status ?? null,
);
this.loadingPatents.set(false);
},
error: (error: unknown) => {
console.error('Patent search failed:', error);
this.setPatentMatches([]);
this.setPatentMatches([], null);
this.patentsError.set(true);
this.loadingPatents.set(false);
},
});
}
private setPatentMatches(matches: KeywordPatentMatch[]): void {
private setPatentMatches(
matches: KeywordPatentMatch[],
mappingStatus: KeywordPatentMappingStatus | null = null,
): void {
this.patentMatchesBase.set(matches);
this.mappingStatus.set(mappingStatus);
this.updateDisplayedMatches();
writePatentsCache(this.state.keywords(), this.patentMatchesBase());
writePatentsCache(
this.state.keywords(),
this.patentMatchesBase(),
mappingStatus,
);
}
private updateDisplayedMatches(): void {