From 23b1be3b7bbf5b8e931b7f9c6394e6be4e4e78f5 Mon Sep 17 00:00:00 2001 From: taguesokoudjou Date: Thu, 9 Jul 2026 15:01:43 +0200 Subject: [PATCH] Add patents-by-keywords mapping pipeline and keyword patent search flow --- .../build_patents_openalex_keywords.py | 143 ++++ service/scripts/diagnose_keyword_patents.py | 91 +++ .../diagnose_patents_openalex_keywords.py | 89 ++ .../main/inse/patents/keywords/__init__.py | 0 .../src/main/inse/patents/keywords/logic.py | 405 ++++++++++ .../src/main/inse/patents/keywords/model.py | 46 ++ .../inse/patents/keywords/reverse_lookup.py | 760 ++++++++++++++++++ .../inse/patents/keywords/search_queries.py | 166 ++++ .../src/main/inse/patents/keywords/service.py | 23 + .../main/inse/patents/keywords/test_logic.py | 128 +++ .../patents_openalex_keywords/__init__.py | 0 .../patents_openalex_keywords/client.py | 171 ++++ .../patents_openalex_keywords/ipc_entries.py | 207 +++++ .../patents_openalex_keywords/mapping.py | 34 + .../patents_openalex_keywords/matching.py | 409 ++++++++++ .../patents_openalex_keywords/resolver.py | 284 +++++++ .../test_matching.py | 88 ++ .../test_resolver.py | 102 +++ webapp/src/app/api/api/patents.service.ts | 19 + .../api/model/patentsByKeywordsResponse.ts | 26 + .../keywords-patents.component.html | 114 +++ .../keywords-patents.component.scss | 145 ++++ .../keywords-patents.component.ts | 88 ++ .../keywords-search.component.html | 22 +- .../keywords-search.component.scss | 15 +- .../keywords-search.component.ts | 84 +- 26 files changed, 3643 insertions(+), 16 deletions(-) create mode 100644 service/scripts/build_patents_openalex_keywords.py create mode 100644 service/scripts/diagnose_keyword_patents.py create mode 100644 service/scripts/diagnose_patents_openalex_keywords.py create mode 100644 service/src/main/inse/patents/keywords/__init__.py create mode 100644 service/src/main/inse/patents/keywords/logic.py create mode 100644 service/src/main/inse/patents/keywords/model.py create mode 100644 service/src/main/inse/patents/keywords/reverse_lookup.py create mode 100644 service/src/main/inse/patents/keywords/search_queries.py create mode 100644 service/src/main/inse/patents/keywords/service.py create mode 100644 service/src/main/inse/patents/keywords/test_logic.py create mode 100644 service/src/main/inse/patents/patents_openalex_keywords/__init__.py create mode 100644 service/src/main/inse/patents/patents_openalex_keywords/client.py create mode 100644 service/src/main/inse/patents/patents_openalex_keywords/ipc_entries.py create mode 100644 service/src/main/inse/patents/patents_openalex_keywords/mapping.py create mode 100644 service/src/main/inse/patents/patents_openalex_keywords/matching.py create mode 100644 service/src/main/inse/patents/patents_openalex_keywords/resolver.py create mode 100644 service/src/main/inse/patents/patents_openalex_keywords/test_matching.py create mode 100644 service/src/main/inse/patents/patents_openalex_keywords/test_resolver.py create mode 100644 webapp/src/app/api/model/patentsByKeywordsResponse.ts create mode 100644 webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html create mode 100644 webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.scss create mode 100644 webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.ts diff --git a/service/scripts/build_patents_openalex_keywords.py b/service/scripts/build_patents_openalex_keywords.py new file mode 100644 index 00000000..606660a3 --- /dev/null +++ b/service/scripts/build_patents_openalex_keywords.py @@ -0,0 +1,143 @@ +#!/usr/bin/env python3 +""" +build_patents_openalex_keywords.py — Build IPC/CPC → OpenAlex topic/keyword matches. + +Fetches IPC/CPC metadata from the `ipc` index, matches labels against OpenAlex topics +(from topic_hierarchy_cache.json) and keywords (from openalex-topics) using +SentenceTransformer embeddings, then writes results to the patents_openalex_keywords +Elasticsearch index and a local JSON backup. + +Usage: + python scripts/build_patents_openalex_keywords.py + python scripts/build_patents_openalex_keywords.py --top-k 3 --min-score 0.55 + python scripts/build_patents_openalex_keywords.py --levels section class subclass + python scripts/build_patents_openalex_keywords.py --skip-keywords + +Requires src/main/inse/.env with PATENT_ELASTICSEARCH credentials (INSE) and, unless +--skip-keywords is set, NES Elasticsearch credentials for openalex-topics. +""" +from __future__ import annotations + +import argparse +import asyncio +import json +import logging +import sys +from pathlib import Path + +current_dir = Path(__file__).resolve().parent +sys.path.insert(0, str(current_dir.parent / "src" / "main")) + +from inse.patents.patents_openalex_keywords.client import PatentsOpenAlexKeywordsClient +from inse.patents.patents_openalex_keywords.ipc_entries import ( + DEFAULT_BUILD_LEVELS, + fetch_unique_ipc_entries, +) +from inse.patents.patents_openalex_keywords.matching import ( + TopicVectorsMatcher, + build_documents_from_topicvectors, + documents_to_json_mapping, +) + +logger = logging.getLogger(__name__) + + +async def run(args: argparse.Namespace) -> None: + levels = tuple(args.levels) + + ipc_entries = await fetch_unique_ipc_entries(levels=levels) + counts = {level: len(ipc_entries.get(level, {})) for level in levels} + logger.info("Fetched unique IPC/CPC symbols: %s", counts) + + if args.skip_keywords: + logger.info("--skip-keywords is ignored in topicvectors mode") + if args.topic_cache: + logger.info("--topic-cache is ignored in topicvectors mode") + if args.batch_size != 64: + logger.info("--batch-size is ignored in topicvectors mode") + + matcher = TopicVectorsMatcher(min_score=args.min_score) + logger.info("Matching IPC/CPC labels against topicvectors index...") + documents = await build_documents_from_topicvectors( + ipc_entries, matcher, levels=levels, top_k=args.top_k + ) + logger.info("Built %d IPC/CPC mapping documents", len(documents)) + + if args.output: + output_path = Path(args.output) + output_path.parent.mkdir(parents=True, exist_ok=True) + mapping = documents_to_json_mapping(documents) + output_path.write_text( + json.dumps(mapping, indent=2, ensure_ascii=True), + encoding="utf-8", + ) + logger.info("Wrote local JSON backup to %s", output_path) + + if not args.dry_run: + client = PatentsOpenAlexKeywordsClient(timeout=60.0) + await client.ensure_index() + await client.bulk_index(documents) + logger.info("Indexed %d documents into patents_openalex_keywords", len(documents)) + else: + logger.info("Dry run — skipped Elasticsearch indexing") + + +def main() -> None: + parser = argparse.ArgumentParser( + description="Build IPC/CPC → OpenAlex topic/keyword matches with SentenceTransformer.", + ) + parser.add_argument( + "--output", + default=str( + current_dir.parent / "src" / "data" / "patents_openalex_keywords_mapping.json" + ), + help="Local JSON backup path", + ) + parser.add_argument( + "--topic-cache", + default=None, + help="Deprecated in topicvectors mode (kept for CLI compatibility)", + ) + parser.add_argument( + "--levels", + nargs="+", + default=list(DEFAULT_BUILD_LEVELS), + choices=list(DEFAULT_BUILD_LEVELS), + help="IPC/CPC hierarchy levels to map", + ) + parser.add_argument( + "--top-k", + type=int, + default=3, + help="Number of top topic/keyword matches per IPC/CPC code", + ) + parser.add_argument( + "--min-score", + type=float, + default=0.5, + help="Minimum cosine similarity for a match", + ) + parser.add_argument( + "--batch-size", + type=int, + default=64, + help="Deprecated in topicvectors mode (kept for CLI compatibility)", + ) + parser.add_argument( + "--skip-keywords", + action="store_true", + help="Deprecated in topicvectors mode (kept for CLI compatibility)", + ) + parser.add_argument( + "--dry-run", + action="store_true", + help="Build matches locally without indexing into Elasticsearch", + ) + args = parser.parse_args() + + logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") + asyncio.run(run(args)) + + +if __name__ == "__main__": + main() diff --git a/service/scripts/diagnose_keyword_patents.py b/service/scripts/diagnose_keyword_patents.py new file mode 100644 index 00000000..7beeeb44 --- /dev/null +++ b/service/scripts/diagnose_keyword_patents.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python3 +"""Diagnose keyword → patent search for a given keyword.""" +from __future__ import annotations + +import argparse +import asyncio +import sys +from pathlib import Path + +current_dir = Path(__file__).resolve().parent +sys.path.insert(0, str(current_dir.parent / "src" / "main")) + +from dotenv import load_dotenv + +load_dotenv(current_dir.parent / "src" / "main" / "inse" / ".env") + +from inse.patents.authors.ipc_openalex_mapping import _load_topic_cache +from inse.patents.keywords.logic import _patent_search_terms, get_patents_by_keywords +from inse.patents.keywords.model import KeywordPatentSearchItem, PatentsByKeywordsRequest +from inse.patents.keywords.reverse_lookup import KeywordIpcReverseLookup + + +def _find_topic(keyword: str) -> tuple[str, dict]: + cache = _load_topic_cache() + keyword_lower = keyword.casefold() + for name, info in cache.items(): + if keyword_lower in name.casefold(): + return name, info + for name, info in cache.items(): + if info.get("subfield", "").casefold() == keyword_lower: + return name, info + return keyword, {} + + +async def diagnose(keyword: str, topic_name: str | None, topic_id: str | None) -> None: + if topic_name and topic_id: + display_name = topic_name + tid = topic_id + info = _load_topic_cache().get(topic_name, {}) + else: + display_name, info = _find_topic(keyword) + tid = info.get("topic_id") + + item = KeywordPatentSearchItem( + keyword=keyword, + topic_id=tid, + topic_display_name=display_name, + subfield_name=info.get("subfield"), + field_name=info.get("field"), + relevance_score=1.0, + ) + print(f"Keyword: {keyword}") + print(f"Topic: {display_name} ({tid})") + print(f"Subfield: {info.get('subfield')} | Field: {info.get('field')}") + + lookup = KeywordIpcReverseLookup() + ipc = await lookup.lookup_ipc_codes([item]) + print(f"\nIPC matches ({len(ipc)}):") + for match in ipc[:20]: + print( + f" {match.ipc_symbol:14} score={match.match_score:.3f} " + f"type={match.match_type}" + ) + + terms = _patent_search_terms(ipc) + print(f"\nPatent search terms ({len(terms)}): {terms}") + + response = await get_patents_by_keywords(PatentsByKeywordsRequest(keywords=[item])) + print(f"\nPatents returned: {response.patent_count}") + for entry in response.patents[:10]: + patent = entry.patent + title = (patent.title or "")[:60] + print( + f" score={entry.match_score:.3f} {patent.patent_id} " + f"ipc={entry.matched_ipc_symbols} | {title}" + ) + if patent.ipc: + print(f" raw ipc: {patent.ipc[:2]}") + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("keyword", default="Medizin", nargs="?") + parser.add_argument("--topic-name", default=None) + parser.add_argument("--topic-id", default=None) + args = parser.parse_args() + asyncio.run(diagnose(args.keyword, args.topic_name, args.topic_id)) + + +if __name__ == "__main__": + main() diff --git a/service/scripts/diagnose_patents_openalex_keywords.py b/service/scripts/diagnose_patents_openalex_keywords.py new file mode 100644 index 00000000..d226739f --- /dev/null +++ b/service/scripts/diagnose_patents_openalex_keywords.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python3 +"""Print IPC/CPC → OpenAlex topic/keyword matches from patents_openalex_keywords.""" +from __future__ import annotations + +import argparse +import asyncio +import sys +from pathlib import Path + +current_dir = Path(__file__).resolve().parent +sys.path.insert(0, str(current_dir.parent / "src" / "main")) + +from inse.patents.patents_openalex_keywords.client import PatentsOpenAlexKeywordsClient +from inse.patents.patents_openalex_keywords.ipc_entries import infer_subclass, normalize_symbol + +DEFAULT_SYMBOLS = ("A", "A61", "A61B", "G01N", "C12N", "H04L") + + +def _print_match_block(title: str, matches: list[dict]) -> None: + print(f" {title}:") + if not matches: + print(" (none)") + return + for item in matches: + if "keyword" in item: + label = item.get("keyword") + topic = item.get("topic_display_name") or item.get("topic_id") + print( + f" #{item.get('rank')} {label} " + f"[topic={topic}, score={item.get('match_score')}]" + ) + else: + label = item.get("topic_display_name") or item.get("topic_id") + print(f" #{item.get('rank')} {label} (score={item.get('match_score')})") + + +async def diagnose_symbol(client: PatentsOpenAlexKeywordsClient, symbol: str) -> None: + normalized = normalize_symbol(symbol) + print(f"\n{'=' * 70}") + print(f"IPC/CPC symbol: {normalized}") + + doc = await client.lookup_symbol(normalized) + if doc: + print(f"Matched level: {doc.get('ipc_level')}") + print(f"IPC label: {doc.get('ipc_label')}") + _print_match_block("Topic matches", doc.get("topic_matches") or []) + _print_match_block("Keyword matches", doc.get("keyword_matches") or []) + return + + subclass = infer_subclass(normalized) + for level, candidate in ( + ("subgroup", normalized), + ("group", normalized), + ("subclass", subclass), + ("class", normalized[:3] if len(normalized) >= 3 else None), + ("section", normalized[:1] if normalized else None), + ): + if not candidate: + continue + doc = await client.lookup(level, candidate) + if doc: + print(f"Matched level: {doc.get('ipc_level')} (via fallback lookup)") + print(f"IPC label: {doc.get('ipc_label')}") + _print_match_block("Topic matches", doc.get("topic_matches") or []) + _print_match_block("Keyword matches", doc.get("keyword_matches") or []) + return + + print(" No mapping found in patents_openalex_keywords.") + + +async def main() -> None: + parser = argparse.ArgumentParser( + description="Diagnose IPC/CPC matches in patents_openalex_keywords.", + ) + parser.add_argument( + "symbols", + nargs="*", + default=list(DEFAULT_SYMBOLS), + help="IPC/CPC symbols to inspect", + ) + args = parser.parse_args() + + client = PatentsOpenAlexKeywordsClient() + for symbol in args.symbols: + await diagnose_symbol(client, symbol) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/service/src/main/inse/patents/keywords/__init__.py b/service/src/main/inse/patents/keywords/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/service/src/main/inse/patents/keywords/logic.py b/service/src/main/inse/patents/keywords/logic.py new file mode 100644 index 00000000..6daeabe4 --- /dev/null +++ b/service/src/main/inse/patents/keywords/logic.py @@ -0,0 +1,405 @@ +"""Find patents for extracted OpenAlex keywords via patents_openalex_keywords index.""" +from __future__ import annotations + +import asyncio +import logging + +import httpx + +from inse.patents.common import model +from inse.patents.common.elastic_search_client import ( + BasePatentSearchClient, + MissingApiKeyError, +) +from inse.patents.common.parsing import ( + deduplicate_patents, + enrich_patents_classifications, + parse_epo_hits, + parse_uspto_hits, +) +from inse.patents.ipc_lookup import extract_ipc_symbol +from inse.patents.ipc_search_client import IpcSearchClient +from inse.patents.keywords.model import ( + KeywordPatentMatch, + KeywordPatentSearchItem, + PatentsByKeywordsRequest, + PatentsByKeywordsResponse, +) +from inse.patents.keywords.reverse_lookup import IpcCodeMatch, KeywordIpcReverseLookup +from inse.patents.keywords.search_queries import ( + IpcPatentSearchQueries, + _search_terms_for_symbol, +) +from inse.patents.patents_openalex_keywords.ipc_entries import normalize_symbol + +logger = logging.getLogger(__name__) + +_MAX_PATENTS = 100 +_MAX_IPC_CODES = 40 +_MAX_PATENT_SEARCH_TERMS = 12 +_MIN_IPC_MATCH_SCORE = 0.45 +_MIN_PATENT_MATCH_SCORE = 0.35 + + +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] = {} + for match in ipc_matches: + section = _ipc_section(match.ipc_symbol) + if not section: + 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 _filter_ipc_matches_for_search(ipc_matches: list[IpcCodeMatch]) -> list[IpcCodeMatch]: + if not ipc_matches: + return [] + + 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 or match.match_type == "heuristic" + ] + if not strong: + strong = ranked[:8] + + 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: + continue + if match.match_type == "heuristic": + filtered.append(match) + seen.add(key) + continue + if match.match_score >= 0.8: + filtered.append(match) + seen.add(key) + continue + if _ipc_section(match.ipc_symbol) in dominant_sections: + filtered.append(match) + seen.add(key) + + return filtered or strong[:12] + + +def _active_heuristic_prefixes(ipc_matches: list[IpcCodeMatch]) -> set[str]: + prefixes: set[str] = set() + for match in ipc_matches: + if match.match_type != "heuristic": + continue + symbol = normalize_symbol(match.ipc_symbol) + if not symbol: + continue + for prefix in ( + "A61", + "B01", + "C01", + "C07", + "C08", + "C09", + "C10", + "C12", + "G01N", + "G06", + "B60", + "F02", + ): + if symbol.startswith(prefix): + prefixes.add(prefix) + return prefixes + + +def _symbol_matches_heuristic_prefixes(symbol: str, prefixes: set[str]) -> bool: + normalized = normalize_symbol(symbol) + return any(normalized.startswith(prefix) for prefix in prefixes) + + +def _ipc_search_domain(symbol: str) -> str: + normalized = normalize_symbol(symbol) + if normalized.startswith("A61"): + return "medicine" + if ( + normalized.startswith("C") + or normalized.startswith("B01") + or normalized.startswith("G01N") + ): + return "chemistry" + if normalized.startswith("B60") or normalized.startswith("F02"): + return "automotive" + if normalized.startswith("G06"): + return "cs_ai" + return "other" + + +def _term_from_ipc_match(match: IpcCodeMatch) -> str | None: + from inse.patents.patents_openalex_keywords.ipc_entries import infer_subclass + + return infer_subclass(normalize_symbol(match.ipc_symbol)) + + +def _interleave_ipc_matches( + matches: list[IpcCodeMatch], + *, + limit: int, +) -> list[IpcCodeMatch]: + from collections import defaultdict + + by_domain: dict[str, list[IpcCodeMatch]] = defaultdict(list) + for match in matches: + by_domain[_ipc_search_domain(match.ipc_symbol)].append(match) + + if len(by_domain) <= 1: + return matches[:limit] + + ordered: list[IpcCodeMatch] = [] + seen: set[tuple[str, str]] = set() + queues = list(by_domain.values()) + while len(ordered) < limit and queues: + progressed = False + for queue in list(queues): + if len(ordered) >= limit: + break + while queue: + match = queue.pop(0) + key = (match.ipc_level, match.ipc_symbol) + if key in seen: + continue + seen.add(key) + ordered.append(match) + progressed = True + break + queues = [queue for queue in queues if queue] + if not progressed: + break + return ordered + + +def _balanced_patent_matches( + scored: list[KeywordPatentMatch], + limit: int, +) -> list[KeywordPatentMatch]: + from collections import defaultdict + + by_domain: dict[str, list[KeywordPatentMatch]] = defaultdict(list) + for item in scored: + domain = ( + _ipc_search_domain(item.matched_ipc_symbols[0]) + if item.matched_ipc_symbols + else "other" + ) + by_domain[domain].append(item) + + if len(by_domain) <= 1: + return scored[:limit] + + ordered: list[KeywordPatentMatch] = [] + seen_ids: set[str] = set() + queues = list(by_domain.values()) + while len(ordered) < limit and queues: + progressed = False + for queue in list(queues): + if len(ordered) >= limit: + break + while queue: + item = queue.pop(0) + if item.patent.patent_id in seen_ids: + continue + seen_ids.add(item.patent.patent_id) + ordered.append(item) + progressed = True + break + queues = [queue for queue in queues if queue] + if not progressed: + break + return ordered + + +def _patent_search_terms(ipc_matches: list[IpcCodeMatch]) -> list[str]: + filtered = _filter_ipc_matches_for_search(ipc_matches) + active_prefixes = _active_heuristic_prefixes(ipc_matches) + if active_prefixes: + filtered = [ + match + for match in filtered + if _symbol_matches_heuristic_prefixes(match.ipc_symbol, active_prefixes) + ] + + filtered = _interleave_ipc_matches(filtered, limit=_MAX_PATENT_SEARCH_TERMS) + terms: list[str] = [] + seen: set[str] = set() + for match in filtered: + subclass = _term_from_ipc_match(match) + if not subclass or subclass in seen: + continue + seen.add(subclass) + terms.append(subclass) + if len(terms) >= _MAX_PATENT_SEARCH_TERMS: + break + return terms + + +def _ipc_terms_overlap(patent_code: str, mapped_symbol: str) -> bool: + patent_terms = set( + _search_terms_for_symbol(extract_ipc_symbol(patent_code) or patent_code) + ) + mapped_terms = set(_search_terms_for_symbol(mapped_symbol)) + return bool(patent_terms & mapped_terms) + + +def _patent_code_matches_symbol(patent_code: str, mapped_symbol: str) -> bool: + if _ipc_terms_overlap(patent_code, mapped_symbol): + return True + normalized_patent = normalize_symbol(extract_ipc_symbol(patent_code)) + normalized_mapped = normalize_symbol(mapped_symbol) + if not normalized_patent or not normalized_mapped: + return False + return ( + normalized_patent.startswith(normalized_mapped) + or normalized_mapped.startswith(normalized_patent) + ) + + +def _score_patent( + patent: model.PatentEntry, + ipc_matches: list[IpcCodeMatch], +) -> tuple[float, list[str], list[str]] | None: + best_score = 0.0 + matched_keywords: set[str] = set() + matched_symbols: set[str] = set() + + patent_codes = [ + normalize_symbol(extract_ipc_symbol(code)) + for code in (*patent.ipc, *patent.cpc) + if extract_ipc_symbol(code) + ] + + for ipc_match in ipc_matches: + for patent_code in patent_codes: + if _patent_code_matches_symbol(patent_code, ipc_match.ipc_symbol): + if ipc_match.match_score > best_score: + best_score = ipc_match.match_score + matched_keywords.add(ipc_match.source_keyword) + matched_symbols.add(ipc_match.ipc_symbol) + + if best_score <= 0: + return None + + return ( + best_score, + sorted(matched_keywords), + sorted(matched_symbols), + ) + + +async def get_patents_by_keywords( + request: PatentsByKeywordsRequest, + *, + reverse_lookup: KeywordIpcReverseLookup | None = None, + search_client: BasePatentSearchClient | None = None, + ipc_client: IpcSearchClient | None = None, +) -> PatentsByKeywordsResponse: + lookup = reverse_lookup or KeywordIpcReverseLookup() + client = search_client or BasePatentSearchClient() + ipc_search = ipc_client or IpcSearchClient() + queries = IpcPatentSearchQueries() + + ipc_matches = await lookup.lookup_ipc_codes( + request.keywords, + max_codes=_MAX_IPC_CODES, + ) + ipc_matches = _filter_ipc_matches_for_search(ipc_matches) + if not ipc_matches: + logger.info( + "Keyword patent search: no IPC codes for keywords %s", + [item.keyword for item in request.keywords], + ) + return PatentsByKeywordsResponse(patent_count=0, patents=[]) + + symbols = _patent_search_terms(ipc_matches) + 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_terms(symbols, size=_MAX_PATENTS)), + client.search_uspto( + queries.uspto_query_by_ipc_terms(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) + ) + + scored: list[KeywordPatentMatch] = [] + for patent in raw_patents: + result = _score_patent(patent, ipc_matches) + if result is None: + continue + score, matched_keywords, matched_symbols = result + if score < _MIN_PATENT_MATCH_SCORE: + continue + scored.append( + KeywordPatentMatch( + patent=patent, + match_score=score, + matched_keywords=matched_keywords, + matched_ipc_symbols=matched_symbols, + ) + ) + + scored.sort( + key=lambda item: ( + item.match_score, + item.patent.publication_date or "", + item.patent.patent_id, + ), + reverse=True, + ) + scored = _balanced_patent_matches(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, + ) + + +def keyword_items_from_entries( + entries: list[dict], +) -> list[KeywordPatentSearchItem]: + """Helper for tests – build search items from serialized keyword entries.""" + items: list[KeywordPatentSearchItem] = [] + for entry in entries: + llm = entry.get("llm_keyword") or {} + topic_mapping = entry.get("topic_mapping") or {} + topic = topic_mapping.get("topic") or {} + items.append( + KeywordPatentSearchItem( + keyword=str(llm.get("keyword") or "").strip(), + topic_id=topic.get("id"), + topic_display_name=topic.get("display_name"), + subfield_name=(topic.get("subfield") or {}).get("display_name"), + field_name=(topic.get("field") or {}).get("display_name"), + relevance_score=float(llm.get("relevance_score") or 1.0), + ) + ) + return [item for item in items if item.keyword] diff --git a/service/src/main/inse/patents/keywords/model.py b/service/src/main/inse/patents/keywords/model.py new file mode 100644 index 00000000..0c435b1c --- /dev/null +++ b/service/src/main/inse/patents/keywords/model.py @@ -0,0 +1,46 @@ +from pydantic import BaseModel, Field + +from inse.patents.common.model import PatentEntry + + +class KeywordPatentSearchItem(BaseModel): + keyword: str = Field(description="Extracted keyword text.") + topic_id: str | None = Field( + default=None, + description="OpenAlex topic id from keyword enrichment, if available.", + ) + topic_display_name: str | None = Field( + default=None, + description="OpenAlex topic display name from enrichment, if available.", + ) + subfield_name: str | None = Field( + default=None, + description="OpenAlex subfield name from enrichment, if available.", + ) + field_name: str | None = Field( + default=None, + description="OpenAlex field name from enrichment, if available.", + ) + relevance_score: float = Field( + default=1.0, + description="LLM relevance score for the keyword.", + ) + + +class PatentsByKeywordsRequest(BaseModel): + keywords: list[KeywordPatentSearchItem] = Field( + min_length=1, + description="Keywords to match against patents_openalex_keywords.", + ) + + +class KeywordPatentMatch(BaseModel): + patent: PatentEntry + match_score: float = Field(description="Combined match quality score.") + matched_keywords: list[str] = Field(default_factory=list) + matched_ipc_symbols: list[str] = Field(default_factory=list) + + +class PatentsByKeywordsResponse(BaseModel): + patent_count: int + patents: list[KeywordPatentMatch] diff --git a/service/src/main/inse/patents/keywords/reverse_lookup.py b/service/src/main/inse/patents/keywords/reverse_lookup.py new file mode 100644 index 00000000..13b9e097 --- /dev/null +++ b/service/src/main/inse/patents/keywords/reverse_lookup.py @@ -0,0 +1,760 @@ +"""Reverse lookup: OpenAlex keywords/topics → IPC/CPC codes via patents_openalex_keywords.""" +from __future__ import annotations + +import logging +from dataclasses import dataclass +from functools import lru_cache +from typing import Any + +import httpx + +from inse.patents.authors.ipc_openalex_mapping import ( + _load_topic_cache, + load_ipc_openalex_mapping, + normalize_openalex_id, +) +from inse.patents.common.elastic_search_client import MissingApiKeyError +from inse.patents.keywords.model import KeywordPatentSearchItem +from inse.patents.patents_openalex_keywords.client import PatentsOpenAlexKeywordsClient +from inse.patents.patents_openalex_keywords.ipc_entries import normalize_symbol +from inse.patents.patents_openalex_keywords.mapping import PATENTS_OPENALEX_KEYWORDS_INDEX +from inse.patents.patents_openalex_keywords.resolver import load_patents_openalex_keywords_json + +logger = logging.getLogger(__name__) + +_CS_AI_IPC_SUBCLASSES = ("G06N", "G06F", "G06T", "G06V", "G06K", "G06Q") +_AUTOMOTIVE_IPC_SUBCLASSES = ( + "B60L", + "B60K", + "B60W", + "B60R", + "B60H", + "B60Q", + "B60M", + "F02M", + "F02D", +) +_MEDICINE_IPC_SUBCLASSES = ("A61B", "A61K", "A61M", "A61P", "A61N", "A61F") +_CHEMISTRY_IPC_SUBCLASSES_GENERAL = ("C07C", "C01B", "C08L", "G01N") +_CHEMISTRY_IPC_SUBCLASSES_ORGANIC = ("C07C", "C07D") +_CHEMISTRY_IPC_SUBCLASSES_INORGANIC = ("C01B", "C01G") +_CHEMISTRY_IPC_SUBCLASSES_POLYMER = ("C08L", "C08G") +_CHEMISTRY_IPC_SUBCLASSES_BIOCHEM = ("C12N", "C12Q") +_CHEMISTRY_IPC_SUBCLASSES_ANALYTICAL = ("G01N",) +_CHEMISTRY_IPC_SUBCLASSES_PROCESS = ("B01J", "B01D") +_CHEMISTRY_RELATED_SUBFIELDS = frozenset( + { + "organic chemistry", + "inorganic chemistry", + "physical and theoretical chemistry", + "analytical chemistry", + "materials chemistry", + "environmental chemistry", + "biochemistry", + "process chemistry and technology", + "spectroscopy", + "clinical biochemistry", + "geochemistry and petrology", + "pharmaceutical science", + } +) +_CHEMISTRY_RELATED_FIELDS = frozenset( + { + "chemistry", + "chemical engineering", + } +) +_MEDICINE_RELATED_SUBFIELDS = frozenset( + { + "medicine", + "public health", + "health professions", + "pharmacology", + "surgery", + "oncology", + "radiology, nuclear medicine and imaging", + "cardiology and cardiovascular medicine", + "epidemiology", + "immunology", + } +) +_MEDICINE_RELATED_FIELDS = frozenset( + { + "medicine", + "health professions", + "nursing", + "pharmacology, toxicology and pharmaceutics", + "biochemistry, genetics and molecular biology", + } +) +_AI_RELATED_SUBFIELDS = frozenset( + { + "artificial intelligence", + "computer vision and pattern recognition", + "signal processing", + "information systems and management", + "human-computer interaction", + "software", + } +) + +_LEVEL_WEIGHTS = { + "subgroup": 1.0, + "group": 0.92, + "subclass": 0.85, + "class": 0.75, + "section": 0.6, +} + + +@dataclass(frozen=True) +class IpcCodeMatch: + ipc_level: str + ipc_symbol: str + match_score: float + source_keyword: str + match_type: str + + +def _keyword_variants(keyword: str) -> list[str]: + normalized = keyword.strip().casefold() + if not normalized: + return [] + return list(dict.fromkeys([normalized, keyword.strip()])) + + +def _topic_id_variants(topic_id: str | None) -> list[str]: + if not topic_id or not str(topic_id).strip(): + return [] + raw = str(topic_id).strip() + short = normalize_openalex_id(raw) + variants = [raw] + if short: + variants.append(short) + variants.append(f"https://openalex.org/{short}") + return list(dict.fromkeys(variants)) + + +def _weighted_score( + ipc_level: str, + base_score: float, + relevance_score: float, +) -> float: + level_weight = _LEVEL_WEIGHTS.get(ipc_level, 0.7) + relevance = max(relevance_score, 0.1) + return round(base_score * level_weight * relevance, 4) + + +@lru_cache(maxsize=1) +def _build_json_inverted_index() -> tuple[ + dict[str, list[tuple[str, str, float, str, str]]], + dict[str, list[tuple[str, str, float, str, str]]], +]: + """keyword/topic_id -> list of (level, symbol, score, source_keyword, match_type).""" + by_keyword: dict[str, list[tuple[str, str, float, str, str]]] = {} + by_topic: dict[str, list[tuple[str, str, float, str, str]]] = {} + + table = load_patents_openalex_keywords_json() + for level, entries in table.items(): + for symbol, doc in entries.items(): + for match in doc.get("keyword_matches") or []: + keyword = str(match.get("keyword") or "").strip() + if not keyword: + continue + key = keyword.casefold() + entry = ( + level, + symbol, + float(match.get("match_score") or 0.0), + keyword, + "keyword", + ) + by_keyword.setdefault(key, []).append(entry) + topic_id = match.get("topic_id") + if topic_id: + for variant in _topic_id_variants(str(topic_id)): + by_topic.setdefault(variant, []).append(entry) + + for match in doc.get("topic_matches") or []: + topic_id = match.get("topic_id") + if not topic_id: + continue + entry = ( + level, + symbol, + float(match.get("match_score") or 0.0), + str(match.get("topic_display_name") or topic_id), + "topic", + ) + for variant in _topic_id_variants(str(topic_id)): + by_topic.setdefault(variant, []).append(entry) + + return by_keyword, by_topic + + +def clear_reverse_lookup_caches() -> None: + _build_json_inverted_index.cache_clear() + _topic_id_to_hierarchy.cache_clear() + _legacy_indices.cache_clear() + + +def _merge_ipc_match( + matches: dict[tuple[str, str], IpcCodeMatch], + level: str, + symbol: str, + score: float, + source_keyword: str, + match_type: str, +) -> None: + key = (level, normalize_symbol(symbol)) + existing = matches.get(key) + if existing is None or score > existing.match_score: + matches[key] = IpcCodeMatch( + ipc_level=level, + ipc_symbol=normalize_symbol(symbol), + match_score=score, + source_keyword=source_keyword, + match_type=match_type, + ) + + +def _matches_from_doc( + doc: dict[str, Any], + item: KeywordPatentSearchItem, +) -> list[IpcCodeMatch]: + ipc_level = str(doc.get("ipc_level") or "") + ipc_symbol = normalize_symbol(str(doc.get("ipc_symbol") or "")) + if not ipc_level or not ipc_symbol: + return [] + + keyword_variants = set(_keyword_variants(item.keyword)) + topic_variants = set(_topic_id_variants(item.topic_id)) + topic_name = (item.topic_display_name or "").strip().casefold() + found: list[IpcCodeMatch] = [] + + for match in doc.get("keyword_matches") or []: + match_keyword = str(match.get("keyword") or "").strip() + if match_keyword.casefold() not in keyword_variants: + match_topic = match.get("topic_id") + if not match_topic or str(match_topic) not in topic_variants: + continue + score = _weighted_score( + ipc_level, + float(match.get("match_score") or 0.0), + item.relevance_score, + ) + found.append( + IpcCodeMatch( + ipc_level=ipc_level, + ipc_symbol=ipc_symbol, + match_score=score, + source_keyword=item.keyword, + match_type="keyword", + ) + ) + break + + for match in doc.get("topic_matches") or []: + match_topic = match.get("topic_id") + match_name = str(match.get("topic_display_name") or "").strip().casefold() + topic_hit = match_topic and str(match_topic) in topic_variants + name_hit = topic_name and match_name == topic_name + if not topic_hit and not name_hit: + continue + score = _weighted_score( + ipc_level, + float(match.get("match_score") or 0.0), + item.relevance_score, + ) + found.append( + IpcCodeMatch( + ipc_level=ipc_level, + ipc_symbol=ipc_symbol, + match_score=score, + source_keyword=item.keyword, + match_type="topic", + ) + ) + break + + return found + + +def _json_lookup(items: list[KeywordPatentSearchItem]) -> list[IpcCodeMatch]: + by_keyword, by_topic = _build_json_inverted_index() + merged: dict[tuple[str, str], IpcCodeMatch] = {} + + for item in items: + 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 + ) + + for variant in _topic_id_variants(item.topic_id): + for level, symbol, base_score, source_keyword, match_type in by_topic.get( + variant, [] + ): + score = _weighted_score(level, base_score, item.relevance_score) + _merge_ipc_match( + merged, level, symbol, score, item.keyword, match_type + ) + + return sorted(merged.values(), key=lambda match: match.match_score, reverse=True) + + +@lru_cache(maxsize=1) +def _topic_id_to_hierarchy() -> dict[str, dict[str, str]]: + result: dict[str, dict[str, str]] = {} + for info in _load_topic_cache().values(): + topic_id = info.get("topic_id") + if not topic_id: + continue + for variant in _topic_id_variants(str(topic_id)): + result[variant] = info + return result + + +@lru_cache(maxsize=1) +def _legacy_indices() -> tuple[ + dict[str, list[tuple[str, str, float]]], + dict[str, list[tuple[str, str, float]]], + dict[str, list[tuple[str, str, float]]], + dict[str, list[tuple[str, str, float]]], +]: + """topic_id / topic_name / subfield / field -> (level, symbol, score).""" + by_topic_id: dict[str, list[tuple[str, str, float]]] = {} + by_topic_name: dict[str, list[tuple[str, str, float]]] = {} + by_subfield: dict[str, list[tuple[str, str, float]]] = {} + by_field: dict[str, list[tuple[str, str, float]]] = {} + cache = _load_topic_cache() + + mapping = load_ipc_openalex_mapping() + for level, entries in mapping.items(): + for symbol, mapped in entries.items(): + score = 0.55 + record = (level, normalize_symbol(symbol), score) + for variant in _topic_id_variants(mapped.topic_id): + by_topic_id.setdefault(variant, []).append(record) + if mapped.topic_display_name: + by_topic_name.setdefault( + mapped.topic_display_name.casefold(), [] + ).append(record) + + info = cache.get(mapped.topic_display_name or "") + if info: + subfield = str(info.get("subfield") or "").casefold() + field = str(info.get("field") or "").casefold() + if subfield: + by_subfield.setdefault(subfield, []).append(record) + if field: + by_field.setdefault(field, []).append(record) + + return by_topic_id, by_topic_name, by_subfield, by_field + + +def _hierarchy_for_item(item: KeywordPatentSearchItem) -> dict[str, str]: + for variant in _topic_id_variants(item.topic_id): + info = _topic_id_to_hierarchy().get(variant) + if info: + return info + if item.topic_display_name: + info = _load_topic_cache().get(item.topic_display_name) + if info: + return info + return { + "subfield": item.subfield_name or "", + "field": item.field_name or "", + } + + +def _apply_cs_ai_heuristics( + merged: dict[tuple[str, str], IpcCodeMatch], + item: KeywordPatentSearchItem, +) -> None: + hierarchy = _hierarchy_for_item(item) + subfield = str(hierarchy.get("subfield") or "").casefold() + field = str(hierarchy.get("field") or "").casefold() + if field != "computer science" and subfield not in _AI_RELATED_SUBFIELDS: + return + + for symbol in _CS_AI_IPC_SUBCLASSES: + score = _weighted_score("subclass", 0.62, item.relevance_score) + _merge_ipc_match( + merged, + "subclass", + symbol, + score, + item.keyword, + "heuristic", + ) + + +def _apply_automotive_heuristics( + merged: dict[tuple[str, str], IpcCodeMatch], + item: KeywordPatentSearchItem, +) -> None: + hierarchy = _hierarchy_for_item(item) + subfield = str(hierarchy.get("subfield") or "").casefold() + field = str(hierarchy.get("field") or "").casefold() + keyword = item.keyword.casefold() + automotive_keyword = any( + token in keyword + for token in ( + "automobil", + "fahrzeug", + "kraftfahr", + "elektromob", + "verkehr", + "mobil", + ) + ) + if ( + subfield != "automotive engineering" + and field != "engineering" + and not automotive_keyword + ): + return + + for symbol in _AUTOMOTIVE_IPC_SUBCLASSES: + score = _weighted_score("subclass", 0.6, item.relevance_score) + _merge_ipc_match( + merged, + "subclass", + symbol, + score, + item.keyword, + "heuristic", + ) + + +def _chemistry_subclasses_for_keyword(keyword: str) -> tuple[str, ...]: + normalized = keyword.casefold() + subclasses: list[str] = [] + if any(token in normalized for token in ("anorganisch", "inorganic")): + subclasses.extend(_CHEMISTRY_IPC_SUBCLASSES_INORGANIC) + elif any(token in normalized for token in ("organisch", "organic")): + subclasses.extend(_CHEMISTRY_IPC_SUBCLASSES_ORGANIC) + if any(token in normalized for token in ("polymer", "makromolek")): + subclasses.extend(_CHEMISTRY_IPC_SUBCLASSES_POLYMER) + if any(token in normalized for token in ("biochem", "enzym", "ferment")): + subclasses.extend(_CHEMISTRY_IPC_SUBCLASSES_BIOCHEM) + if any( + token in normalized + for token in ("analyt", "spektroskop", "chromatograph", "spektromet") + ): + subclasses.extend(_CHEMISTRY_IPC_SUBCLASSES_ANALYTICAL) + if any( + token in normalized + for token in ("verfahren", "reaktion", "katalys", "synthese", "technische chemie") + ): + subclasses.extend(_CHEMISTRY_IPC_SUBCLASSES_PROCESS) + subclasses.extend(_CHEMISTRY_IPC_SUBCLASSES_ORGANIC) + if any( + token in normalized + for token in ("chemie", "chemisch", "molekül", "molekul", "stoff") + ): + if not subclasses: + subclasses.extend(_CHEMISTRY_IPC_SUBCLASSES_GENERAL) + return tuple(dict.fromkeys(subclasses)) + + +def _apply_chemistry_heuristics( + merged: dict[tuple[str, str], IpcCodeMatch], + item: KeywordPatentSearchItem, +) -> None: + hierarchy = _hierarchy_for_item(item) + subfield = str(hierarchy.get("subfield") or "").casefold() + field = str(hierarchy.get("field") or "").casefold() + subclasses = _chemistry_subclasses_for_keyword(item.keyword) + if ( + subfield not in _CHEMISTRY_RELATED_SUBFIELDS + and field not in _CHEMISTRY_RELATED_FIELDS + and not subclasses + ): + return + + if not subclasses: + subclasses = _CHEMISTRY_IPC_SUBCLASSES_GENERAL + + for symbol in subclasses: + score = _weighted_score("subclass", 0.68, item.relevance_score) + _merge_ipc_match( + merged, + "subclass", + symbol, + score, + item.keyword, + "heuristic", + ) + + +def _apply_medicine_heuristics( + merged: dict[tuple[str, str], IpcCodeMatch], + item: KeywordPatentSearchItem, +) -> None: + hierarchy = _hierarchy_for_item(item) + subfield = str(hierarchy.get("subfield") or "").casefold() + field = str(hierarchy.get("field") or "").casefold() + keyword = item.keyword.casefold() + medicine_keyword = any( + token in keyword + for token in ( + "medizin", + "krankheit", + "therap", + "diagnos", + "patient", + "klinik", + "arzt", + "heilkund", + "pharma", + "immun", + "patholog", + ) + ) + if ( + subfield not in _MEDICINE_RELATED_SUBFIELDS + and field not in _MEDICINE_RELATED_FIELDS + and not medicine_keyword + ): + return + + for symbol in _MEDICINE_IPC_SUBCLASSES: + score = _weighted_score("subclass", 0.72, item.relevance_score) + _merge_ipc_match( + merged, + "subclass", + symbol, + score, + item.keyword, + "heuristic", + ) + + +def _legacy_lookup(items: list[KeywordPatentSearchItem]) -> list[IpcCodeMatch]: + by_topic_id, by_topic_name, by_subfield, by_field = _legacy_indices() + merged: dict[tuple[str, str], IpcCodeMatch] = {} + + for item in items: + for variant in _topic_id_variants(item.topic_id): + for level, symbol, base_score in by_topic_id.get(variant, []): + score = _weighted_score(level, base_score, item.relevance_score) + _merge_ipc_match( + merged, level, symbol, score, item.keyword, "topic" + ) + + topic_name = (item.topic_display_name or "").strip().casefold() + if topic_name: + for level, symbol, base_score in by_topic_name.get(topic_name, []): + score = _weighted_score(level, base_score, item.relevance_score) + _merge_ipc_match( + merged, level, symbol, score, item.keyword, "topic" + ) + + hierarchy = _hierarchy_for_item(item) + subfield = str(hierarchy.get("subfield") or "").casefold() + field = str(hierarchy.get("field") or "").casefold() + if subfield: + for level, symbol, base_score in by_subfield.get(subfield, []): + score = _weighted_score(level, base_score * 0.85, item.relevance_score) + _merge_ipc_match( + merged, level, symbol, score, item.keyword, "subfield" + ) + if field: + for level, symbol, base_score in by_field.get(field, []): + score = _weighted_score(level, base_score * 0.7, item.relevance_score) + _merge_ipc_match( + merged, level, symbol, score, item.keyword, "field" + ) + + results = sorted(merged.values(), key=lambda match: match.match_score, reverse=True) + if not results: + logger.info( + "Legacy IPC lookup found no codes for %d keyword(s); " + "build patents_openalex_keywords for better coverage.", + len(items), + ) + return results + + +def _finalize_ipc_matches( + items: list[KeywordPatentSearchItem], + matches: list[IpcCodeMatch], +) -> list[IpcCodeMatch]: + merged: dict[tuple[str, str], IpcCodeMatch] = {} + for match in matches: + _merge_ipc_match( + merged, + match.ipc_level, + match.ipc_symbol, + match.match_score, + match.source_keyword, + match.match_type, + ) + for item in items: + _apply_cs_ai_heuristics(merged, item) + _apply_automotive_heuristics(merged, item) + _apply_chemistry_heuristics(merged, item) + _apply_medicine_heuristics(merged, item) + return sorted(merged.values(), key=lambda match: match.match_score, reverse=True) + + +def _build_es_should_clauses(items: list[KeywordPatentSearchItem]) -> list[dict[str, Any]]: + should: list[dict[str, Any]] = [] + seen: set[str] = set() + + for item in items: + for keyword in _keyword_variants(item.keyword): + if keyword in seen: + continue + seen.add(keyword) + should.append( + { + "nested": { + "path": "keyword_matches", + "query": {"term": {"keyword_matches.keyword": keyword}}, + } + } + ) + + for topic_id in _topic_id_variants(item.topic_id): + if topic_id in seen: + continue + seen.add(topic_id) + should.extend( + [ + { + "nested": { + "path": "keyword_matches", + "query": {"term": {"keyword_matches.topic_id": topic_id}}, + } + }, + { + "nested": { + "path": "topic_matches", + "query": {"term": {"topic_matches.topic_id": topic_id}}, + } + }, + ] + ) + + topic_name = (item.topic_display_name or "").strip() + if topic_name and topic_name not in seen: + seen.add(topic_name) + should.append( + { + "nested": { + "path": "topic_matches", + "query": { + "term": {"topic_matches.topic_display_name": topic_name} + }, + } + } + ) + + return should + + +class KeywordIpcReverseLookup: + def __init__(self, client: PatentsOpenAlexKeywordsClient | None = None): + self.client = client or PatentsOpenAlexKeywordsClient() + self._elasticsearch_checked = False + self._elasticsearch_enabled = False + + async def _elasticsearch_enabled_for_request(self) -> bool: + if self._elasticsearch_checked: + return self._elasticsearch_enabled + self._elasticsearch_checked = True + try: + self._elasticsearch_enabled = await self.client.index_exists() + except Exception as exc: + logger.warning("patents_openalex_keywords index check failed: %s", exc) + self._elasticsearch_enabled = False + return self._elasticsearch_enabled + + async def lookup_ipc_codes( + self, + items: list[KeywordPatentSearchItem], + *, + max_codes: int = 40, + ) -> list[IpcCodeMatch]: + if not items: + return [] + + matches: list[IpcCodeMatch] = [] + if await self._elasticsearch_enabled_for_request(): + try: + matches = await self._lookup_via_elasticsearch(items) + except (MissingApiKeyError, httpx.HTTPError) as exc: + logger.warning("Keyword IPC ES lookup failed, using JSON fallback: %s", exc) + self._elasticsearch_enabled = False + + if not matches: + matches = _json_lookup(items) + + if not matches: + matches = _legacy_lookup(items) + + if not matches: + logger.info( + "No IPC codes resolved for keywords: %s", + [item.keyword for item in items], + ) + + matches = _finalize_ipc_matches(items, matches) + heuristics = [match for match in matches if match.match_type == "heuristic"] + regular = [match for match in matches if match.match_type != "heuristic"] + regular = sorted(regular, key=lambda match: match.match_score, reverse=True) + remaining = max(0, max_codes - len(heuristics)) + return heuristics + regular[:remaining] + + async def _lookup_via_elasticsearch( + self, + items: list[KeywordPatentSearchItem], + ) -> list[IpcCodeMatch]: + should = _build_es_should_clauses(items) + if not should: + return [] + + payload = { + "size": 200, + "query": {"bool": {"should": should, "minimum_should_match": 1}}, + "_source": [ + "ipc_level", + "ipc_symbol", + "topic_matches", + "keyword_matches", + ], + } + + async with httpx.AsyncClient( + base_url=self.client.base_url, + timeout=self.client.timeout, + transport=self.client.transport, + ) as client: + response = await client.post( + f"/{PATENTS_OPENALEX_KEYWORDS_INDEX}/_search", + headers=self.client._headers(), + json=payload, + ) + response.raise_for_status() + data = response.json() + + merged: dict[tuple[str, str], IpcCodeMatch] = {} + for hit in data.get("hits", {}).get("hits", []): + doc = hit.get("_source", {}) + for item in items: + for match in _matches_from_doc(doc, item): + _merge_ipc_match( + merged, + match.ipc_level, + match.ipc_symbol, + match.match_score, + match.source_keyword, + match.match_type, + ) + + 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 new file mode 100644 index 00000000..86a3ce9b --- /dev/null +++ b/service/src/main/inse/patents/keywords/search_queries.py @@ -0,0 +1,166 @@ +"""Elasticsearch query builders for IPC-based patent search.""" +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.patents_openalex_keywords.ipc_entries import infer_subclass, normalize_symbol + +_PATENT_SOURCE_FIELDS = [ + "doc_number", + "country", + "kind", + "date_publication", + "date_publication_year", + "application_number", + "application_filing_date", + "title_en", + "title_de", + "abstract", + "inventors_name", + "applicants_name", + "ipc", + "cpc", +] + +_USPTO_SOURCE_FIELDS = [ + "publication_number", + "country", + "publication_date", + "publication_year", + "application_number", + "application_date", + "application_type", + "number_of_claims", + "status", + "title", + "abstract", + "inventors_names", + "assignees_orgs", + "ipcr", + "cpc", +] + +_MIN_MATCH_TERM_LEN = 4 + + +def _search_terms_for_symbol(symbol: str) -> list[str]: + """Derive EPO/USPTO `match` terms from an IPC/CPC symbol. + + 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. + """ + 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) + + keys = parse_ipc_symbol(normalized) + 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 len(normalized) >= _MIN_MATCH_TERM_LEN: + prefix = normalized[:_MIN_MATCH_TERM_LEN] + if prefix not in terms: + terms.append(prefix) + + return list(dict.fromkeys(term for term in terms if len(term) >= _MIN_MATCH_TERM_LEN)) + + +def _ipc_match_clauses(field: str, terms: list[str]) -> list[dict[str, Any]]: + clauses: list[dict[str, Any]] = [] + seen: set[tuple[str, str]] = set() + for term in terms: + if len(term) < _MIN_MATCH_TERM_LEN: + continue + key = (field, term) + if key in seen: + continue + seen.add(key) + clauses.append({"match": {field: term}}) + return clauses + + +class IpcPatentSearchQueries: + def epo_query_by_ipc_terms( + self, + terms: list[str], + size: int = DEFAULT_SEARCH_SIZE, + ) -> dict[str, Any]: + should = _ipc_match_clauses("ipc", terms) + _ipc_match_clauses("cpc", terms) + 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": [ + {"date_publication": {"order": "desc", "missing": "_last"}}, + "_doc", + ], + "_source": _PATENT_SOURCE_FIELDS, + "query": query, + } + + def uspto_query_by_ipc_terms( + self, + terms: list[str], + size: int = DEFAULT_SEARCH_SIZE, + ) -> dict[str, Any]: + should = _ipc_match_clauses("ipcr", terms) + _ipc_match_clauses("cpc", terms) + 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": [ + {"publication_date": {"order": "desc", "missing": "_last"}}, + "_doc", + ], + "_source": _USPTO_SOURCE_FIELDS, + "query": query, + } + + def epo_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.epo_query_by_ipc_terms(terms, 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) diff --git a/service/src/main/inse/patents/keywords/service.py b/service/src/main/inse/patents/keywords/service.py new file mode 100644 index 00000000..8aac2ea4 --- /dev/null +++ b/service/src/main/inse/patents/keywords/service.py @@ -0,0 +1,23 @@ +from typing import Annotated + +from fastapi import APIRouter, Body + +from inse.patents.keywords import logic +from inse.patents.keywords.model import PatentsByKeywordsRequest, PatentsByKeywordsResponse + +router = APIRouter(prefix="/api/inse-service/keywords", tags=["Keywords"]) + + +@router.post( + "/patents", + operation_id="getPatentsByKeywords", + response_model=PatentsByKeywordsResponse, + summary="Find patents matching extracted OpenAlex keywords.", +) +async def get_patents_by_keywords( + request: Annotated[ + PatentsByKeywordsRequest, + Body(description="Keywords enriched with OpenAlex topics."), + ], +): + return await logic.get_patents_by_keywords(request) diff --git a/service/src/main/inse/patents/keywords/test_logic.py b/service/src/main/inse/patents/keywords/test_logic.py new file mode 100644 index 00000000..74817c6c --- /dev/null +++ b/service/src/main/inse/patents/keywords/test_logic.py @@ -0,0 +1,128 @@ +"""Tests for keyword-based patent search.""" +from __future__ import annotations + +from inse.patents.common import model +from inse.patents.keywords.logic import _patent_code_matches_symbol, _score_patent +from inse.patents.keywords.reverse_lookup import ( + IpcCodeMatch, + _finalize_ipc_matches, + _json_lookup, + _legacy_lookup, + _weighted_score, + clear_reverse_lookup_caches, +) +from inse.patents.keywords.model import KeywordPatentSearchItem +from inse.patents.keywords.search_queries import _search_terms_for_symbol + + +def test_patent_code_matches_symbol_prefix() -> None: + assert _patent_code_matches_symbol("G01S 5/02", "G01S") + assert _patent_code_matches_symbol("G01S5/02", "G01S") + assert not _patent_code_matches_symbol("H01L 21/02", "G01S") + + +def test_score_patent_uses_best_ipc_match() -> None: + patent = model.PatentEntry( + patent_id="EP123", + source="EPO", + ipc=["G01S 5/02"], + ) + ipc_matches = [ + IpcCodeMatch("subclass", "G01S", 0.9, "localization", "keyword"), + IpcCodeMatch("class", "G01", 0.5, "wireless", "topic"), + ] + result = _score_patent(patent, ipc_matches) + assert result is not None + score, keywords, symbols = result + assert score == 0.9 + assert "localization" in keywords + assert "G01S" in symbols + + +def test_weighted_score_applies_level_and_relevance() -> None: + score = _weighted_score("subclass", 0.8, 0.5) + assert score == round(0.8 * 0.85 * 0.5, 4) + + +def test_search_terms_use_subclass_prefix() -> None: + assert "B60R" in _search_terms_for_symbol("B60R2300/8086") + assert "G06N" in _search_terms_for_symbol("G06N") + + +def test_legacy_lookup_uses_chemistry_heuristics() -> None: + clear_reverse_lookup_caches() + items = [ + KeywordPatentSearchItem( + keyword="Organische Chemie", + relevance_score=1.0, + ) + ] + matches = _finalize_ipc_matches(items, _legacy_lookup(items)) + symbols = {match.ipc_symbol for match in matches} + assert "C07C" in symbols + + +def test_legacy_lookup_uses_medicine_heuristics() -> None: + clear_reverse_lookup_caches() + items = [ + KeywordPatentSearchItem( + keyword="Medizin", + relevance_score=1.0, + ) + ] + matches = _finalize_ipc_matches(items, _legacy_lookup(items)) + symbols = {match.ipc_symbol for match in matches} + assert "A61B" in symbols + + +def test_legacy_lookup_uses_cs_ai_heuristics() -> None: + clear_reverse_lookup_caches() + items = [ + KeywordPatentSearchItem( + keyword="Klassifikation", + topic_id="https://openalex.org/T12072", + topic_display_name="Machine Learning and Algorithms", + subfield_name="Artificial Intelligence", + field_name="Computer Science", + relevance_score=1.0, + ) + ] + matches = _finalize_ipc_matches(items, _legacy_lookup(items)) + symbols = {match.ipc_symbol for match in matches} + assert "G06N" in symbols + + +def test_json_lookup_finds_ipc_for_keyword(monkeypatch) -> None: + clear_reverse_lookup_caches() + monkeypatch.setattr( + "inse.patents.keywords.reverse_lookup.load_patents_openalex_keywords_json", + lambda: { + "subclass": { + "G01S": { + "ipc_level": "subclass", + "ipc_symbol": "G01S", + "keyword_matches": [ + { + "keyword": "wireless localization", + "match_score": 0.91, + "topic_id": "https://openalex.org/T12345", + } + ], + "topic_matches": [], + } + } + }, + ) + clear_reverse_lookup_caches() + + items = [ + KeywordPatentSearchItem( + keyword="wireless localization", + topic_id="https://openalex.org/T12345", + relevance_score=1.0, + ) + ] + matches = _json_lookup(items) + assert len(matches) == 1 + assert matches[0].ipc_symbol == "G01S" + assert matches[0].match_score > 0 diff --git a/service/src/main/inse/patents/patents_openalex_keywords/__init__.py b/service/src/main/inse/patents/patents_openalex_keywords/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/service/src/main/inse/patents/patents_openalex_keywords/client.py b/service/src/main/inse/patents/patents_openalex_keywords/client.py new file mode 100644 index 00000000..57809df0 --- /dev/null +++ b/service/src/main/inse/patents/patents_openalex_keywords/client.py @@ -0,0 +1,171 @@ +"""HTTP client for the patents_openalex_keywords Elasticsearch index.""" +from __future__ import annotations + +import json +import logging +from typing import Any + +import httpx + +from inse import config +from inse.patents.common.elastic_search_client import MissingApiKeyError +from inse.patents.patents_openalex_keywords.mapping import ( + PATENTS_OPENALEX_KEYWORDS_INDEX, + PATENTS_OPENALEX_KEYWORDS_MAPPING, +) + +logger = logging.getLogger(__name__) + +_LEVEL_LOOKUP_ORDER = ("subgroup", "group", "subclass", "class", "section") + + +class PatentsOpenAlexKeywordsClient: + def __init__( + self, + base_url: str | None = None, + api_key: str | None = None, + timeout: float = 10.0, + transport: httpx.AsyncBaseTransport | None = None, + ): + self.base_url = (base_url or config.settings.patent_elasticsearch_url).rstrip("/") + self.api_key = api_key if api_key is not None else config.settings.patent_elasticsearch_api_key + self.timeout = timeout + self.transport = transport + + def _headers(self, content_type: str = "application/json") -> dict[str, str]: + if not self.api_key: + raise MissingApiKeyError("Patent Elasticsearch API key is not configured.") + return { + "Authorization": f"ApiKey {self.api_key}", + "Content-Type": content_type, + } + + async def ensure_index(self) -> None: + async with httpx.AsyncClient( + base_url=self.base_url, + timeout=self.timeout, + transport=self.transport, + ) as client: + response = await client.head( + f"/{PATENTS_OPENALEX_KEYWORDS_INDEX}", + headers=self._headers(), + ) + if response.status_code == 404: + create_response = await client.put( + f"/{PATENTS_OPENALEX_KEYWORDS_INDEX}", + headers=self._headers(), + json={"mappings": PATENTS_OPENALEX_KEYWORDS_MAPPING}, + ) + create_response.raise_for_status() + logger.info("Created index %s", PATENTS_OPENALEX_KEYWORDS_INDEX) + return + + response.raise_for_status() + mapping_response = await client.put( + f"/{PATENTS_OPENALEX_KEYWORDS_INDEX}/_mapping", + headers=self._headers(), + json=PATENTS_OPENALEX_KEYWORDS_MAPPING, + ) + mapping_response.raise_for_status() + + async def index_exists(self) -> bool: + async with httpx.AsyncClient( + base_url=self.base_url, + timeout=self.timeout, + transport=self.transport, + ) as client: + response = await client.head( + f"/{PATENTS_OPENALEX_KEYWORDS_INDEX}", + headers=self._headers(), + ) + if response.status_code == 404: + return False + response.raise_for_status() + return True + + async def bulk_index(self, documents: list[tuple[str, dict[str, Any]]]) -> None: + if not documents: + return + + batch_size = 500 + async with httpx.AsyncClient( + base_url=self.base_url, + timeout=self.timeout, + transport=self.transport, + ) as client: + for start in range(0, len(documents), batch_size): + batch = documents[start : start + batch_size] + bulk_lines: list[str] = [] + for doc_id, source in batch: + bulk_lines.append( + json.dumps( + { + "index": { + "_index": PATENTS_OPENALEX_KEYWORDS_INDEX, + "_id": doc_id, + } + } + ) + ) + bulk_lines.append(json.dumps(source)) + + payload = "\n".join(bulk_lines) + "\n" + response = await client.post( + "/_bulk", + content=payload, + headers=self._headers("application/x-ndjson"), + params={"refresh": "true"}, + ) + response.raise_for_status() + result = response.json() + if result.get("errors"): + failed = [ + item + for item in result.get("items", []) + if item.get("index", {}).get("status", 200) >= 400 + ] + logger.error("Bulk index errors: %s", failed[:3]) + raise RuntimeError( + f"Bulk indexing into {PATENTS_OPENALEX_KEYWORDS_INDEX} failed." + ) + + async def lookup(self, level: str, symbol: str) -> dict[str, Any] | None: + normalized = symbol.strip().upper().replace(" ", "") + doc_id = f"{level}:{normalized}" + async with httpx.AsyncClient( + base_url=self.base_url, + timeout=self.timeout, + transport=self.transport, + ) as client: + response = await client.get( + f"/{PATENTS_OPENALEX_KEYWORDS_INDEX}/_doc/{doc_id}", + headers=self._headers(), + ) + if response.status_code == 404: + return None + response.raise_for_status() + return response.json().get("_source") + + async def lookup_symbol(self, symbol: str) -> dict[str, Any] | None: + from inse.patents.patents_openalex_keywords.ipc_entries import infer_subclass + + normalized = symbol.strip().upper().replace(" ", "") + candidates: list[tuple[str, str]] = [(level, normalized) for level in _LEVEL_LOOKUP_ORDER] + subclass = infer_subclass(normalized) + if subclass: + candidates.append(("subclass", subclass)) + if len(normalized) >= 3: + candidates.append(("class", normalized[:3])) + if normalized: + candidates.append(("section", normalized[:1])) + + seen: set[tuple[str, str]] = set() + for level, candidate in candidates: + key = (level, candidate) + if key in seen: + continue + seen.add(key) + doc = await self.lookup(level, candidate) + if doc is not None: + return doc + return None diff --git a/service/src/main/inse/patents/patents_openalex_keywords/ipc_entries.py b/service/src/main/inse/patents/patents_openalex_keywords/ipc_entries.py new file mode 100644 index 00000000..b89ad79e --- /dev/null +++ b/service/src/main/inse/patents/patents_openalex_keywords/ipc_entries.py @@ -0,0 +1,207 @@ +"""Fetch unique IPC/CPC hierarchy symbols and labels from the ipc Elasticsearch index.""" +from __future__ import annotations + +import re +from collections import defaultdict + +from inse.integrations import elasticsearch +from inse.model import ESCluster +from inse.patents.ipc_search_client import IPC_INDEX + +LEVEL_FIELDS: tuple[tuple[str, str, str], ...] = ( + ("section", "cpc_section_number", "cpc_section_name"), + ("class", "cpc_class_number", "cpc_class_name"), + ("group", "cpc_group_number", "cpc_group_name"), + ("subgroup", "cpc_subgroup_number", "cpc_subgroup_name"), +) +DEFAULT_BUILD_LEVELS = ("section", "class", "subclass", "group", "subgroup") + + +def normalize_symbol(symbol: str | None) -> str: + if not symbol: + return "" + return symbol.strip().upper().replace(" ", "") + + +def infer_subclass(symbol: str | None) -> str | None: + if not symbol: + return None + cleaned = normalize_symbol(symbol) + match = re.match(r"^([A-HY]\d{2}[A-Z])", cleaned) + return match.group(1) if match else None + + +def infer_class(symbol: str | None) -> str | None: + if not symbol: + return None + cleaned = normalize_symbol(symbol) + match = re.match(r"^([A-HY]\d{2})", cleaned) + return match.group(1) if match else None + + +def build_class_entries_from_subclasses( + subclass_entries: dict[str, str], + max_labels_per_class: int = 8, +) -> dict[str, str]: + labels_by_class: dict[str, list[str]] = defaultdict(list) + seen_labels_by_class: dict[str, set[str]] = defaultdict(set) + + for subclass_symbol, subclass_label in sorted(subclass_entries.items()): + class_symbol = infer_class(subclass_symbol) + if not class_symbol: + continue + + label = " ".join(subclass_label.split()) + label_key = label.casefold() + if label_key in seen_labels_by_class[class_symbol]: + continue + + seen_labels_by_class[class_symbol].add(label_key) + labels_by_class[class_symbol].append(f"{subclass_symbol}: {label}") + + class_entries: dict[str, str] = {} + for class_symbol, labels in labels_by_class.items(): + selected_labels = labels[:max_labels_per_class] + class_entries[class_symbol] = ( + f"IPC/CPC class {class_symbol}. Related subclasses: " + "; ".join(selected_labels) + ) + return class_entries + + +async def fetch_unique_ipc_entries( + levels: tuple[str, ...] = DEFAULT_BUILD_LEVELS, +) -> dict[str, dict[str, str]]: + entries: dict[str, dict[str, str]] = defaultdict(dict) + + async def _composite_with_label( + level: str, + number_field: str, + name_field: str, + page_size: int, + ) -> bool: + for field_name in (number_field, f"{number_field}.keyword"): + after_key: dict[str, str] | None = None + found_any = False + while True: + payload: dict[str, object] = { + "size": 0, + "aggs": { + "items": { + "composite": { + "size": page_size, + "sources": [ + {"symbol": {"terms": {"field": field_name}}}, + ], + }, + "aggs": { + "sample": { + "top_hits": {"size": 1, "_source": [name_field]}, + } + }, + } + }, + } + if after_key: + payload["aggs"]["items"]["composite"]["after"] = after_key + try: + data = await elasticsearch.search( + index=IPC_INDEX, + body=payload, + cluster=ESCluster.INSE, + ) + except Exception: + found_any = False + break + items = data.get("aggregations", {}).get("items", {}) + buckets = items.get("buckets", []) + if not buckets: + break + found_any = True + for bucket in buckets: + key = bucket.get("key", {}) + symbol = key.get("symbol") + hits = bucket.get("sample", {}).get("hits", {}).get("hits", []) + if not symbol or not hits: + continue + name = hits[0].get("_source", {}).get(name_field) + if not name: + continue + normalized = normalize_symbol(str(symbol)) + if level == "subclass": + if len(normalized) <= 3: + continue + normalized = infer_subclass(str(symbol)) or normalized + entries[level][normalized] = str(name).strip() + after_key = items.get("after_key") + if not after_key: + break + if found_any: + return True + return False + + async def _terms_with_label( + level: str, + number_field: str, + name_field: str, + size: int, + ) -> None: + for field_name in (number_field, f"{number_field}.keyword"): + payload = { + "size": 0, + "aggs": { + "items": { + "terms": {"field": field_name, "size": size}, + "aggs": { + "sample": { + "top_hits": {"size": 1, "_source": [name_field]}, + } + }, + } + }, + } + try: + data = await elasticsearch.search( + index=IPC_INDEX, + body=payload, + cluster=ESCluster.INSE, + ) + except Exception: + continue + buckets = data.get("aggregations", {}).get("items", {}).get("buckets", []) + if buckets: + break + else: + return + for bucket in buckets: + symbol = bucket.get("key") + hits = bucket.get("sample", {}).get("hits", {}).get("hits", []) + if not symbol or not hits: + continue + name = hits[0].get("_source", {}).get(name_field) + if not name: + continue + normalized = normalize_symbol(str(symbol)) + if level == "class" and len(normalized) != 3: + continue + if level == "subclass": + if len(normalized) <= 3: + continue + normalized = infer_subclass(str(symbol)) or normalized + entries[level][normalized] = str(name).strip() + + if "section" in levels: + await _terms_with_label("section", "cpc_section_number", "cpc_section_name", 30) + if "subclass" in levels or "class" in levels: + await _terms_with_label("subclass", "cpc_class_number", "cpc_class_name", 10000) + if "group" in levels: + if not await _composite_with_label("group", "cpc_group_number", "cpc_group_name", 1000): + await _terms_with_label("group", "cpc_group_number", "cpc_group_name", 20000) + if "subgroup" in levels: + if not await _composite_with_label("subgroup", "cpc_subgroup_number", "cpc_subgroup_name", 1000): + await _terms_with_label("subgroup", "cpc_subgroup_number", "cpc_subgroup_name", 20000) + if "class" in levels: + subclass_entries = entries.get("subclass", {}) + entries["class"].update(build_class_entries_from_subclasses(subclass_entries)) + if "subclass" not in levels: + entries.pop("subclass", None) + return entries diff --git a/service/src/main/inse/patents/patents_openalex_keywords/mapping.py b/service/src/main/inse/patents/patents_openalex_keywords/mapping.py new file mode 100644 index 00000000..8464dd30 --- /dev/null +++ b/service/src/main/inse/patents/patents_openalex_keywords/mapping.py @@ -0,0 +1,34 @@ +PATENTS_OPENALEX_KEYWORDS_INDEX = "patents_openalex_keywords" + +PATENTS_OPENALEX_KEYWORDS_MAPPING = { + "properties": { + "ipc_level": {"type": "keyword"}, + "ipc_symbol": {"type": "keyword"}, + "ipc_label": {"type": "text", "fields": {"keyword": {"type": "keyword"}}}, + "topic_matches": { + "type": "nested", + "properties": { + "rank": {"type": "integer"}, + "topic_id": {"type": "keyword"}, + "topic_display_name": {"type": "keyword"}, + "subfield": {"type": "keyword"}, + "field": {"type": "keyword"}, + "domain": {"type": "keyword"}, + "match_score": {"type": "float"}, + }, + }, + "keyword_matches": { + "type": "nested", + "properties": { + "rank": {"type": "integer"}, + "keyword": {"type": "keyword"}, + "topic_id": {"type": "keyword"}, + "topic_display_name": {"type": "keyword"}, + "match_score": {"type": "float"}, + }, + }, + "match_method": {"type": "keyword"}, + "model_name": {"type": "keyword"}, + "built_at": {"type": "date"}, + } +} diff --git a/service/src/main/inse/patents/patents_openalex_keywords/matching.py b/service/src/main/inse/patents/patents_openalex_keywords/matching.py new file mode 100644 index 00000000..2467d4d6 --- /dev/null +++ b/service/src/main/inse/patents/patents_openalex_keywords/matching.py @@ -0,0 +1,409 @@ +"""SentenceTransformer-based IPC/CPC → OpenAlex topic/keyword matching.""" +from __future__ import annotations + +import json +import logging +from dataclasses import dataclass +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + +import numpy as np +from sentence_transformers import SentenceTransformer + +from inse.config import settings +from inse.integrations import elasticsearch +from inse.model import ESCluster +from inse.util import get_model + +logger = logging.getLogger(__name__) + +TOPIC_CACHE_FILENAME = "topic_hierarchy_cache.json" +MATCH_METHOD = "sentence_transformer" +TOPIC_VECTORS_INDEX = "topicvectors" + + +@dataclass(frozen=True) +class TopicCandidate: + topic_id: str + display_name: str + subfield: str | None = None + field: str | None = None + domain: str | None = None + + +@dataclass(frozen=True) +class KeywordCandidate: + keyword: str + topic_id: str + topic_display_name: str | None = None + + +def _data_dir() -> Path: + return Path(__file__).resolve().parents[4] / "data" + + +def load_topic_cache(cache_path: Path | None = None) -> list[TopicCandidate]: + path = cache_path or (_data_dir() / TOPIC_CACHE_FILENAME) + with path.open(encoding="utf-8") as handle: + raw = json.load(handle) + topics: list[TopicCandidate] = [] + for display_name, info in raw.items(): + topic_id = info.get("topic_id") + if not topic_id: + continue + topics.append( + TopicCandidate( + topic_id=str(topic_id), + display_name=display_name, + subfield=info.get("subfield"), + field=info.get("field"), + domain=info.get("domain"), + ) + ) + return topics + + +def topic_embedding_text(topic: TopicCandidate) -> str: + parts = [topic.display_name] + for label in (topic.subfield, topic.field, topic.domain): + if label: + parts.append(label) + return ". ".join(parts) + + +async def fetch_keyword_candidates() -> list[KeywordCandidate]: + candidates: list[KeywordCandidate] = [] + seen: set[tuple[str, str]] = set() + async for hit in elasticsearch.scan( + index="openalex-topics", + query={"match_all": {}}, + source=["id", "display_name", "keywords"], + cluster=ESCluster.NES, + ): + source = hit.get("_source", {}) + topic_id = source.get("id") + topic_name = source.get("display_name") + if not topic_id: + continue + keywords = source.get("keywords") or [] + if not isinstance(keywords, list): + keywords = [keywords] if keywords else [] + for keyword in keywords: + if not keyword or not str(keyword).strip(): + continue + key = (str(topic_id), str(keyword).strip().casefold()) + if key in seen: + continue + seen.add(key) + candidates.append( + KeywordCandidate( + keyword=str(keyword).strip(), + topic_id=str(topic_id), + topic_display_name=topic_name, + ) + ) + return candidates + + +def _normalize_rows(vectors: np.ndarray) -> np.ndarray: + norms = np.linalg.norm(vectors, axis=1, keepdims=True) + norms = np.where(norms == 0, 1.0, norms) + return vectors / norms + + +def top_k_indices(query_vector: np.ndarray, corpus_matrix: np.ndarray, k: int) -> list[tuple[int, float]]: + if corpus_matrix.size == 0: + return [] + scores = corpus_matrix @ query_vector + limit = min(k, len(scores)) + if limit <= 0: + return [] + top_idx = np.argpartition(-scores, limit - 1)[:limit] + top_idx = top_idx[np.argsort(-scores[top_idx])] + return [(int(idx), float(scores[idx])) for idx in top_idx] + + +class EmbeddingMatcher: + def __init__( + self, + model: SentenceTransformer | None = None, + min_score: float = 0.5, + batch_size: int = 64, + ): + self.model = model or get_model() + self.min_score = min_score + self.batch_size = batch_size + self.model_name = settings.sentence_transformers_model_name + self._topic_candidates: list[TopicCandidate] = [] + self._keyword_candidates: list[KeywordCandidate] = [] + self._topic_matrix: np.ndarray | None = None + self._keyword_matrix: np.ndarray | None = None + + def prepare_topics(self, topics: list[TopicCandidate]) -> None: + self._topic_candidates = topics + texts = [topic_embedding_text(topic) for topic in topics] + vectors = self.model.encode( + texts, + batch_size=self.batch_size, + show_progress_bar=True, + convert_to_numpy=True, + ) + self._topic_matrix = _normalize_rows(np.asarray(vectors, dtype=np.float32)) + + def prepare_keywords(self, keywords: list[KeywordCandidate]) -> None: + self._keyword_candidates = keywords + if not keywords: + self._keyword_matrix = np.empty((0, 0), dtype=np.float32) + return + texts = [item.keyword for item in keywords] + vectors = self.model.encode( + texts, + batch_size=self.batch_size, + show_progress_bar=True, + convert_to_numpy=True, + ) + self._keyword_matrix = _normalize_rows(np.asarray(vectors, dtype=np.float32)) + + def match_ipc_label( + self, + ipc_label: str, + top_k: int, + ) -> tuple[list[dict], list[dict]]: + query_vector = self.model.encode( + ipc_label, + convert_to_numpy=True, + ) + query_vector = query_vector / max(float(np.linalg.norm(query_vector)), 1e-9) + + topic_matches: list[dict] = [] + if self._topic_matrix is not None and len(self._topic_candidates): + for rank, (idx, score) in enumerate( + top_k_indices(query_vector, self._topic_matrix, top_k), + start=1, + ): + if score < self.min_score: + continue + topic = self._topic_candidates[idx] + topic_matches.append( + { + "rank": rank, + "topic_id": topic.topic_id, + "topic_display_name": topic.display_name, + "subfield": topic.subfield, + "field": topic.field, + "domain": topic.domain, + "match_score": round(score, 4), + } + ) + + keyword_matches: list[dict] = [] + if self._keyword_matrix is not None and len(self._keyword_candidates): + for rank, (idx, score) in enumerate( + top_k_indices(query_vector, self._keyword_matrix, top_k), + start=1, + ): + if score < self.min_score: + continue + keyword = self._keyword_candidates[idx] + keyword_matches.append( + { + "rank": rank, + "keyword": keyword.keyword, + "topic_id": keyword.topic_id, + "topic_display_name": keyword.topic_display_name, + "match_score": round(score, 4), + } + ) + + return topic_matches, keyword_matches + + +def build_documents( + ipc_entries: dict[str, dict[str, str]], + matcher: EmbeddingMatcher, + levels: tuple[str, ...], + top_k: int, +) -> list[tuple[str, dict]]: + built_at = datetime.now(timezone.utc).isoformat() + documents: list[tuple[str, dict]] = [] + label_cache: dict[str, tuple[list[dict], list[dict]]] = {} + + for level in levels: + for symbol, label in ipc_entries.get(level, {}).items(): + cache_key = label.casefold() + if cache_key not in label_cache: + label_cache[cache_key] = matcher.match_ipc_label(label, top_k=top_k) + topic_matches, keyword_matches = label_cache[cache_key] + if not topic_matches and not keyword_matches: + continue + doc_id = f"{level}:{symbol}" + documents.append( + ( + doc_id, + { + "ipc_level": level, + "ipc_symbol": symbol, + "ipc_label": label, + "topic_matches": topic_matches, + "keyword_matches": keyword_matches, + "match_method": MATCH_METHOD, + "model_name": matcher.model_name, + "built_at": built_at, + }, + ) + ) + return documents + + +def documents_to_json_mapping(documents: list[tuple[str, dict]]) -> dict[str, dict[str, dict]]: + mapping: dict[str, dict[str, dict]] = { + "section": {}, + "class": {}, + "subclass": {}, + "group": {}, + "subgroup": {}, + } + for _doc_id, source in documents: + level = source["ipc_level"] + symbol = source["ipc_symbol"] + mapping.setdefault(level, {})[symbol] = source + return mapping + + +class TopicVectorsMatcher: + + def __init__( + self, + model: SentenceTransformer | None = None, + min_score: float = 0.5, + num_candidates: int = 200, + ): + self.model = model or get_model() + self.min_score = min_score + self.num_candidates = num_candidates + self.model_name = settings.sentence_transformers_model_name + + async def _search_topic_vectors( + self, + *, + vector: list[float], + top_k: int, + ) -> list[dict[str, Any]]: + payload = { + "size": max(top_k * 4, top_k), + "_source": ["id", "display_name", "subfield", "field", "domain", "keywords"], + "knn": { + "field": "display_name_vector", + "query_vector": vector, + "k": max(top_k * 4, top_k), + "num_candidates": max(self.num_candidates, top_k * 8), + }, + } + data = await elasticsearch.search( + index=TOPIC_VECTORS_INDEX, + body=payload, + cluster=ESCluster.NES, + ) + return data.get("hits", {}).get("hits", []) or [] + + async def match_ipc_label( + self, + ipc_label: str, + top_k: int, + ) -> tuple[list[dict], list[dict]]: + vector = self.model.encode(ipc_label, convert_to_numpy=True) + query_vector = _normalize_rows(np.asarray([vector], dtype=np.float32))[0].tolist() + hits = await self._search_topic_vectors(vector=query_vector, top_k=top_k) + + topic_matches: list[dict] = [] + keyword_matches: list[dict] = [] + seen_topics: set[str] = set() + seen_keywords: set[tuple[str, str]] = set() + + for hit in hits: + source = hit.get("_source", {}) + topic_id = str(source.get("id") or "") + topic_name = str(source.get("display_name") or "") + if not topic_id or not topic_name or topic_id in seen_topics: + continue + score = float(hit.get("_score") or 0.0) + if score < self.min_score: + continue + + seen_topics.add(topic_id) + topic_matches.append( + { + "rank": len(topic_matches) + 1, + "topic_id": topic_id, + "topic_display_name": topic_name, + "subfield": source.get("subfield"), + "field": source.get("field"), + "domain": source.get("domain"), + "match_score": round(score, 4), + } + ) + + keywords = source.get("keywords") or [] + if not isinstance(keywords, list): + keywords = [keywords] if keywords else [] + for keyword in keywords: + normalized_keyword = str(keyword).strip() + if not normalized_keyword: + continue + key = (topic_id, normalized_keyword.casefold()) + if key in seen_keywords: + continue + seen_keywords.add(key) + keyword_matches.append( + { + "rank": len(keyword_matches) + 1, + "keyword": normalized_keyword, + "topic_id": topic_id, + "topic_display_name": topic_name, + "match_score": round(score, 4), + } + ) + break + + if len(topic_matches) >= top_k and len(keyword_matches) >= top_k: + break + + return topic_matches[:top_k], keyword_matches[:top_k] + + +async def build_documents_from_topicvectors( + ipc_entries: dict[str, dict[str, str]], + matcher: TopicVectorsMatcher, + levels: tuple[str, ...], + top_k: int, +) -> list[tuple[str, dict]]: + built_at = datetime.now(timezone.utc).isoformat() + documents: list[tuple[str, dict]] = [] + label_cache: dict[str, tuple[list[dict], list[dict]]] = {} + + for level in levels: + for symbol, label in ipc_entries.get(level, {}).items(): + cache_key = label.casefold() + if cache_key not in label_cache: + label_cache[cache_key] = await matcher.match_ipc_label(label, top_k=top_k) + topic_matches, keyword_matches = label_cache[cache_key] + if not topic_matches and not keyword_matches: + continue + doc_id = f"{level}:{symbol}" + documents.append( + ( + doc_id, + { + "ipc_level": level, + "ipc_symbol": symbol, + "ipc_label": label, + "topic_matches": topic_matches, + "keyword_matches": keyword_matches, + "match_method": "topicvectors_knn", + "model_name": matcher.model_name, + "built_at": built_at, + }, + ) + ) + return documents diff --git a/service/src/main/inse/patents/patents_openalex_keywords/resolver.py b/service/src/main/inse/patents/patents_openalex_keywords/resolver.py new file mode 100644 index 00000000..bb33970b --- /dev/null +++ b/service/src/main/inse/patents/patents_openalex_keywords/resolver.py @@ -0,0 +1,284 @@ +"""Runtime resolver for IPC/CPC → OpenAlex matches from patents_openalex_keywords.""" +from __future__ import annotations + +import json +import logging +import os +from functools import lru_cache + +from inse.patents.authors.ipc_openalex_mapping import ( + MappedOpenAlexTopic, + _enrich_mapped_topic, + load_ipc_openalex_mapping, + normalize_openalex_id, + resolve_mapped_topics_for_code, +) +from inse.patents.common import model +from inse.patents.ipc_lookup import extract_ipc_symbol, parse_ipc_symbol +from inse.patents.patents_openalex_keywords.client import PatentsOpenAlexKeywordsClient +from inse.patents.patents_openalex_keywords.ipc_entries import infer_subclass, normalize_symbol + +logger = logging.getLogger(__name__) + +KEYWORDS_MAPPING_FILENAME = "patents_openalex_keywords_mapping.json" +_LEVEL_ORDER = {"subgroup": 5, "group": 4, "subclass": 3, "class": 2, "section": 1} + + +def _data_dir() -> str: + for base in ( + "/data", + os.path.normpath( + os.path.join( + os.path.dirname(__file__), + "..", + "..", + "..", + "..", + "data", + ) + ), + ): + if os.path.isdir(base): + return base + return os.path.normpath( + os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "data") + ) + + +@lru_cache(maxsize=1) +def load_patents_openalex_keywords_json() -> dict[str, dict[str, dict]]: + path = os.path.join(_data_dir(), KEYWORDS_MAPPING_FILENAME) + try: + with open(path, encoding="utf-8") as handle: + raw = json.load(handle) + except (OSError, json.JSONDecodeError): + return {} + if not isinstance(raw, dict): + return {} + return { + level: { + normalize_symbol(symbol): entry + for symbol, entry in (entries or {}).items() + if isinstance(entry, dict) + } + for level, entries in raw.items() + if isinstance(entries, dict) + } + + +def clear_resolver_caches() -> None: + load_patents_openalex_keywords_json.cache_clear() + + +def mapped_topics_from_index_doc(doc: dict) -> list[MappedOpenAlexTopic]: + seen: set[str] = set() + mapped: list[MappedOpenAlexTopic] = [] + ipc_level = doc.get("ipc_level") + ipc_symbol = doc.get("ipc_symbol") + + for match in doc.get("topic_matches") or []: + topic_id = match.get("topic_id") + if not topic_id: + continue + key = normalize_openalex_id(str(topic_id)) or str(topic_id) + if key in seen: + continue + seen.add(key) + mapped.append( + _enrich_mapped_topic( + MappedOpenAlexTopic( + topic_id=str(topic_id), + topic_display_name=match.get("topic_display_name"), + subfield_name=match.get("subfield"), + field_name=match.get("field"), + domain_name=match.get("domain"), + ipc_level=ipc_level, + ipc_symbol=ipc_symbol, + ) + ) + ) + + for match in doc.get("keyword_matches") or []: + topic_id = match.get("topic_id") + if not topic_id: + continue + key = normalize_openalex_id(str(topic_id)) or str(topic_id) + if key in seen: + continue + seen.add(key) + mapped.append( + _enrich_mapped_topic( + MappedOpenAlexTopic( + topic_id=str(topic_id), + topic_display_name=match.get("topic_display_name"), + ipc_level=ipc_level, + ipc_symbol=ipc_symbol, + ) + ) + ) + + return mapped + + +def _json_lookup_symbol( + symbol: str, + table: dict[str, dict[str, dict]], +) -> dict | None: + normalized = normalize_symbol(symbol) + best_doc: dict | None = None + best_rank = -1 + + subclass = infer_subclass(normalized) + candidates: list[tuple[str, str]] = [ + ("subgroup", normalized), + ("group", normalized), + ] + if subclass: + candidates.append(("subclass", subclass)) + if len(normalized) >= 3: + candidates.append(("class", normalized[:3])) + if normalized: + candidates.append(("section", normalized[:1])) + + for level, candidate in candidates: + doc = table.get(level, {}).get(candidate) + if not doc: + continue + rank = _LEVEL_ORDER.get(level, 0) + if rank > best_rank: + best_rank = rank + best_doc = doc + + if best_doc is not None: + return best_doc + + for entries in table.values(): + if normalized in entries: + return entries[normalized] + return None + + +def _lookup_candidates(raw_code: str) -> list[str]: + symbol = extract_ipc_symbol(raw_code) + if not symbol: + return [] + + candidates: list[str] = [] + normalized = normalize_symbol(symbol) + if normalized: + candidates.append(normalized) + + keys = parse_ipc_symbol(symbol) or parse_ipc_symbol(normalized) + if keys is not None: + for value in ( + keys.subgroup or keys.normalized, + keys.main_group, + keys.subclass, + keys.ipc_class, + keys.section, + ): + if value: + candidates.append(normalize_symbol(value)) + + subclass = infer_subclass(normalized) + if subclass: + candidates.append(subclass) + + seen: set[str] = set() + ordered: list[str] = [] + for candidate in candidates: + if candidate and candidate not in seen: + seen.add(candidate) + ordered.append(candidate) + return ordered + + +class PatentOpenAlexMappingResolver: + """Resolve patent IPC/CPC codes via patents_openalex_keywords (ES → JSON → legacy).""" + + def __init__( + self, + client: PatentsOpenAlexKeywordsClient | None = None, + *, + use_elasticsearch: bool = True, + ): + self.client = client or PatentsOpenAlexKeywordsClient() + self.use_elasticsearch = use_elasticsearch + self._doc_cache: dict[str, dict | None] = {} + self._legacy_mapping = load_ipc_openalex_mapping() + self._elasticsearch_checked = False + self._elasticsearch_enabled = False + + async def resolve_topics_for_patents( + self, + patents: list[model.PatentEntry], + ) -> dict[str, list[MappedOpenAlexTopic]]: + from inse.patents.common.parsing import patent_map_key + + result: dict[str, list[MappedOpenAlexTopic]] = {} + for patent in patents: + result[patent_map_key(patent)] = await self.resolve_mapped_topics_for_patent( + patent + ) + return result + + async def _elasticsearch_enabled_for_request(self) -> bool: + if not self.use_elasticsearch: + return False + if self._elasticsearch_checked: + return self._elasticsearch_enabled + self._elasticsearch_checked = True + try: + self._elasticsearch_enabled = await self.client.index_exists() + except Exception as exc: + logger.warning("patents_openalex_keywords index check failed: %s", exc) + self._elasticsearch_enabled = False + return self._elasticsearch_enabled + + async def resolve_mapped_topics_for_patent( + self, + patent: model.PatentEntry, + ) -> list[MappedOpenAlexTopic]: + seen: set[str] = set() + resolved: list[MappedOpenAlexTopic] = [] + for raw_code in (*patent.ipc, *patent.cpc): + for mapped in await self.resolve_mapped_topics_for_code(raw_code): + topic_key = normalize_openalex_id(mapped.topic_id) or mapped.topic_id + if topic_key in seen: + continue + seen.add(topic_key) + resolved.append(mapped) + return resolved + + async def resolve_mapped_topics_for_code(self, raw_code: str) -> list[MappedOpenAlexTopic]: + for candidate in _lookup_candidates(raw_code): + doc = await self._lookup_document(candidate) + if doc is not None: + mapped = mapped_topics_from_index_doc(doc) + if mapped: + return mapped + + return resolve_mapped_topics_for_code(raw_code, self._legacy_mapping) + + async def _lookup_document(self, symbol: str) -> dict | None: + normalized = normalize_symbol(symbol) + if normalized in self._doc_cache: + return self._doc_cache[normalized] + + doc: dict | None = None + if await self._elasticsearch_enabled_for_request(): + try: + doc = await self.client.lookup_symbol(normalized) + except Exception as exc: + logger.warning( + "patents_openalex_keywords ES lookup failed for %s: %s", + normalized, + exc, + ) + self._elasticsearch_enabled = False + + if doc is None: + doc = _json_lookup_symbol(normalized, load_patents_openalex_keywords_json()) + + self._doc_cache[normalized] = doc + return doc diff --git a/service/src/main/inse/patents/patents_openalex_keywords/test_matching.py b/service/src/main/inse/patents/patents_openalex_keywords/test_matching.py new file mode 100644 index 00000000..66417433 --- /dev/null +++ b/service/src/main/inse/patents/patents_openalex_keywords/test_matching.py @@ -0,0 +1,88 @@ +"""Tests for patents_openalex_keywords embedding matcher.""" +from __future__ import annotations + +import numpy as np +import pytest + +from inse.patents.patents_openalex_keywords.matching import ( + EmbeddingMatcher, + TopicCandidate, + top_k_indices, + topic_embedding_text, +) + + +def test_topic_embedding_text_joins_hierarchy() -> None: + topic = TopicCandidate( + topic_id="T1", + display_name="Cancer Immunotherapy", + subfield="Oncology", + field="Medicine", + domain="Health", + ) + assert topic_embedding_text(topic) == "Cancer Immunotherapy. Oncology. Medicine. Health" + + +def test_top_k_indices_returns_highest_scores() -> None: + corpus = np.array( + [ + [1.0, 0.0, 0.0], + [0.0, 1.0, 0.0], + [0.9, 0.1, 0.0], + ], + dtype=np.float32, + ) + corpus = corpus / np.linalg.norm(corpus, axis=1, keepdims=True) + query = np.array([1.0, 0.0, 0.0], dtype=np.float32) + + matches = top_k_indices(query, corpus, k=2) + assert len(matches) == 2 + assert matches[0][0] in {0, 2} + assert matches[0][1] >= matches[1][1] + + +class _FakeModel: + def encode(self, sentences, **kwargs): + del kwargs + if isinstance(sentences, str): + sentences = [sentences] + vectors = [] + for text in sentences: + lowered = text.casefold() + if "surgery" in lowered: + vectors.append(np.array([1.0, 0.0], dtype=np.float32)) + elif "immunotherapy" in lowered: + vectors.append(np.array([0.95, 0.05], dtype=np.float32)) + else: + vectors.append(np.array([0.0, 1.0], dtype=np.float32)) + arr = np.vstack(vectors) + if len(sentences) == 1 and isinstance(sentences[0], str): + return arr[0] + return arr + + +def test_embedding_matcher_returns_topic_and_keyword_matches() -> None: + matcher = EmbeddingMatcher(model=_FakeModel(), min_score=0.5) + matcher.prepare_topics( + [ + TopicCandidate(topic_id="T1", display_name="Cancer Immunotherapy"), + TopicCandidate(topic_id="T2", display_name="Unrelated Topic"), + ] + ) + from inse.patents.patents_openalex_keywords.matching import KeywordCandidate + + matcher.prepare_keywords( + [ + KeywordCandidate(keyword="surgery", topic_id="T9", topic_display_name="Surgery"), + KeywordCandidate(keyword="finance", topic_id="T8", topic_display_name="Finance"), + ] + ) + + topic_matches, keyword_matches = matcher.match_ipc_label( + "medical immunotherapy devices", + top_k=2, + ) + assert topic_matches + assert topic_matches[0]["topic_id"] == "T1" + assert keyword_matches + assert keyword_matches[0]["keyword"] == "surgery" diff --git a/service/src/main/inse/patents/patents_openalex_keywords/test_resolver.py b/service/src/main/inse/patents/patents_openalex_keywords/test_resolver.py new file mode 100644 index 00000000..f46378de --- /dev/null +++ b/service/src/main/inse/patents/patents_openalex_keywords/test_resolver.py @@ -0,0 +1,102 @@ +"""Tests for patents_openalex_keywords runtime resolver.""" +from __future__ import annotations + +import asyncio + +from inse.patents.authors.ipc_openalex_mapping import MappedOpenAlexTopic +from inse.patents.authors.test_ipc_openalex_mapping import _author_with_topic +from inse.patents.authors.topic_filter import filter_patents_by_ipc_topic_mapping +from inse.patents.common import model +from inse.patents.patents_openalex_keywords.resolver import ( + PatentOpenAlexMappingResolver, + mapped_topics_from_index_doc, +) + + +def test_mapped_topics_from_index_doc_includes_topics_and_keywords() -> None: + doc = { + "ipc_level": "subclass", + "ipc_symbol": "H01L", + "topic_matches": [ + { + "rank": 1, + "topic_id": "https://openalex.org/T99999", + "topic_display_name": "Semiconductor materials and devices", + "subfield": "Electrical Engineering", + } + ], + "keyword_matches": [ + { + "rank": 1, + "keyword": "silicon", + "topic_id": "https://openalex.org/T88888", + "topic_display_name": "Silicon Processing", + } + ], + } + mapped = mapped_topics_from_index_doc(doc) + assert len(mapped) == 2 + assert {item.topic_id for item in mapped} == { + "https://openalex.org/T99999", + "https://openalex.org/T88888", + } + + +class _FakeKeywordsClient: + def __init__(self, docs: dict[str, dict]): + self.docs = docs + + async def index_exists(self) -> bool: + return True + + async def lookup_symbol(self, symbol: str): + return self.docs.get(symbol) + + +def test_resolver_uses_index_doc_before_legacy_fallback() -> None: + resolver = PatentOpenAlexMappingResolver( + client=_FakeKeywordsClient( + { + "H01L": { + "ipc_level": "subclass", + "ipc_symbol": "H01L", + "topic_matches": [ + { + "topic_id": "https://openalex.org/T99999", + "topic_display_name": "Semiconductor materials and devices", + } + ], + "keyword_matches": [], + } + } + ), + use_elasticsearch=True, + ) + mapped = asyncio.run(resolver.resolve_mapped_topics_for_code("H01L 21/02")) + assert mapped + assert mapped[0].topic_id.endswith("T99999") + + +def test_filter_uses_patent_topic_map_from_resolver() -> None: + author = _author_with_topic( + "https://openalex.org/T99999", + "Semiconductor materials and devices", + ) + patent = model.PatentEntry(patent_id="EP1", source="EPO", ipc=["H01L 21/02"]) + from inse.patents.common.parsing import patent_map_key + + topic_map = { + patent_map_key(patent): [ + MappedOpenAlexTopic( + topic_id="https://openalex.org/T99999", + topic_display_name="Semiconductor materials and devices", + ) + ] + } + filtered = filter_patents_by_ipc_topic_mapping( + [patent], + author, + is_ambiguous=True, + patent_topic_map=topic_map, + ) + assert len(filtered) == 1 diff --git a/webapp/src/app/api/api/patents.service.ts b/webapp/src/app/api/api/patents.service.ts index 14d602a1..1844b05e 100644 --- a/webapp/src/app/api/api/patents.service.ts +++ b/webapp/src/app/api/api/patents.service.ts @@ -16,6 +16,10 @@ import { PatentsByAuthorResponse } from '../model/patentsByAuthorResponse'; import { PatentsByInstitutionResponse } from '../model/patentsByInstitutionResponse'; import { OrgPatentsResponse, OrgPatentMatchTypeFilter } from '../model/orgPatentsResponse'; import { AllPatentsResponse } from '../model/allPatentsResponse'; +import { + PatentsByKeywordsRequest, + PatentsByKeywordsResponse, +} from '../model/patentsByKeywordsResponse'; export type { AllPatentsResponse }; @@ -402,4 +406,19 @@ export class PatentsService extends BaseService { headers: localVarHeaders, }); } + + public getPatentsByKeywords( + request: PatentsByKeywordsRequest, + ): Observable { + const localVarHeaders = this.defaultHeaders.set('Accept', 'application/json'); + const { basePath, withCredentials } = this.configuration; + return this.httpClient.post( + `${basePath}/api/inse-service/keywords/patents`, + request, + { + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + }, + ); + } } diff --git a/webapp/src/app/api/model/patentsByKeywordsResponse.ts b/webapp/src/app/api/model/patentsByKeywordsResponse.ts new file mode 100644 index 00000000..e2b8921a --- /dev/null +++ b/webapp/src/app/api/model/patentsByKeywordsResponse.ts @@ -0,0 +1,26 @@ +import { PatentEntry } from './patentEntry'; + +export interface KeywordPatentSearchItem { + keyword: string; + topic_id?: string | null; + topic_display_name?: string | null; + subfield_name?: string | null; + field_name?: string | null; + relevance_score?: number; +} + +export interface PatentsByKeywordsRequest { + keywords: KeywordPatentSearchItem[]; +} + +export interface KeywordPatentMatch { + patent: PatentEntry; + match_score: number; + matched_keywords?: string[]; + matched_ipc_symbols?: string[]; +} + +export interface PatentsByKeywordsResponse { + patent_count: number; + patents: KeywordPatentMatch[]; +} 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 new file mode 100644 index 00000000..6d96b219 --- /dev/null +++ b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html @@ -0,0 +1,114 @@ +@if (loading()) { +

Lade passende Patente...

+} @else if (error()) { +

Fehler beim Laden der Patente.

+} @else if (matches().length === 0) { +

Keine passenden Patente gefunden.

+} @else { +
+

Passende Patente

+ +
+
+
+ +
+ + + + + + + + + + + @for (item of pagedMatches(); track trackMatch($index, item)) { + + + + + + } + +
PatentQuelleJahr
+ {{ item.patent.title ?? item.patent.patent_id }} + + + {{ item.patent.source }} + + {{ item.patent.publication_year ?? '-' }}
+ + @if (hasPagination()) { + + } +
+ + @if (selectedPatent(); as patent) { +
+

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

+
+
+ Quelle + + + {{ patent.source }} + + +
+
+ Patent-Nr. + {{ patent.patent_id }} +
+
+ Datum + {{ + formatDate(patent.publication_date) + }} +
+ @if (getPublicationStageLabel(patent); as stageLabel) { +
+ Publikationsstufe + {{ stageLabel }} +
+ } +
+ + +
+ } +
+
+} 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 new file mode 100644 index 00000000..be8b1c24 --- /dev/null +++ b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.scss @@ -0,0 +1,145 @@ +.message { + padding: 16px; + color: #666; +} + +.section-title { + margin: 0 0 16px; + font-size: 1.25rem; +} + +.patents-container { + margin-top: 1.5rem; + padding: 16px; + border-radius: 12px; + background: #fff; + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08); +} + +.sort-control { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 10px 14px; + border-radius: 20px; + background: #f2f2f2; + font-size: 14px; + + select { + border: 0; + background: transparent; + font: inherit; + cursor: pointer; + } +} + +.patents-content { + display: flex; + gap: 24px; + align-items: flex-start; +} + +.patents-list { + flex: 1; + + table { + width: 100%; + border-collapse: collapse; + } + + th { + text-align: left; + padding: 10px 12px; + border-bottom: 2px solid #e0e0e0; + } + + tr { + cursor: pointer; + + &:hover { + background: #f5f5f5; + } + + &.selected { + background: #f0f0f0; + } + } + + td { + padding: 10px 12px; + border-bottom: 1px solid #eee; + } +} + +.patent-title { + font-weight: 500; +} + +.source-badge { + display: inline-block; + padding: 2px 8px; + border-radius: 999px; + font-size: 12px; + font-weight: 600; + + &--epo { + background: #dbeafe; + color: #1e40af; + } + + &--uspto { + background: #dcfce7; + color: #166534; + } +} + +.pagination { + display: flex; + align-items: center; + gap: 12px; + margin-top: 12px; +} + +.patent-detail { + flex: 0 0 320px; + padding: 16px; + border-radius: 12px; + background: #f8fafc; +} + +.detail-stats { + display: grid; + gap: 10px; + margin: 12px 0; +} + +.stat-label { + display: block; + font-size: 12px; + color: #666; +} + +.patent-detail-action { + display: flex; + align-items: center; + justify-content: space-between; + width: 100%; + margin-top: 12px; + padding: 10px 12px; + border: 0; + border-radius: 8px; + background: #111827; + color: #fff; + cursor: pointer; +} + +@media (max-width: 900px) { + .patents-content { + flex-direction: column; + } + + .patent-detail { + flex: 1; + width: 100%; + } +} 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 new file mode 100644 index 00000000..4d11c1a2 --- /dev/null +++ b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.ts @@ -0,0 +1,88 @@ +import { Component, input, signal } from '@angular/core'; +import { Router } from '@angular/router'; +import { PatentEntry } from '../../../api/model/patentEntry'; +import { KeywordPatentMatch } from '../../../api/model/patentsByKeywordsResponse'; +import { + formatPatentDate, + getPublicationStageLabel, +} from '../../patent-detail/patent-detail.utils'; + +type SourceFilter = 'all' | 'EPO' | 'USPTO'; + +@Component({ + selector: 'app-keywords-patents', + templateUrl: './keywords-patents.component.html', + styleUrl: './keywords-patents.component.scss', +}) +export class KeywordsPatentsComponent { + readonly matches = input([]); + readonly loading = input(false); + readonly error = input(false); + + activeFilter = signal('all'); + selectedPatent = signal(null); + selectedPage = signal(1); + readonly pageSize = 10; + + constructor(private readonly router: Router) {} + + filteredMatches(): KeywordPatentMatch[] { + const filter = this.activeFilter(); + const items = this.matches(); + if (filter === 'all') { + return items; + } + return items.filter((item) => item.patent.source === filter); + } + + pagedMatches(): KeywordPatentMatch[] { + const start = (this.selectedPage() - 1) * this.pageSize; + return this.filteredMatches().slice(start, start + this.pageSize); + } + + pageCount(): number { + return Math.max(1, Math.ceil(this.filteredMatches().length / this.pageSize)); + } + + hasPagination(): boolean { + return this.pageCount() > 1; + } + + setFilter(filter: SourceFilter): void { + this.activeFilter.set(filter); + this.selectedPage.set(1); + this.selectedPatent.set(null); + } + + setPage(page: number): void { + this.selectedPage.set(Math.min(Math.max(page, 1), this.pageCount())); + } + + selectPatent(patent: PatentEntry): void { + this.selectedPatent.set(patent); + } + + openDetail(): void { + const patent = this.selectedPatent(); + if (!patent) return; + void this.router.navigate(['/patent', patent.patent_id]); + } + + formatDate(date: string | null | undefined): string { + return formatPatentDate(date); + } + + getPublicationStageLabel(patent: PatentEntry): string | null { + return getPublicationStageLabel(patent); + } + + trackMatch(_index: number, item: KeywordPatentMatch): string { + const patent = item.patent; + return [ + patent.source, + patent.patent_id, + patent.publication_date ?? '', + patent.kind ?? patent.application_type ?? '', + ].join('|'); + } +} diff --git a/webapp/src/app/modules/keywords-search/keywords-search.component.html b/webapp/src/app/modules/keywords-search/keywords-search.component.html index e313d794..de1aa15d 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.html +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.html @@ -385,11 +385,11 @@ -
+
+
+ + @if (showPatents()) { + + + } } diff --git a/webapp/src/app/modules/keywords-search/keywords-search.component.scss b/webapp/src/app/modules/keywords-search/keywords-search.component.scss index 15e6e6c5..e5afef70 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.scss +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.scss @@ -419,16 +419,23 @@ mat-button-toggle-group { ============================================================ */ .search-container { display: flex; + flex-wrap: wrap; justify-content: center; + gap: 1rem; margin-top: 0.5rem; } -.search-btn { - min-width: 240px; +.action-btn { + min-width: 200px; align-self: center; min-height: $touch-target; } +.patents-btn { + background: #0f766e !important; + color: #fff !important; +} + @media (max-width: $phone) { .search-container { position: sticky; @@ -439,7 +446,7 @@ mat-button-toggle-group { box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.08); } - .search-btn { + .action-btn { width: 100%; } } @@ -465,7 +472,7 @@ mat-button-toggle-group { width: 100%; justify-content: center; } - .search-btn { + .action-btn { width: 100%; } } diff --git a/webapp/src/app/modules/keywords-search/keywords-search.component.ts b/webapp/src/app/modules/keywords-search/keywords-search.component.ts index a4442326..fbf9e4ef 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.ts +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.ts @@ -45,6 +45,12 @@ import { } from '../../resolvers/utils/topic-legend'; import { MatTooltipModule } from '@angular/material/tooltip'; import { A11yModule } from '@angular/cdk/a11y'; +import { PatentsService } from '../../api/api/patents.service'; +import { + KeywordPatentMatch, + KeywordPatentSearchItem, +} from '../../api/model/patentsByKeywordsResponse'; +import { KeywordsPatentsComponent } from './keywords-patents/keywords-patents.component'; type InputMode = 'url' | 'text'; type KeywordCategory = 'broad' | 'coarse' | 'fine' | 'manual'; type KeywordView = 'llm' | 'topic'; @@ -70,6 +76,7 @@ type KeywordView = 'llm' | 'topic'; MatTooltipModule, A11yModule, NgTemplateOutlet, + KeywordsPatentsComponent, ], templateUrl: './keywords-search.component.html', styleUrl: './keywords-search.component.scss', @@ -81,6 +88,7 @@ export class KeywordsSearchComponent { private readonly destroyRef = inject(DestroyRef); private readonly websocketService = inject(KeywordWebSocketService); private readonly topicsService = inject(TopicsService); + private readonly patentsService = inject(PatentsService); readonly form = this.formBuilder.nonNullable.group({ selectedInputType: 'url' as InputMode, @@ -115,6 +123,11 @@ export class KeywordsSearchComponent { readonly loadingNewKeyword = signal(false); readonly extractionSource = signal(null); readonly showVisualization = signal(false); + readonly showPatents = signal(false); + readonly patentMatches = signal([]); + readonly loadingPatents = signal(false); + readonly patentsError = signal(false); + readonly patentsLoaded = signal(false); readonly keywordsExist = computed( () => @@ -234,6 +247,10 @@ export class KeywordsSearchComponent { this.broadKeywordEntries.set([]); this.coarseKeywordEntries.set([]); this.fineKeywordEntries.set([]); + this.patentMatches.set([]); + this.patentsLoaded.set(false); + this.patentsError.set(false); + this.showPatents.set(false); this.websocketService.close(); this.isExtracting.set(false); this.loadingNewKeyword.set(false); @@ -449,6 +466,10 @@ export class KeywordsSearchComponent { this.manualKeywordEntries.set([]); this.sourceContent.set(''); this.sourceUrl.set(null); + this.patentMatches.set([]); + this.patentsLoaded.set(false); + this.patentsError.set(false); + this.showPatents.set(false); // Keep only selected keywords that are in the manual list const manualSet = new Set(this.getKeywordLabels(this.manualKeywords())); @@ -553,21 +574,20 @@ export class KeywordsSearchComponent { search(): void { this.showVisualization.set(false); - const payload = { - extractedKeywords: this.getSelectedExtractedKeywordEntries(), - manualKeywords: this.getSelectedManualKeywordEntries(), - keywords: this.selectedKeywords(), - }; - - console.log('searching for keywords:', payload); - // e.g. navigate to search results page with the full payload in navigation state - // this.router.navigate(['/search'], { state: payload }); + this.showPatents.set(false); } visualize(): void { + this.showPatents.set(false); this.showVisualization.set(true); } + loadPatentsForSelection(): void { + this.showVisualization.set(false); + this.showPatents.set(true); + this.loadMatchingPatents(); + } + // --- Helpers -------------------------------------------------------------- private applyExtractedKeywords(keywords: ExtractedKeywords): void { @@ -993,4 +1013,50 @@ export class KeywordsSearchComponent { return 50; // fallback for unknown steps } } + + private loadMatchingPatents(): void { + const entries = [ + ...this.getSelectedExtractedKeywordEntries(), + ...this.getSelectedManualKeywordEntries(), + ]; + const keywords = this.buildPatentSearchItems(entries); + if (keywords.length === 0) { + this.patentMatches.set([]); + this.patentsLoaded.set(true); + return; + } + + this.loadingPatents.set(true); + this.patentsError.set(false); + + this.patentsService.getPatentsByKeywords({ keywords }).subscribe({ + next: (response) => { + this.patentMatches.set(response.patents ?? []); + this.patentsLoaded.set(true); + this.loadingPatents.set(false); + }, + error: (error) => { + console.error('Patent search failed:', error); + this.patentMatches.set([]); + this.patentsLoaded.set(true); + this.patentsError.set(true); + this.loadingPatents.set(false); + }, + }); + } + + private buildPatentSearchItems( + entries: KeywordEntryWithTopic[], + ): KeywordPatentSearchItem[] { + return entries + .map((entry) => ({ + keyword: entry.llm_keyword.keyword, + topic_id: entry.topic_mapping?.topic?.id ?? null, + topic_display_name: entry.topic_mapping?.topic?.display_name ?? null, + subfield_name: entry.topic_mapping?.topic?.subfield?.display_name ?? null, + field_name: entry.topic_mapping?.topic?.field?.display_name ?? null, + relevance_score: entry.llm_keyword.relevance_score ?? 1, + })) + .filter((item) => item.keyword.trim().length > 0); + } }