diff --git a/service/src/main/inse/patents/keywords/logic.py b/service/src/main/inse/patents/keywords/logic.py index 47e51161..1e030675 100644 --- a/service/src/main/inse/patents/keywords/logic.py +++ b/service/src/main/inse/patents/keywords/logic.py @@ -5,6 +5,7 @@ import asyncio import logging import math import re +from dataclasses import dataclass, field import httpx @@ -30,28 +31,60 @@ from inse.patents.ipc_lookup import ( ) from inse.patents.ipc_search_client import IpcSearchClient from inse.patents.keywords.model import ( + KeywordEvidence, + KeywordPatentMappingStatus, KeywordPatentMatch, + KeywordPatentSearchDiagnostics, KeywordPatentSearchItem, PatentsByKeywordsRequest, PatentsByKeywordsResponse, ) -from inse.patents.keywords.reverse_lookup import IpcCodeMatch, KeywordIpcReverseLookup -from inse.patents.keywords.search_queries import IpcPatentSearchQueries +from inse.patents.keywords.reverse_lookup import ( + IpcCodeMatch, + KeywordIpcReverseLookup, + _topic_group_key as _match_topic_group_key, +) +from inse.patents.keywords.search_queries import ( + IpcPatentSearchQueries, + _search_terms_for_symbol, +) from inse.patents.patents_openalex_keywords.ipc_entries import infer_subclass, normalize_symbol from inse.patents.patents_openalex_keywords.resolver import PatentOpenAlexMappingResolver logger = logging.getLogger(__name__) _MAX_PATENTS = 100 -_MAX_IPC_CODES = 20 -_MAX_IPC_CODES_PER_KEYWORD = 2 +# Raw mapping candidates before cluster selection (avoid early truncation bias). +_MAX_IPC_LOOKUP_CANDIDATES = 200 +_MAX_IPC_CODES_PER_KEYWORD = 3 +_MAX_CLUSTERS_PER_TOPIC = 3 _MAX_PATENT_SEARCH_TERMS = 10 _MAX_SEARCH_KEYWORDS = 10 _MIN_KEYWORD_RELEVANCE = 0.0 _MIN_IPC_MATCH_SCORE = 0.65 +# Concentration gates: fragmented distributions return no IPC codes. +_MIN_CLUSTER_RELATIVE_MASS = 0.15 +_MIN_CLUSTER_TAIL_MASS = 0.10 +_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 +# Section/class are excluded from retrieval; subclass is allowed but weaker. _SEARCHABLE_IPC_LEVELS = frozenset({"subgroup", "group", "subclass"}) +_EXCLUDED_IPC_LEVELS = frozenset({"section", "class"}) +# Level weighting is applied once in reverse_lookup (_LEVEL_WEIGHTS). +# Cluster mass uses those scores as-is — no second level discount here. +_IPC_LEVEL_RANK = {"subgroup": 3, "group": 2, "subclass": 1} # Soft field overlap for natural-science / engineering patent domains. _SOFT_MATCH_FIELD_NAMES = frozenset( { @@ -133,100 +166,301 @@ _TEXT_STOPWORDS = frozenset( ) +@dataclass +class IpcSubclassCluster: + """Aggregated IPC evidence for one topic/keyword × subclass.""" + + topic_key: str + subclass: str + mass: float + relative_mass: float = 0.0 + members: list[IpcCodeMatch] = field(default_factory=list) + + @property + def best_match(self) -> IpcCodeMatch: + return max( + self.members, + key=lambda match: ( + _IPC_LEVEL_RANK.get(match.ipc_level, 0), + match.match_score, + ), + ) + + +@dataclass(frozen=True) +class IpcClusterSelection: + topic_key: str + subclass: str + cluster_mass: float + relative_mass: float + match: IpcCodeMatch + reason: str + + def _ipc_section(symbol: str) -> str: normalized = normalize_symbol(symbol) return normalized[:1] if normalized else "" -def _dominant_ipc_sections(ipc_matches: list[IpcCodeMatch], limit: int = 2) -> set[str]: - weights: dict[str, float] = {} +def _evidence_weight(match: IpcCodeMatch) -> float: + """Cluster mass uses reverse-lookup scores (already level-weighted once).""" + return match.match_score + + +def _subclass_key(symbol: str) -> str | None: + normalized = normalize_symbol(symbol) + if not normalized: + return None + return infer_subclass(normalized) + + +def _usable_ipc_matches(ipc_matches: list[IpcCodeMatch]) -> list[IpcCodeMatch]: + """Keep only real subgroup/group/subclass matches above the score floor.""" + usable: list[IpcCodeMatch] = [] for match in ipc_matches: - section = _ipc_section(match.ipc_symbol) - if not section: + if match.ipc_level in _EXCLUDED_IPC_LEVELS: continue - weights[section] = weights.get(section, 0.0) + match.match_score - ranked = sorted(weights.items(), key=lambda item: item[1], reverse=True) - return {section for section, _ in ranked[:limit]} - - -def _prefer_searchable_ipc_levels(ipc_matches: list[IpcCodeMatch]) -> list[IpcCodeMatch]: - searchable = [ - match for match in ipc_matches if match.ipc_level in _SEARCHABLE_IPC_LEVELS - ] - return searchable if searchable else ipc_matches - - -def _filter_ipc_matches_for_search(ipc_matches: list[IpcCodeMatch]) -> list[IpcCodeMatch]: - if not ipc_matches: - return [] - - ipc_matches = _prefer_searchable_ipc_levels(ipc_matches) - ranked = sorted(ipc_matches, key=lambda match: match.match_score, reverse=True) - strong = [ - match - for match in ranked - if match.match_score >= _MIN_IPC_MATCH_SCORE - ] - if not strong: - return [] - - dominant_sections = _dominant_ipc_sections(strong) - filtered: list[IpcCodeMatch] = [] - seen: set[tuple[str, str]] = set() - for match in strong: - key = (match.ipc_level, match.ipc_symbol) - if key in seen: + if match.ipc_level not in _SEARCHABLE_IPC_LEVELS: continue - if match.match_score >= 0.8: - filtered.append(match) - seen.add(key) + if match.match_score < _MIN_IPC_MATCH_SCORE: continue - if _ipc_section(match.ipc_symbol) in dominant_sections: - filtered.append(match) - seen.add(key) - - return filtered + if _subclass_key(match.ipc_symbol) is None: + continue + usable.append(match) + return usable -def _limit_matches_per_keyword( +def _aggregate_subclass_clusters( + topic_key: str, matches: list[IpcCodeMatch], - limit: int = _MAX_IPC_CODES_PER_KEYWORD, -) -> list[IpcCodeMatch]: - grouped: dict[str, list[IpcCodeMatch]] = {} +) -> list[IpcSubclassCluster]: + buckets: dict[str, IpcSubclassCluster] = {} for match in matches: - grouped.setdefault(match.source_keyword.casefold(), []).append(match) + subclass = _subclass_key(match.ipc_symbol) + if not subclass: + continue + cluster = buckets.get(subclass) + if cluster is None: + cluster = IpcSubclassCluster(topic_key=topic_key, subclass=subclass, mass=0.0) + buckets[subclass] = cluster + cluster.mass += _evidence_weight(match) + cluster.members.append(match) - result: list[IpcCodeMatch] = [] - for keyword_matches in grouped.values(): - keyword_matches.sort(key=lambda match: match.match_score, reverse=True) - result.extend(keyword_matches[:limit]) + clusters = list(buckets.values()) + total_mass = sum(cluster.mass for cluster in clusters) + if total_mass <= 0: + return [] + for cluster in clusters: + cluster.relative_mass = cluster.mass / total_mass + return sorted(clusters, key=lambda item: item.mass, reverse=True) - return sorted(result, key=lambda match: match.match_score, reverse=True) + +def _select_dominant_clusters( + clusters: list[IpcSubclassCluster], +) -> list[tuple[IpcSubclassCluster, str]]: + """Pick dominant subclass clusters by relative mass / clear leadership. + + Fragmented distributions (many similarly weak clusters) return empty — + the caller should treat that as ``uncertain`` IPC evidence. + """ + if not clusters: + return [] + + if len(clusters) == 1: + return [(clusters[0], "sole_cluster_evidence")] + + selected: list[tuple[IpcSubclassCluster, str]] = [] + cumulative = 0.0 + + for cluster in clusters: + if len(selected) >= _MAX_CLUSTERS_PER_TOPIC: + break + + if cluster.relative_mass >= _MIN_CLUSTER_RELATIVE_MASS: + selected.append((cluster, "dominant_relative_mass")) + cumulative += cluster.relative_mass + continue + + if ( + selected + and cumulative < _TARGET_CUMULATIVE_CLUSTER_MASS + and cluster.relative_mass >= _MIN_CLUSTER_TAIL_MASS + ): + selected.append((cluster, "cumulative_mass_tail")) + cumulative += cluster.relative_mass + continue + + if selected: + break + + if not selected: + leader = clusters[0] + runner_up = clusters[1] + if ( + leader.relative_mass >= _MIN_LEADER_RELATIVE_MASS + and leader.mass >= runner_up.mass * _MIN_LEADER_MASS_RATIO + ): + selected.append((leader, "mass_leader_with_gap")) + + # No fragmented_top_mass fallback: weak/flat distributions stay empty. + return selected + + +def _select_ipc_matches_for_topic( + topic_key: str, + matches: list[IpcCodeMatch], +) -> list[IpcClusterSelection]: + usable = _usable_ipc_matches(matches) + clusters = _aggregate_subclass_clusters(topic_key, usable) + selected_clusters = _select_dominant_clusters(clusters) + + if not selected_clusters and clusters: + top = clusters[0] + logger.info( + "IPC cluster uncertain: topic=%s clusters=%d top_subclass=%s " + "top_relative_mass=%.4f top_cluster_mass=%.4f reason=fragmented_uncertain", + topic_key, + len(clusters), + top.subclass, + top.relative_mass, + top.mass, + ) + + selections: list[IpcClusterSelection] = [] + for cluster, reason in selected_clusters: + best = cluster.best_match + selections.append( + IpcClusterSelection( + topic_key=topic_key, + subclass=cluster.subclass, + cluster_mass=round(cluster.mass, 4), + relative_mass=round(cluster.relative_mass, 4), + match=best, + reason=reason, + ) + ) + return selections + + +def _topic_group_key(match: IpcCodeMatch) -> str: + """Group by OpenAlex topic_id when present; else fall back to keyword.""" + return _match_topic_group_key(match.topic_id, match.source_keyword) + + +def _group_matches_by_topic( + ipc_matches: list[IpcCodeMatch], +) -> dict[str, list[IpcCodeMatch]]: + grouped: dict[str, list[IpcCodeMatch]] = {} + for match in ipc_matches: + key = _topic_group_key(match) + grouped.setdefault(key, []).append(match) + return grouped + + +def select_ipc_matches_by_cluster_mass( + ipc_matches: list[IpcCodeMatch], +) -> tuple[list[IpcCodeMatch], list[IpcClusterSelection]]: + """Data-driven IPC selection from real patents_openalex_keywords matches. + + Evidence is aggregated per topic_id (or keyword) × subclass, then dominant + clusters are chosen by relative mass / leadership gap. Fragmented evidence + yields an empty selection (uncertain) — no synthetic IPC codes. + """ + selections: list[IpcClusterSelection] = [] + for topic_key, topic_matches in _group_matches_by_topic(ipc_matches).items(): + topic_selections = _select_ipc_matches_for_topic(topic_key, topic_matches) + for selection in topic_selections[:_MAX_IPC_CODES_PER_KEYWORD]: + selections.append(selection) + logger.info( + "IPC cluster selected: topic=%s subclass=%s level=%s symbol=%s " + "score=%.4f cluster_mass=%.4f relative_mass=%.4f reason=%s", + selection.topic_key, + selection.subclass, + selection.match.ipc_level, + selection.match.ipc_symbol, + selection.match.match_score, + selection.cluster_mass, + selection.relative_mass, + selection.reason, + ) + + # Merge across topics: keep best real match per symbol. + best_by_symbol: dict[str, IpcCodeMatch] = {} + for selection in selections: + symbol = normalize_symbol(selection.match.ipc_symbol) + existing = best_by_symbol.get(symbol) + if existing is None or selection.match.match_score > existing.match_score: + best_by_symbol[symbol] = selection.match + + selected_matches = sorted( + best_by_symbol.values(), + key=lambda match: ( + _IPC_LEVEL_RANK.get(match.ipc_level, 0), + match.match_score, + ), + reverse=True, + ) + return selected_matches, selections + + +def _preferred_retrieval_symbols(match: IpcCodeMatch) -> list[str]: + """Prefer specific real symbols (subgroup/group) over broad subclass alone.""" + symbol = normalize_symbol(match.ipc_symbol) + if not symbol: + return [] + + ordered: list[str] = [] + if match.ipc_level in {"subgroup", "group"}: + # Keep the concrete matched symbol first for query expansion. + ordered.append(symbol) + parsed = parse_ipc_symbol(symbol) + if parsed is not None and parsed.main_group: + main_group = normalize_symbol(parsed.main_group) + if main_group and main_group not in ordered: + ordered.append(main_group) + + subclass = _subclass_key(symbol) + if subclass and subclass not in ordered: + ordered.append(subclass) + return ordered def _term_from_ipc_match(match: IpcCodeMatch) -> str | None: - symbol = normalize_symbol(match.ipc_symbol) - if not symbol: - return None - - return infer_subclass(symbol) + """Derive subclass prefix from a real match (used by tests / helpers).""" + return _subclass_key(match.ipc_symbol) def _patent_search_terms(ipc_matches: list[IpcCodeMatch]) -> list[str]: - filtered = _filter_ipc_matches_for_search(ipc_matches) - filtered = sorted(filtered, key=lambda match: match.match_score, reverse=True) + """Build EPO/USPTO search symbols from selected real matches. + + Subgroup/group matches contribute their concrete symbols (and main-group) + before the broader subclass prefix. Nothing is injected without mapping + evidence. Query builders expand these via ``_search_terms_for_symbol``. + """ + ranked = sorted( + ipc_matches, + key=lambda match: ( + _IPC_LEVEL_RANK.get(match.ipc_level, 0), + match.match_score, + ), + reverse=True, + ) terms: list[str] = [] seen: set[str] = set() - for match in filtered: + for match in ranked: if match.ipc_level not in _SEARCHABLE_IPC_LEVELS: continue - term = _term_from_ipc_match(match) - if not term or term in seen: - continue - seen.add(term) - terms.append(term) - if len(terms) >= _MAX_PATENT_SEARCH_TERMS: - break + for symbol in _preferred_retrieval_symbols(match): + # Only keep symbols that expand to usable ES match terms. + expanded = _search_terms_for_symbol(symbol) + if not expanded: + continue + if symbol in seen: + continue + seen.add(symbol) + terms.append(symbol) + if len(terms) >= _MAX_PATENT_SEARCH_TERMS: + return terms return terms @@ -344,14 +578,6 @@ def _normalized_field_name(name: str | None) -> str: return (name or "").strip().casefold() -def _patent_has_g06_code(patent: model.PatentEntry) -> bool: - for code in (*patent.ipc, *patent.cpc): - symbol = normalize_symbol(extract_ipc_symbol(code) or code) - if symbol.startswith("G06"): - return True - return False - - def _compatible_patent_fields(keyword_field: str) -> frozenset[str]: return _COMPATIBLE_FIELDS.get(keyword_field, frozenset({keyword_field})) @@ -379,23 +605,27 @@ def _keyword_overlap_criteria( ) -def _topics_overlap_keywords( +@dataclass(frozen=True) +class TopicEvidence: + match_kind: str + score: float + + +@dataclass(frozen=True) +class TextGateDecision: + accepted: bool + reason: str + + +def _compute_topic_evidence( patent_topics: list[MappedOpenAlexTopic], keyword_topic_ids: frozenset[str], keyword_subfield_names: frozenset[str], keyword_soft_field_names: frozenset[str], - *, - patent: model.PatentEntry | None = None, -) -> bool: - if ( - not keyword_topic_ids - and not keyword_subfield_names - and not keyword_soft_field_names - ): - return True - +) -> TopicEvidence: + """Graded topic overlap used for ranking (field is weak signal only).""" if not patent_topics: - return False + return TopicEvidence(match_kind="none", score=0.0) patent_topic_ids = { topic_id @@ -403,7 +633,7 @@ def _topics_overlap_keywords( if (topic_id := normalize_openalex_id(mapped.topic_id)) } if keyword_topic_ids & patent_topic_ids: - return True + return TopicEvidence(match_kind="topic_id", score=_TOPIC_SCORE_TOPIC_ID) patent_subfield_names = { (mapped.subfield_name or "").strip().casefold() @@ -411,7 +641,7 @@ def _topics_overlap_keywords( if (mapped.subfield_name or "").strip() } if keyword_subfield_names & patent_subfield_names: - return True + return TopicEvidence(match_kind="subfield", score=_TOPIC_SCORE_SUBFIELD) if keyword_soft_field_names: patent_field_names = { @@ -421,17 +651,64 @@ def _topics_overlap_keywords( } for keyword_field in keyword_soft_field_names: if patent_field_names & _compatible_patent_fields(keyword_field): - return True - if ( - patent is not None - and _patent_has_g06_code(patent) - and keyword_soft_field_names & {"engineering", "computer science"} - ): - return True + return TopicEvidence( + match_kind="compatible_field", + score=_TOPIC_SCORE_COMPATIBLE_FIELD, + ) + return TopicEvidence(match_kind="none", score=0.0) + + +def _topics_overlap_keywords( + patent_topics: list[MappedOpenAlexTopic], + keyword_topic_ids: frozenset[str], + keyword_subfield_names: frozenset[str], + keyword_soft_field_names: frozenset[str], + *, + patent: model.PatentEntry | None = None, +) -> bool: + """True when any graded topic signal is present (including weak field).""" + _ = patent + if ( + not keyword_topic_ids + and not keyword_subfield_names + and not keyword_soft_field_names + ): + return True + return ( + _compute_topic_evidence( + patent_topics, + keyword_topic_ids, + keyword_subfield_names, + keyword_soft_field_names, + ).score + > 0.0 + ) + + +def _topic_passes_relevance_gate(topic_evidence: TopicEvidence) -> bool: + """Compatible field alone must not pass the gate — only ranking signal.""" + return topic_evidence.match_kind in {"topic_id", "subfield"} + + +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) + + def _text_search_terms(items: list[KeywordPatentSearchItem]) -> list[str]: terms: list[str] = [] seen: set[str] = set() @@ -442,14 +719,8 @@ def _text_search_terms(items: list[KeywordPatentSearchItem]) -> list[str]: item.topic_display_name, item.subfield_name, ): - normalized = (value or "").strip().casefold() - if not normalized: - continue - - words = re.findall(r"[a-zäöüß]{4,}", normalized) - - for word in words: - if word in _TEXT_STOPWORDS or word in seen: + for word in _tokenize_words(value or ""): + if len(word) < 4 or word in _TEXT_STOPWORDS or word in seen: continue seen.add(word) terms.append(word) @@ -457,23 +728,210 @@ 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], ) -> float: - text = " ".join( - part - for part in [patent.title or "", patent.abstract or ""] - if part - ).casefold() - - if not search_terms or not text.strip(): + tokens = _token_set( + _tokenize_words( + " ".join( + part + for part in [patent.title or "", patent.abstract or ""] + if part + ) + ) + ) + if not search_terms or not tokens: return 0.0 - hits = sum(1 for term in search_terms if term in text) + hits = sum(1 for term in search_terms if term in tokens) 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], *, @@ -483,14 +941,14 @@ def _patent_passes_relevance_gate( patent: model.PatentEntry, text_score: float, ) -> bool: - has_topic_match = bool(patent_topics) and _topics_overlap_keywords( + _ = patent + topic_evidence = _compute_topic_evidence( patent_topics, keyword_topic_ids, keyword_subfield_names, keyword_soft_field_names, - patent=patent, ) - return has_topic_match or text_score > 0.0 + return _topic_passes_relevance_gate(topic_evidence) or text_score > 0.0 def _normalize_score_weights( @@ -599,26 +1057,407 @@ def _score_patent( _text_search_terms(search_keywords), ) - has_topic_match = bool(patent_topics) and _topics_overlap_keywords( + topic_evidence = _compute_topic_evidence( patent_topics or [], keyword_topic_ids or frozenset(), keyword_subfield_names or frozenset(), keyword_soft_field_names or frozenset(), - patent=patent, ) - if not has_topic_match and text_score == 0.0: + if not _topic_passes_relevance_gate(topic_evidence) and text_score == 0.0: return None - topic_score = 1.0 if has_topic_match else 0.0 - return ( - _compute_final_score(ipc_score, topic_score, text_score), + _compute_final_score(ipc_score, topic_evidence.score, text_score), matched_keywords, matched_symbols, ) +async def _fetch_patents_for_queries( + client: BasePatentSearchClient, + epo_query: dict, + uspto_query: dict, +) -> list[model.PatentEntry] | None: + """Run EPO+USPTO search. Returns None on configuration/transport failure.""" + try: + epo_data, uspto_data = await asyncio.gather( + client.search_epo(epo_query), + client.search_uspto(uspto_query), + ) + except MissingApiKeyError: + logger.warning("Patent search skipped: Elasticsearch API key not configured.") + return None + except httpx.HTTPError as exc: + logger.warning("Patent search failed: %s", exc) + return None + + return deduplicate_patents(parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data)) + + +def _cluster_selection_dicts( + selections: list[IpcClusterSelection], +) -> list[dict]: + return [ + { + "topic_key": selection.topic_key, + "subclass": selection.subclass, + "symbol": selection.match.ipc_symbol, + "level": selection.match.ipc_level, + "match_score": selection.match.match_score, + "cluster_mass": selection.cluster_mass, + "relative_mass": selection.relative_mass, + "reason": selection.reason, + } + for selection in selections + ] + + +def _empty_diagnostics( + *, + search_path: str = "none", + ipc_cluster_selections: list[dict] | None = None, +) -> KeywordPatentSearchDiagnostics: + return KeywordPatentSearchDiagnostics( + search_path=search_path, + es_query_size_per_index=_MAX_PATENTS, + max_patents_cap=_MAX_PATENTS, + ipc_cluster_selections=list(ipc_cluster_selections or []), + ) + + +def _finalize_scored_patents( + scored: list[KeywordPatentMatch], + *, + raw_count: int, + filtered_by_ipc: int, + filtered_by_relevance_gate: int, + filtered_by_min_score: int, + passed_relevance_gate: int, + search_path: str, + ipc_cluster_selections: list[dict] | None = None, +) -> tuple[list[KeywordPatentMatch], KeywordPatentSearchDiagnostics]: + scored_before_cap = len(scored) + scored.sort( + key=lambda item: ( + item.match_score, + item.patent.publication_date or "", + item.patent.patent_id, + ), + reverse=True, + ) + returned = scored[:_MAX_PATENTS] + diagnostics = KeywordPatentSearchDiagnostics( + search_path=search_path, + es_query_size_per_index=_MAX_PATENTS, + raw_patents_after_dedupe=raw_count, + filtered_by_ipc=filtered_by_ipc, + filtered_by_relevance_gate=filtered_by_relevance_gate, + filtered_by_min_score=filtered_by_min_score, + passed_relevance_gate=passed_relevance_gate, + scored_before_cap=scored_before_cap, + returned=len(returned), + max_patents_cap=_MAX_PATENTS, + hit_return_cap=scored_before_cap >= _MAX_PATENTS, + ipc_cluster_selections=list(ipc_cluster_selections or []), + ) + return returned, diagnostics + + +async def _score_patents_with_ipc( + *, + raw_patents: list[model.PatentEntry], + ipc_matches: list[IpcCodeMatch], + 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]]: + patent_topics_by_key = await resolver.resolve_topics_for_patents(raw_patents) + scored: list[KeywordPatentMatch] = [] + filtered_by_ipc = 0 + 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), []) + ipc_result = _score_ipc_match(patent, ipc_matches) + if ipc_result is None: + filtered_by_ipc += 1 + continue + ipc_score, matched_keywords, matched_symbols = ipc_result + + topic_evidence = _compute_topic_evidence( + patent_topics, + keyword_topic_ids, + keyword_subfield_names, + keyword_soft_field_names, + ) + text_score = _text_overlap_score(patent, text_search_terms) + if not _topic_passes_relevance_gate(topic_evidence) and text_score == 0.0: + filtered_by_relevance_gate += 1 + logger.info( + "IPC path reject: id=%s topic_kind=%s topic_score=%.2f " + "text_score=%.2f reason=field_or_none_without_text", + patent.patent_id, + topic_evidence.match_kind, + topic_evidence.score, + text_score, + ) + continue + + passed_relevance_gate += 1 + score = _compute_final_score(ipc_score, topic_evidence.score, text_score) + if score < _MIN_PATENT_MATCH_SCORE: + filtered_by_min_score += 1 + continue + + logger.info( + "IPC path accept: id=%s topic_kind=%s topic_score=%.2f " + "text_score=%.2f final_score=%.4f", + patent.patent_id, + topic_evidence.match_kind, + topic_evidence.score, + text_score, + score, + ) + scored.append( + KeywordPatentMatch( + patent=patent, + match_score=score, + ipc_score=ipc_score, + topic_score=topic_evidence.score, + text_score=text_score, + matched_keywords=matched_keywords, + matched_ipc_symbols=matched_symbols, + text_retrieval=False, + topic_match_kind=topic_evidence.match_kind, + ) + ) + + logger.info( + "Keyword patent search: filtered_by_ipc=%d filtered_by_relevance_gate=%d " + "filtered_by_min_score=%d passed_relevance_gate=%d scored=%d", + filtered_by_ipc, + filtered_by_relevance_gate, + filtered_by_min_score, + passed_relevance_gate, + len(scored), + ) + return scored, { + "filtered_by_ipc": filtered_by_ipc, + "filtered_by_relevance_gate": filtered_by_relevance_gate, + "filtered_by_min_score": filtered_by_min_score, + "passed_relevance_gate": passed_relevance_gate, + } + + +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, *, @@ -639,7 +1478,12 @@ async def get_patents_by_keywords( "Keyword patent search: no searchable keywords in %s", [item.keyword for item in request.keywords], ) - return PatentsByKeywordsResponse(patent_count=0, patents=[]) + return PatentsByKeywordsResponse( + patent_count=0, + patents=[], + mapping_status="no_mapping", + diagnostics=_empty_diagnostics(search_path="none"), + ) logger.info( "Keyword patent search: using keywords=%s (from %d requested)", @@ -658,152 +1502,116 @@ async def get_patents_by_keywords( _keyword_overlap_criteria(search_keywords) ) - ipc_matches = await lookup.lookup_ipc_codes( + raw_ipc_matches = await lookup.lookup_ipc_codes( search_keywords, - max_codes=_MAX_IPC_CODES, + max_codes=_MAX_IPC_LOOKUP_CANDIDATES, ) - ipc_matches = _filter_ipc_matches_for_search(ipc_matches) - ipc_matches = _limit_matches_per_keyword(ipc_matches) + had_usable_mapping = bool(_usable_ipc_matches(raw_ipc_matches)) + ipc_matches, cluster_selections = select_ipc_matches_by_cluster_mass(raw_ipc_matches) + cluster_dicts = _cluster_selection_dicts(cluster_selections) logger.info( - "Keyword patent search: search_keywords=%s ipc_matches=%s", + "Keyword patent search: search_keywords=%s selected_ipc=%s", [item.keyword for item in search_keywords], - [ - { - "symbol": match.ipc_symbol, - "level": match.ipc_level, - "score": match.match_score, - "keyword": match.source_keyword, - } - for match in ipc_matches - ], + cluster_dicts, ) - if not ipc_matches: - logger.info( - "Keyword patent search: no IPC codes after filtering for keywords %s", - [item.keyword for item in search_keywords], - ) - return PatentsByKeywordsResponse(patent_count=0, patents=[]) - symbols = _patent_search_terms(ipc_matches) + if not symbols: + mapping_status: KeywordPatentMappingStatus = ( + "uncertain" if had_usable_mapping else "no_mapping" + ) + logger.info( + "Keyword patent search: no IPC search terms for keywords %s " + "(mapping_status=%s) — trying keyword text search", + [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, + mapping_status=mapping_status, + ipc_cluster_selections=cluster_dicts, + ) + text_search_terms = _text_search_terms(search_keywords) logger.info("Keyword patent search: patent_search_terms=%s", symbols) - if not symbols: - return PatentsByKeywordsResponse(patent_count=0, patents=[]) - try: - epo_data, uspto_data = await asyncio.gather( - client.search_epo( - queries.epo_query_by_ipc_symbols(symbols, size=_MAX_PATENTS) - ), - client.search_uspto( - queries.uspto_query_by_ipc_symbols(symbols, size=_MAX_PATENTS) - ), - ) - except MissingApiKeyError: - logger.warning("Patent search skipped: Elasticsearch API key not configured.") - return PatentsByKeywordsResponse(patent_count=0, patents=[]) - except httpx.HTTPError as exc: - logger.warning("Patent search failed: %s", exc) - return PatentsByKeywordsResponse(patent_count=0, patents=[]) - - raw_patents = deduplicate_patents( - parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data) + raw_patents = await _fetch_patents_for_queries( + client, + queries.epo_query_by_ipc_symbols(symbols, size=_MAX_PATENTS), + queries.uspto_query_by_ipc_symbols(symbols, size=_MAX_PATENTS), ) + if raw_patents is None: + return PatentsByKeywordsResponse( + patent_count=0, + patents=[], + mapping_status="search_error", + diagnostics=_empty_diagnostics( + search_path="ipc", + ipc_cluster_selections=cluster_dicts, + ), + ) + logger.info("Keyword patent search: raw_patents=%d", len(raw_patents)) - patent_topics_by_key = await resolver.resolve_topics_for_patents(raw_patents) + scored, filter_counts = await _score_patents_with_ipc( + raw_patents=raw_patents, + ipc_matches=ipc_matches, + 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=filter_counts["filtered_by_ipc"], + 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="ipc", + ipc_cluster_selections=cluster_dicts, + ) - scored: list[KeywordPatentMatch] = [] - filtered_by_ipc = 0 - filtered_by_relevance_gate = 0 - filtered_by_min_score = 0 - for patent in raw_patents: - patent_topics = patent_topics_by_key.get(patent_map_key(patent), []) - ipc_result = _score_ipc_match(patent, ipc_matches) - if ipc_result is None: - filtered_by_ipc += 1 - continue - ipc_score, matched_keywords, matched_symbols = ipc_result - - has_topic_match = bool(patent_topics) and _topics_overlap_keywords( - patent_topics, - keyword_topic_ids, - keyword_subfield_names, - keyword_soft_field_names, - patent=patent, + if scored: + await enrich_patents_classifications([item.patent for item in scored], ipc_search) + return PatentsByKeywordsResponse( + patent_count=len(scored), + patents=scored, + mapping_status="mapped", + diagnostics=diagnostics, ) - text_score = _text_overlap_score(patent, text_search_terms) - - if not has_topic_match and text_score == 0.0: - filtered_by_relevance_gate += 1 - continue - - topic_score = 1.0 if has_topic_match else 0.0 - - score = _compute_final_score(ipc_score, topic_score, text_score) - if score < _MIN_PATENT_MATCH_SCORE: - filtered_by_min_score += 1 - continue - - hierarchy_levels = sorted( - { - level - for symbol in matched_symbols - for code in (*patent.ipc, *patent.cpc) - if (level := _ipc_hierarchy_level(code, symbol)) - } - ) - logger.info( - "Patent candidate: id=%s title=%s ipc_score=%.4f " - "topic_score=%.4f text_score=%.4f final_score=%.4f " - "hierarchy_levels=%s matched_keywords=%s matched_symbols=%s", - patent.patent_id, - patent.title, - ipc_score, - topic_score, - text_score, - score, - hierarchy_levels, - matched_keywords, - matched_symbols, - ) - scored.append( - KeywordPatentMatch( - patent=patent, - match_score=score, - ipc_score=ipc_score, - topic_score=topic_score, - text_score=text_score, - matched_keywords=matched_keywords, - matched_ipc_symbols=matched_symbols, - ) + 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: filtered_by_ipc=%d filtered_by_relevance_gate=%d " - "filtered_by_min_score=%d final_patents=%d", - filtered_by_ipc, - filtered_by_relevance_gate, - filtered_by_min_score, - len(scored), + "Keyword patent search: IPC path yielded no scored patents — " + "trying keyword text search (policy=_TEXT_SEARCH_AFTER_EMPTY_IPC)" ) - - scored.sort( - key=lambda item: ( - item.match_score, - item.patent.publication_date or "", - item.patent.patent_id, - ), - reverse=True, - ) - scored = scored[:_MAX_PATENTS] - - patents = [item.patent for item in scored] - await enrich_patents_classifications(patents, ipc_search) - - return PatentsByKeywordsResponse( - patent_count=len(scored), - patents=scored, + 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, ) diff --git a/service/src/main/inse/patents/keywords/model.py b/service/src/main/inse/patents/keywords/model.py index 56423282..1a1c4b44 100644 --- a/service/src/main/inse/patents/keywords/model.py +++ b/service/src/main/inse/patents/keywords/model.py @@ -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.", + ) diff --git a/service/src/main/inse/patents/keywords/reverse_lookup.py b/service/src/main/inse/patents/keywords/reverse_lookup.py index 60806eba..5f29b445 100644 --- a/service/src/main/inse/patents/keywords/reverse_lookup.py +++ b/service/src/main/inse/patents/keywords/reverse_lookup.py @@ -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) diff --git a/service/src/main/inse/patents/keywords/search_queries.py b/service/src/main/inse/patents/keywords/search_queries.py index 86a3ce9b..02139697 100644 --- a/service/src/main/inse/patents/keywords/search_queries.py +++ b/service/src/main/inse/patents/keywords/search_queries.py @@ -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, + } diff --git a/service/src/main/inse/patents/keywords/test_logic.py b/service/src/main/inse/patents/keywords/test_logic.py index 0a6af63c..b6f14912 100644 --- a/service/src/main/inse/patents/keywords/test_logic.py +++ b/service/src/main/inse/patents/keywords/test_logic.py @@ -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( diff --git a/webapp/src/app/api/model/keywordEvidence.ts b/webapp/src/app/api/model/keywordEvidence.ts new file mode 100644 index 00000000..5df71c34 --- /dev/null +++ b/webapp/src/app/api/model/keywordEvidence.ts @@ -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; + matched_words?: Array; + text_match_kind?: string; +} diff --git a/webapp/src/app/api/model/keywordPatentMatch.ts b/webapp/src/app/api/model/keywordPatentMatch.ts index 3884b93d..2df6db94 100644 --- a/webapp/src/app/api/model/keywordPatentMatch.ts +++ b/webapp/src/app/api/model/keywordPatentMatch.ts @@ -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; - matched_ipc_symbols?: Array; + 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; + matched_ipc_symbols?: Array; + /** + * 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; } diff --git a/webapp/src/app/api/model/patentsByKeywordsResponse.ts b/webapp/src/app/api/model/patentsByKeywordsResponse.ts index 1e31acb5..d894eb31 100644 --- a/webapp/src/app/api/model/patentsByKeywordsResponse.ts +++ b/webapp/src/app/api/model/patentsByKeywordsResponse.ts @@ -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; + mapping_status: KeywordPatentMappingStatus; } - diff --git a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html index 0481a3b9..952181b2 100644 --- a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html +++ b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html @@ -1,7 +1,11 @@ @if (loading()) {
-

Lade passende Patente...

+
} @else if (error()) {
@@ -11,7 +15,7 @@ } @else if (matches().length === 0) {
-

Keine passenden Patente gefunden.

+

{{ emptyMessage() }}

} @else {
@@ -23,9 +27,7 @@ Patent - Score Quelle - Jahr @@ -36,7 +38,6 @@ {{ item.patent.title ?? item.patent.patent_id }} - {{ formatScore(item.match_score) }}

{{ match.patent.title ?? match.patent.patent_id }}

-
- Match-Score - {{ formatScore(match.match_score) }} -
-
- Gematchte Keywords - {{ - formatMatchList(match.matched_keywords) - }} -
-
- Gematchte IPC/CPC - {{ - formatMatchList(match.matched_ipc_symbols) - }} -
Quelle diff --git a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.scss b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.scss index ae2481f3..18059791 100644 --- a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.scss +++ b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.scss @@ -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; diff --git a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.ts b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.ts index b87a04dd..41a190ea 100644 --- a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.ts +++ b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.ts @@ -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([]); + readonly mappingStatus = input(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 [ diff --git a/webapp/src/app/modules/keywords-search/patent-search.utils.ts b/webapp/src/app/modules/keywords-search/patent-search.utils.ts index 1111e2f8..fbf62404 100644 --- a/webapp/src/app/modules/keywords-search/patent-search.utils.ts +++ b/webapp/src/app/modules/keywords-search/patent-search.utils.ts @@ -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); diff --git a/webapp/src/app/modules/keywords-search/search-results/patents-results/patents-results.component.html b/webapp/src/app/modules/keywords-search/search-results/patents-results/patents-results.component.html index 87d668f6..3e0cb344 100644 --- a/webapp/src/app/modules/keywords-search/search-results/patents-results/patents-results.component.html +++ b/webapp/src/app/modules/keywords-search/search-results/patents-results/patents-results.component.html @@ -22,6 +22,7 @@
([]); + readonly mappingStatus = signal(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 {