From 4c8255e600332d74f392caec77553ce3812e9b8c Mon Sep 17 00:00:00 2001 From: Khalti Date: Tue, 25 Aug 2026 10:05:58 +0200 Subject: [PATCH] feat(patents): keyword search matches title/abstract via Elasticsearch highlighting, plus server-side pagination and colored keyword matches like DFG projects --- service/src/main/inse/patents/common/model.py | 3 + .../src/main/inse/patents/common/parsing.py | 4 + .../src/main/inse/patents/keywords/logic.py | 298 +++++++++++------- .../src/main/inse/patents/keywords/model.py | 32 ++ .../inse/patents/keywords/search_queries.py | 88 ++++++ .../main/inse/patents/keywords/test_logic.py | 207 +++++------- service/uv.lock | 88 ++++++ .../app/api/model/keywordPatentHighlight.ts | 18 ++ .../src/app/api/model/keywordPatentMatch.ts | 2 + webapp/src/app/api/model/patentEntry.ts | 3 + .../app/api/model/patentsByKeywordsRequest.ts | 22 +- .../api/model/patentsByKeywordsResponse.ts | 12 + .../keywords-patents.component.html | 12 +- .../keywords-patents.component.ts | 156 ++++----- .../keywords-search.component.ts | 3 - .../keywords-search/patent-search.utils.ts | 57 ---- .../patents-results.component.html | 10 +- .../patents-results.component.ts | 146 ++++++--- .../patent-table/patent-table.component.html | 53 ++++ .../ui/patent-table/patent-table.component.ts | 109 ++++++- 20 files changed, 861 insertions(+), 462 deletions(-) create mode 100644 webapp/src/app/api/model/keywordPatentHighlight.ts diff --git a/service/src/main/inse/patents/common/model.py b/service/src/main/inse/patents/common/model.py index e9e9bb26..7dea37c2 100644 --- a/service/src/main/inse/patents/common/model.py +++ b/service/src/main/inse/patents/common/model.py @@ -23,7 +23,10 @@ class PatentEntry(BaseModel): patent_id: str source: str title: str | None = None + title_de: str | None = None + title_en: str | None = None abstract: str | None = None + abstract_lang: str | None = None publication_date: str | None = None publication_year: str | None = None application_number: str | None = None diff --git a/service/src/main/inse/patents/common/parsing.py b/service/src/main/inse/patents/common/parsing.py index 314ca6fa..6489e9ab 100644 --- a/service/src/main/inse/patents/common/parsing.py +++ b/service/src/main/inse/patents/common/parsing.py @@ -35,7 +35,10 @@ def parse_epo_hits(data: dict) -> list[model.PatentEntry]: patent_id=f"EP{src.get('doc_number', hit.get('_id', ''))}", source="EPO", title=src.get("title_en") or src.get("title_de"), + title_de=src.get("title_de"), + title_en=src.get("title_en"), abstract=src.get("abstract"), + abstract_lang=src.get("abstract_lang"), publication_date=str(src.get("date_publication")) if src.get("date_publication") else None, publication_year=str(src.get("date_publication_year")) if src.get("date_publication_year") else None, application_number=src.get("application_number"), @@ -63,6 +66,7 @@ def parse_uspto_hits(data: dict) -> list[model.PatentEntry]: source="USPTO", title=src.get("title"), abstract=src.get("abstract"), + abstract_lang=src.get("lang"), publication_date=str(src.get("publication_date")) if src.get("publication_date") else None, publication_year=str(src.get("publication_year")) if src.get("publication_year") else None, application_number=src.get("application_number"), diff --git a/service/src/main/inse/patents/keywords/logic.py b/service/src/main/inse/patents/keywords/logic.py index 138602cb..eeddfcff 100644 --- a/service/src/main/inse/patents/keywords/logic.py +++ b/service/src/main/inse/patents/keywords/logic.py @@ -31,22 +31,19 @@ from inse.patents.ipc_lookup import ( ) from inse.patents.ipc_search_client import IpcSearchClient from inse.patents.keywords.model import ( - KeywordPatentMappingStatus, + KeywordPatentHighlight, KeywordPatentMatch, KeywordPatentSearchDiagnostics, KeywordPatentSearchItem, PatentsByKeywordsRequest, PatentsByKeywordsResponse, ) -from inse.patents.keywords.reverse_lookup import ( - IpcCodeMatch, - KeywordIpcReverseLookup, -) +from inse.patents.keywords.reverse_lookup import IpcCodeMatch from inse.patents.keywords.reverse_lookup import ( _topic_group_key as _match_topic_group_key, ) from inse.patents.keywords.search_queries import ( - IpcPatentSearchQueries, + TextPatentSearchQueries, _search_terms_for_symbol, ) from inse.patents.patents_openalex_keywords.ipc_entries import ( @@ -59,7 +56,7 @@ from inse.patents.patents_openalex_keywords.resolver import ( logger = logging.getLogger(__name__) -_MAX_PATENTS = 100 +_MAX_PATENTS = 2000 # Raw mapping candidates before cluster selection (avoid early truncation bias). _MAX_IPC_LOOKUP_CANDIDATES = 200 _MAX_IPC_CODES_PER_KEYWORD = 3 @@ -874,12 +871,16 @@ def _score_patent( ) -async def _fetch_patents_for_queries( +async def _fetch_patents_with_highlights( client: BasePatentSearchClient, epo_query: dict, uspto_query: dict, -) -> list[model.PatentEntry] | None: - """Run EPO+USPTO search. Returns None on configuration/transport failure.""" +) -> tuple[list[model.PatentEntry], dict[str, dict], dict[str, float]] | None: + """Run EPO+USPTO search, keeping each hit's ES highlight and _score + alongside the parsed patent (keyed the same way deduplicate_patents + groups patents), so the caller can trust Elasticsearch's own match + decision instead of re-deriving it in Python. + """ try: epo_data, uspto_data = await asyncio.gather( client.search_epo(epo_query), @@ -892,7 +893,19 @@ async def _fetch_patents_for_queries( logger.warning("Patent search failed: %s", exc) return None - return deduplicate_patents(parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data)) + epo_patents = parse_epo_hits(epo_data) + uspto_patents = parse_uspto_hits(uspto_data) + + highlights: dict[str, dict] = {} + es_scores: dict[str, float] = {} + for patents, data in ((epo_patents, epo_data), (uspto_patents, uspto_data)): + for patent, hit in zip(patents, data.get("hits", {}).get("hits", [])): + key = patent_map_key(patent) + highlights[key] = hit.get("highlight", {}) + es_scores[key] = hit.get("_score") or 0.0 + + deduped = deduplicate_patents(epo_patents + uspto_patents) + return deduped, highlights, es_scores def _cluster_selection_dicts( @@ -926,6 +939,27 @@ def _empty_diagnostics( ) +def _sort_key_for(sort_by: str | None): + if sort_by == "title": + return lambda item: ( + item.patent.title + or item.patent.title_en + or item.patent.title_de + or "" + ).casefold() + if sort_by == "source": + return lambda item: item.patent.source or "" + if sort_by == "publication_year": + return lambda item: item.patent.publication_date or str( + item.patent.publication_year or "" + ) + return lambda item: ( + item.match_score, + item.patent.publication_date or "", + item.patent.patent_id, + ) + + def _finalize_scored_patents( scored: list[KeywordPatentMatch], *, @@ -935,18 +969,28 @@ def _finalize_scored_patents( filtered_by_min_score: int, passed_relevance_gate: int, search_path: str, + source: str | None = None, + sort_by: str | None = None, + sort_direction: str = "desc", + page: int = 0, + size: int = 10, ipc_cluster_selections: list[dict] | None = None, -) -> tuple[list[KeywordPatentMatch], KeywordPatentSearchDiagnostics]: +) -> tuple[list[KeywordPatentMatch], int, int, int, KeywordPatentSearchDiagnostics]: scored_before_cap = len(scored) - scored.sort( - key=lambda item: ( - item.match_score, - item.patent.publication_date or "", - item.patent.patent_id, - ), - reverse=True, + epo_count = sum(1 for item in scored if item.patent.source == "EPO") + uspto_count = sum(1 for item in scored if item.patent.source == "USPTO") + + filtered = ( + [item for item in scored if item.patent.source == source] + if source + else scored ) - returned = scored[:_MAX_PATENTS] + filtered.sort(key=_sort_key_for(sort_by), reverse=sort_direction != "asc") + + total_count = len(filtered) + start = max(page, 0) * max(size, 1) + page_items = filtered[start : start + max(size, 1)] + diagnostics = KeywordPatentSearchDiagnostics( search_path=search_path, es_query_size_per_index=_MAX_PATENTS, @@ -956,12 +1000,12 @@ def _finalize_scored_patents( filtered_by_min_score=filtered_by_min_score, passed_relevance_gate=passed_relevance_gate, scored_before_cap=scored_before_cap, - returned=len(returned), + returned=len(page_items), max_patents_cap=_MAX_PATENTS, hit_return_cap=scored_before_cap >= _MAX_PATENTS, ipc_cluster_selections=list(ipc_cluster_selections or []), ) - return returned, diagnostics + return page_items, total_count, epo_count, uspto_count, diagnostics async def _score_patents_with_ipc( @@ -1054,26 +1098,95 @@ async def _score_patents_with_ipc( } +_EM_TAG_RE = re.compile(r"(.*?)", re.IGNORECASE) + + +def _extract_highlight_terms(fragments: list[str]) -> list[str]: + """Distinct matched terms out of Elasticsearch highlight fragments + (terms wrapped in ...), like the frontend's extractHighlightTerms. + """ + terms: list[str] = [] + seen: set[str] = set() + for fragment in fragments: + for match in _EM_TAG_RE.finditer(fragment): + term = match.group(1).strip() + key = term.casefold() + if term and key not in seen: + seen.add(key) + terms.append(term) + return terms + + +def _build_matches_from_highlights( + patents: list[model.PatentEntry], + highlights: dict[str, dict], + es_scores: dict[str, float], +) -> list[KeywordPatentMatch]: + """Build matches trusting Elasticsearch's own phrase-prefix decision — + every patent returned by the query already satisfied the OR-search, like + DFG projects. matched_keywords/highlight come from ES's own highlight + fragments (the real matched text span), not a re-derived substring check, + so a short/acronym keyword that only matched as part of a longer word + (e.g. "LRO" inside "LROC") is shown as what actually matched ("LROC"), + never as an invisible, unhighlightable "match". + """ + matches: list[KeywordPatentMatch] = [] + for patent in patents: + key = patent_map_key(patent) + raw_highlight = highlights.get(key, {}) + title_de = raw_highlight.get("title_de") or [] + title_en = (raw_highlight.get("title_en") or []) or ( + raw_highlight.get("title") or [] + ) + abstract = raw_highlight.get("abstract") or [] + highlight = KeywordPatentHighlight( + title_de=title_de, title_en=title_en, abstract=abstract + ) + + matched_keywords = list( + dict.fromkeys( + _extract_highlight_terms(title_de) + + _extract_highlight_terms(title_en) + + _extract_highlight_terms(abstract) + ) + ) + score = round(es_scores.get(key, 0.0), 4) + matches.append( + KeywordPatentMatch( + patent=patent, + match_score=score, + ipc_score=0.0, + topic_score=0.0, + text_score=score, + matched_keywords=matched_keywords, + matched_ipc_symbols=[], + highlight=highlight, + text_retrieval=True, + topic_match_kind=None, + ) + ) + return matches + + async def get_patents_by_keywords( request: PatentsByKeywordsRequest, *, - reverse_lookup: KeywordIpcReverseLookup | None = None, search_client: BasePatentSearchClient | None = None, ipc_client: IpcSearchClient | None = None, - mapping_resolver: PatentOpenAlexMappingResolver | None = None, ) -> PatentsByKeywordsResponse: - lookup = reverse_lookup or KeywordIpcReverseLookup() + """Find patents by matching keywords against patent titles/abstracts. + + Mirrors the DFG project search: each keyword is OR-matched (phrase-prefix) + against title/abstract fields, trusting Elasticsearch's own match and + highlight fragments — no IPC/CPC classification lookup involved. + """ client = search_client or BasePatentSearchClient() ipc_search = ipc_client or IpcSearchClient() - resolver = mapping_resolver or PatentOpenAlexMappingResolver() - queries = IpcPatentSearchQueries() + queries = TextPatentSearchQueries() - search_keywords = _filter_keywords_for_patent_search(request.keywords) - if not search_keywords: - logger.info( - "Keyword patent search: no searchable keywords in %s", - [item.keyword for item in request.keywords], - ) + keywords = [item.keyword.strip() for item in request.keywords if item.keyword.strip()] + if not keywords: + logger.info("Keyword patent search: no keywords in request") return PatentsByKeywordsResponse( patent_count=0, patents=[], @@ -1081,107 +1194,60 @@ async def get_patents_by_keywords( diagnostics=_empty_diagnostics(search_path="none"), ) - logger.info( - "Keyword patent search: using keywords=%s (from %d requested)", - [ - { - "keyword": item.keyword, - "level": item.keyword_level, - "relevance_score": item.relevance_score, - "field_name": item.field_name, - } - for item in search_keywords - ], - len(request.keywords), - ) - keyword_topic_ids, keyword_subfield_names, keyword_soft_field_names = ( - _keyword_overlap_criteria(search_keywords) - ) + logger.info("Keyword patent search (text): keywords=%s", keywords) - raw_ipc_matches = await lookup.lookup_ipc_codes( - search_keywords, - max_codes=_MAX_IPC_LOOKUP_CANDIDATES, - ) - had_usable_mapping = bool(_usable_ipc_matches(raw_ipc_matches)) - ipc_matches, cluster_selections = select_ipc_matches_by_cluster_mass(raw_ipc_matches) - cluster_dicts = _cluster_selection_dicts(cluster_selections) - logger.info( - "Keyword patent search: search_keywords=%s selected_ipc=%s", - [item.keyword for item in search_keywords], - cluster_dicts, - ) - symbols = _patent_search_terms(ipc_matches) - if not symbols: - mapping_status: KeywordPatentMappingStatus = ( - "uncertain" if had_usable_mapping else "no_mapping" - ) - logger.info( - "Keyword patent search: no IPC search terms for keywords %s " - "(mapping_status=%s)", - [item.keyword for item in search_keywords], - mapping_status, - ) - return PatentsByKeywordsResponse( - patent_count=0, - patents=[], - mapping_status=mapping_status, - diagnostics=_empty_diagnostics( - search_path="none", - ipc_cluster_selections=cluster_dicts, - ), - ) - - text_search_terms = _text_search_terms(search_keywords) - logger.info("Keyword patent search: patent_search_terms=%s", symbols) - - raw_patents = await _fetch_patents_for_queries( + raw_result = await _fetch_patents_with_highlights( client, - queries.epo_query_by_ipc_symbols(symbols, size=_MAX_PATENTS), - queries.uspto_query_by_ipc_symbols(symbols, size=_MAX_PATENTS), + queries.epo_query_by_keywords(keywords, size=_MAX_PATENTS), + queries.uspto_query_by_keywords(keywords, size=_MAX_PATENTS), ) - if raw_patents is None: + if raw_result is None: return PatentsByKeywordsResponse( patent_count=0, patents=[], mapping_status="search_error", - diagnostics=_empty_diagnostics( - search_path="ipc", - ipc_cluster_selections=cluster_dicts, - ), + diagnostics=_empty_diagnostics(search_path="text"), ) - logger.info("Keyword patent search: raw_patents=%d", len(raw_patents)) - scored, filter_counts = await _score_patents_with_ipc( - raw_patents=raw_patents, - ipc_matches=ipc_matches, - text_search_terms=text_search_terms, - keyword_topic_ids=keyword_topic_ids, - keyword_subfield_names=keyword_subfield_names, - keyword_soft_field_names=keyword_soft_field_names, - resolver=resolver, - ) - scored, diagnostics = _finalize_scored_patents( - scored, - raw_count=len(raw_patents), - filtered_by_ipc=filter_counts["filtered_by_ipc"], - filtered_by_relevance_gate=filter_counts["filtered_by_relevance_gate"], - filtered_by_min_score=filter_counts["filtered_by_min_score"], - passed_relevance_gate=filter_counts["passed_relevance_gate"], - search_path="ipc", - ipc_cluster_selections=cluster_dicts, + raw_patents, highlights, es_scores = raw_result + logger.info("Keyword patent search (text): raw_patents=%d", len(raw_patents)) + all_scored = _build_matches_from_highlights(raw_patents, highlights, es_scores) + page_items, total_count, epo_count, uspto_count, diagnostics = ( + _finalize_scored_patents( + all_scored, + raw_count=len(raw_patents), + filtered_by_ipc=0, + filtered_by_relevance_gate=0, + filtered_by_min_score=0, + passed_relevance_gate=len(all_scored), + search_path="text", + source=request.source, + sort_by=request.sort_by, + sort_direction=request.sort_direction, + page=request.page, + size=request.size, + ) ) - if scored: - await enrich_patents_classifications([item.patent for item in scored], ipc_search) + if page_items: + await enrich_patents_classifications( + [item.patent for item in page_items], ipc_search + ) return PatentsByKeywordsResponse( - patent_count=len(scored), - patents=scored, + patent_count=len(page_items), + total_count=total_count, + epo_count=epo_count, + uspto_count=uspto_count, + patents=page_items, mapping_status="mapped", diagnostics=diagnostics, ) return PatentsByKeywordsResponse( patent_count=0, + total_count=total_count, + epo_count=epo_count, + uspto_count=uspto_count, patents=[], mapping_status="no_patents_found", diagnostics=diagnostics, diff --git a/service/src/main/inse/patents/keywords/model.py b/service/src/main/inse/patents/keywords/model.py index 978eb46b..2d8bb40f 100644 --- a/service/src/main/inse/patents/keywords/model.py +++ b/service/src/main/inse/patents/keywords/model.py @@ -53,6 +53,20 @@ class PatentsByKeywordsRequest(BaseModel): min_length=1, description="Keywords to match against patents_openalex_keywords.", ) + page: int = Field(default=0, ge=0, description="Zero-based page index.") + size: int = Field(default=10, ge=1, le=100, description="Page size.") + source: str | None = Field( + default=None, + description="Filter to a single source: EPO or USPTO. Omit for both.", + ) + sort_by: str | None = Field( + default=None, + description="title | publication_year | source. Omit to sort by match quality.", + ) + sort_direction: str = Field( + default="desc", + description="asc | desc", + ) class KeywordEvidence(BaseModel): @@ -73,6 +87,14 @@ class KeywordEvidence(BaseModel): ) +class KeywordPatentHighlight(BaseModel): + """Elasticsearch highlight fragments (terms wrapped in ...).""" + + title_de: list[str] = Field(default_factory=list) + title_en: list[str] = Field(default_factory=list) + abstract: list[str] = Field(default_factory=list) + + class KeywordPatentMatch(BaseModel): patent: PatentEntry match_score: float = Field(description="Combined match quality score.") @@ -86,6 +108,10 @@ class KeywordPatentMatch(BaseModel): text_score: float = Field(description="Title/abstract keyword overlap score.") matched_keywords: list[str] = Field(default_factory=list) matched_ipc_symbols: list[str] = Field(default_factory=list) + highlight: KeywordPatentHighlight | None = Field( + default=None, + description="Elasticsearch highlight fragments for title/abstract, like DFG projects.", + ) text_retrieval: bool = Field( default=False, description=( @@ -124,6 +150,12 @@ class KeywordPatentSearchDiagnostics(BaseModel): class PatentsByKeywordsResponse(BaseModel): patent_count: int + total_count: int = Field( + default=0, + description="Total matches across all pages (before page/size slicing).", + ) + epo_count: int = Field(default=0, description="Total EPO matches, unfiltered by source.") + uspto_count: int = Field(default=0, description="Total USPTO matches, unfiltered by source.") patents: list[KeywordPatentMatch] mapping_status: KeywordPatentMappingStatus = Field( description=( diff --git a/service/src/main/inse/patents/keywords/search_queries.py b/service/src/main/inse/patents/keywords/search_queries.py index 780e3903..460f1798 100644 --- a/service/src/main/inse/patents/keywords/search_queries.py +++ b/service/src/main/inse/patents/keywords/search_queries.py @@ -21,6 +21,7 @@ _PATENT_SOURCE_FIELDS = [ "title_en", "title_de", "abstract", + "abstract_lang", "inventors_name", "applicants_name", "ipc", @@ -39,6 +40,7 @@ _USPTO_SOURCE_FIELDS = [ "status", "title", "abstract", + "lang", "inventors_names", "assignees_orgs", "ipcr", @@ -222,3 +224,89 @@ class IpcPatentSearchQueries: size: int = DEFAULT_SEARCH_SIZE, ) -> dict[str, Any]: return self.uspto_query_by_ipc_terms(_merge_term_boosts(symbols), size=size) + + +def _keyword_text_should_clauses( + keywords: list[str], + fields: list[str], +) -> list[dict[str, Any]]: + return [ + { + "multi_match": { + "query": keyword, + "fields": fields, + "type": "phrase_prefix", + "max_expansions": 100, + } + } + for keyword in keywords + if keyword.strip() + ] + + +def _highlight_config( + query: dict[str, Any], + fields: list[str], +) -> dict[str, Any]: + return { + "fragment_size": 200, + "number_of_fragments": 0, + "pre_tags": [""], + "post_tags": [""], + "require_field_match": True, + "fields": {field: {"highlight_query": query} for field in fields}, + } + + +class TextPatentSearchQueries: + """Plain title/abstract keyword search, mirroring the DFG project search.""" + + def epo_query_by_keywords( + self, + keywords: list[str], + size: int = DEFAULT_SEARCH_SIZE, + ) -> dict[str, Any]: + fields = ["title_de^4", "title_en^4", "abstract^2"] + should = _keyword_text_should_clauses(keywords, fields) + query: dict[str, Any] = ( + {"match_none": {}} + if not should + else {"bool": {"should": should, "minimum_should_match": 1}} + ) + return { + "size": size, + "track_total_hits": True, + "sort": [ + {"_score": {"order": "desc"}}, + {"date_publication": {"order": "desc", "missing": "_last"}}, + ], + "_source": _PATENT_SOURCE_FIELDS, + "query": query, + "highlight": _highlight_config( + query, ["title_de", "title_en", "abstract"] + ), + } + + def uspto_query_by_keywords( + self, + keywords: list[str], + size: int = DEFAULT_SEARCH_SIZE, + ) -> dict[str, Any]: + fields = ["title^4", "abstract^2"] + should = _keyword_text_should_clauses(keywords, fields) + query: dict[str, Any] = ( + {"match_none": {}} + if not should + else {"bool": {"should": should, "minimum_should_match": 1}} + ) + return { + "size": size, + "track_total_hits": True, + "sort": [ + {"_score": {"order": "desc"}}, + {"publication_date": {"order": "desc", "missing": "_last"}}, + ], + "_source": _USPTO_SOURCE_FIELDS, + "query": query, + "highlight": _highlight_config(query, ["title", "abstract"]), + } diff --git a/service/src/main/inse/patents/keywords/test_logic.py b/service/src/main/inse/patents/keywords/test_logic.py index 5ac08818..355c2d92 100644 --- a/service/src/main/inse/patents/keywords/test_logic.py +++ b/service/src/main/inse/patents/keywords/test_logic.py @@ -40,6 +40,7 @@ from inse.patents.keywords.reverse_lookup import ( from inse.patents.keywords.model import KeywordPatentSearchItem, PatentsByKeywordsRequest from inse.patents.keywords.search_queries import ( IpcPatentSearchQueries, + TextPatentSearchQueries, _search_terms_for_symbol, _weighted_search_terms_for_symbol, ) @@ -716,14 +717,32 @@ def test_score_patent_rejects_subclass_only_without_topic_or_text() -> None: assert result is None -def test_get_patents_by_keywords_uses_symbol_queries() -> None: - queries = IpcPatentSearchQueries() +def test_get_patents_by_keywords_matches_title_and_abstract() -> None: + """Retrieval/scoring trusts Elasticsearch's own phrase-prefix match and + highlight fragments, like DFG projects — no Python-side re-verification. + """ + queries = TextPatentSearchQueries() captured: list[str] = [] + epo_hit = { + "_score": 3.5, + "_source": { + "doc_number": "1", + "country": "EP", + "kind": "A1", + "title_de": "Verfahren zur organischen Chemie", + "abstract": "Ein neues Syntheseverfahren.", + }, + "highlight": { + "title_de": ["Verfahren zur organischen Chemie"], + }, + } + async def fake_search_epo(query): captured.append("epo") assert "query" in query - return {"hits": {"hits": []}} + assert "highlight" in query + return {"hits": {"hits": [epo_hit]}} async def fake_search_uspto(query): captured.append("uspto") @@ -732,56 +751,77 @@ def test_get_patents_by_keywords_uses_symbol_queries() -> None: request = PatentsByKeywordsRequest( keywords=[ KeywordPatentSearchItem( - keyword="Organische Chemie", + keyword="organischen Chemie", keyword_level="coarse", - topic_id="https://openalex.org/T13859", - field_name="Chemistry", relevance_score=1.0, ) ] ) with patch( - "inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes", - new=AsyncMock( - return_value=[ - IpcCodeMatch( - "subgroup", - "C07C243/08", - 0.8989, - "Organische Chemie", - "keyword", - ) - ] - ), - ), patch( "inse.patents.keywords.logic.BasePatentSearchClient.search_epo", new=AsyncMock(side_effect=fake_search_epo), ), patch( "inse.patents.keywords.logic.BasePatentSearchClient.search_uspto", new=AsyncMock(side_effect=fake_search_uspto), - ), patch( - "inse.patents.keywords.logic.PatentOpenAlexMappingResolver.resolve_topics_for_patents", - new=AsyncMock(return_value={}), ), patch( "inse.patents.keywords.logic.enrich_patents_classifications", new=AsyncMock(), ), patch.object( - IpcPatentSearchQueries, - "epo_query_by_ipc_symbols", - wraps=queries.epo_query_by_ipc_symbols, - ) as epo_symbols, patch.object( - IpcPatentSearchQueries, - "uspto_query_by_ipc_symbols", - wraps=queries.uspto_query_by_ipc_symbols, - ) as uspto_symbols: - asyncio.run(get_patents_by_keywords(request)) + TextPatentSearchQueries, + "epo_query_by_keywords", + wraps=queries.epo_query_by_keywords, + ) as epo_keywords, patch.object( + TextPatentSearchQueries, + "uspto_query_by_keywords", + wraps=queries.uspto_query_by_keywords, + ) as uspto_keywords: + response = asyncio.run(get_patents_by_keywords(request)) - epo_symbols.assert_called_once() - uspto_symbols.assert_called_once() - assert epo_symbols.call_args.args[0][0] == "C07C243/08" - assert "C07C" in epo_symbols.call_args.args[0] + epo_keywords.assert_called_once() + uspto_keywords.assert_called_once() + assert epo_keywords.call_args.args[0] == ["organischen Chemie"] assert captured == ["epo", "uspto"] + assert response.mapping_status == "mapped" + assert response.patent_count == 1 + assert response.patents[0].matched_keywords == ["organischen", "Chemie"] + assert response.patents[0].highlight.title_de == [ + "Verfahren zur organischen Chemie" + ] + assert response.patents[0].match_score == 3.5 + assert response.patents[0].ipc_score == 0.0 + + +def test_get_patents_by_keywords_no_keywords_returns_no_mapping() -> None: + request = PatentsByKeywordsRequest( + keywords=[KeywordPatentSearchItem(keyword=" ", relevance_score=1.0)] + ) + + response = asyncio.run(get_patents_by_keywords(request)) + + assert response.mapping_status == "no_mapping" + assert response.patent_count == 0 + + +def test_get_patents_by_keywords_no_hits_returns_no_patents_found() -> None: + """No search-path re-verification happens anymore — Elasticsearch's own + phrase-prefix query is trusted, so an empty hit list is the only way to + end up with no_patents_found.""" + request = PatentsByKeywordsRequest( + keywords=[KeywordPatentSearchItem(keyword="Quantencomputer", relevance_score=1.0)] + ) + + with patch( + "inse.patents.keywords.logic.BasePatentSearchClient.search_epo", + new=AsyncMock(return_value={"hits": {"hits": []}}), + ), patch( + "inse.patents.keywords.logic.BasePatentSearchClient.search_uspto", + new=AsyncMock(return_value={"hits": {"hits": []}}), + ): + response = asyncio.run(get_patents_by_keywords(request)) + + assert response.mapping_status == "no_patents_found" + assert response.patent_count == 0 def test_text_search_terms_include_topic_metadata() -> None: @@ -865,28 +905,12 @@ def test_technical_search_failure_returns_search_error_not_no_patents_found() -> KeywordPatentSearchItem( keyword="organische Chemie", keyword_level="coarse", - topic_id="https://openalex.org/TORG", - topic_display_name="Organic Chemistry", - field_name="Chemistry", relevance_score=1.0, ) ] ) - ipc_matches = [ - IpcCodeMatch( - "subgroup", - "C07C243/08", - 0.90, - "organische Chemie", - "topic", - "TORG", - ) - ] with patch( - "inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes", - new=AsyncMock(return_value=ipc_matches), - ), patch( "inse.patents.keywords.logic.BasePatentSearchClient.search_epo", new=AsyncMock(side_effect=httpx.HTTPError("boom")), ), patch( @@ -899,87 +923,6 @@ def test_technical_search_failure_returns_search_error_not_no_patents_found() -> assert response.patent_count == 0 -def test_no_ipc_search_terms_returns_without_text_fallback() -> None: - """Without usable IPC symbols the search abstains — no title/abstract path.""" - request = PatentsByKeywordsRequest( - keywords=[ - KeywordPatentSearchItem( - keyword="organische Chemie", - keyword_level="coarse", - topic_id="https://openalex.org/TORG", - topic_display_name="Organic Chemistry", - field_name="Chemistry", - relevance_score=1.0, - ) - ] - ) - search_epo = AsyncMock(return_value={"hits": {"hits": []}}) - search_uspto = AsyncMock(return_value={"hits": {"hits": []}}) - - with patch( - "inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes", - new=AsyncMock(return_value=[]), - ), patch( - "inse.patents.keywords.logic.BasePatentSearchClient.search_epo", - new=search_epo, - ), patch( - "inse.patents.keywords.logic.BasePatentSearchClient.search_uspto", - new=search_uspto, - ): - response = asyncio.run(get_patents_by_keywords(request)) - - assert response.mapping_status == "no_mapping" - assert response.patent_count == 0 - assert response.patents == [] - search_epo.assert_not_called() - search_uspto.assert_not_called() - - -def test_uncertain_ipc_cluster_abstention_returns_without_text_fallback() -> None: - """Fragmented IPC mapping abstains without falling back to text retrieval.""" - fragmented = [ - IpcCodeMatch( - "subgroup", - f"A{index:02d}B1/00", - 0.70, - "organische Chemie", - "topic", - "TORG", - ) - for index in range(1, 16) - ] - request = PatentsByKeywordsRequest( - keywords=[ - KeywordPatentSearchItem( - keyword="organische Chemie", - keyword_level="coarse", - topic_id="https://openalex.org/TORG", - topic_display_name="Organic Chemistry", - field_name="Chemistry", - relevance_score=1.0, - ) - ] - ) - search_epo = AsyncMock(return_value={"hits": {"hits": []}}) - - with patch( - "inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes", - new=AsyncMock(return_value=fragmented), - ), patch( - "inse.patents.keywords.logic.BasePatentSearchClient.search_epo", - new=search_epo, - ), patch( - "inse.patents.keywords.logic.BasePatentSearchClient.search_uspto", - new=AsyncMock(return_value={"hits": {"hits": []}}), - ): - response = asyncio.run(get_patents_by_keywords(request)) - - assert response.mapping_status == "uncertain" - assert response.patent_count == 0 - assert response.patents == [] - search_epo.assert_not_called() - - def test_json_lookup_returns_empty_without_mapping(monkeypatch) -> None: clear_reverse_lookup_caches() monkeypatch.setattr( diff --git a/service/uv.lock b/service/uv.lock index 2305fae5..3992b104 100644 --- a/service/uv.lock +++ b/service/uv.lock @@ -712,6 +712,53 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/df/b2/87e62e8c3e2f4b32e5fe99e0b86d576da1312593b39f47d8ceef365e95ed/packaging-26.2-py3-none-any.whl", hash = "sha256:5fc45236b9446107ff2415ce77c807cee2862cb6fac22b8a73826d0693b0980e", size = 100195, upload-time = "2026-04-24T20:15:22.081Z" }, ] +[[package]] +name = "pandas" +version = "2.3.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, + { name = "python-dateutil" }, + { name = "pytz" }, + { name = "tzdata" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/33/01/d40b85317f86cf08d853a4f495195c73815fdf205eef3993821720274518/pandas-2.3.3.tar.gz", hash = "sha256:e05e1af93b977f7eafa636d043f9f94c7ee3ac81af99c13508215942e64c993b", size = 4495223, upload-time = "2025-09-29T23:34:51.853Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9c/fb/231d89e8637c808b997d172b18e9d4a4bc7bf31296196c260526055d1ea0/pandas-2.3.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:6d21f6d74eb1725c2efaa71a2bfc661a0689579b58e9c0ca58a739ff0b002b53", size = 11597846, upload-time = "2025-09-29T23:19:48.856Z" }, + { url = "https://files.pythonhosted.org/packages/5c/bd/bf8064d9cfa214294356c2d6702b716d3cf3bb24be59287a6a21e24cae6b/pandas-2.3.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:3fd2f887589c7aa868e02632612ba39acb0b8948faf5cc58f0850e165bd46f35", size = 10729618, upload-time = "2025-09-29T23:39:08.659Z" }, + { url = "https://files.pythonhosted.org/packages/57/56/cf2dbe1a3f5271370669475ead12ce77c61726ffd19a35546e31aa8edf4e/pandas-2.3.3-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ecaf1e12bdc03c86ad4a7ea848d66c685cb6851d807a26aa245ca3d2017a1908", size = 11737212, upload-time = "2025-09-29T23:19:59.765Z" }, + { url = "https://files.pythonhosted.org/packages/e5/63/cd7d615331b328e287d8233ba9fdf191a9c2d11b6af0c7a59cfcec23de68/pandas-2.3.3-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b3d11d2fda7eb164ef27ffc14b4fcab16a80e1ce67e9f57e19ec0afaf715ba89", size = 12362693, upload-time = "2025-09-29T23:20:14.098Z" }, + { url = "https://files.pythonhosted.org/packages/a6/de/8b1895b107277d52f2b42d3a6806e69cfef0d5cf1d0ba343470b9d8e0a04/pandas-2.3.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:a68e15f780eddf2b07d242e17a04aa187a7ee12b40b930bfdd78070556550e98", size = 12771002, upload-time = "2025-09-29T23:20:26.76Z" }, + { url = "https://files.pythonhosted.org/packages/87/21/84072af3187a677c5893b170ba2c8fbe450a6ff911234916da889b698220/pandas-2.3.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:371a4ab48e950033bcf52b6527eccb564f52dc826c02afd9a1bc0ab731bba084", size = 13450971, upload-time = "2025-09-29T23:20:41.344Z" }, + { url = "https://files.pythonhosted.org/packages/86/41/585a168330ff063014880a80d744219dbf1dd7a1c706e75ab3425a987384/pandas-2.3.3-cp312-cp312-win_amd64.whl", hash = "sha256:a16dcec078a01eeef8ee61bf64074b4e524a2a3f4b3be9326420cabe59c4778b", size = 10992722, upload-time = "2025-09-29T23:20:54.139Z" }, + { url = "https://files.pythonhosted.org/packages/cd/4b/18b035ee18f97c1040d94debd8f2e737000ad70ccc8f5513f4eefad75f4b/pandas-2.3.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:56851a737e3470de7fa88e6131f41281ed440d29a9268dcbf0002da5ac366713", size = 11544671, upload-time = "2025-09-29T23:21:05.024Z" }, + { url = "https://files.pythonhosted.org/packages/31/94/72fac03573102779920099bcac1c3b05975c2cb5f01eac609faf34bed1ca/pandas-2.3.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:bdcd9d1167f4885211e401b3036c0c8d9e274eee67ea8d0758a256d60704cfe8", size = 10680807, upload-time = "2025-09-29T23:21:15.979Z" }, + { url = "https://files.pythonhosted.org/packages/16/87/9472cf4a487d848476865321de18cc8c920b8cab98453ab79dbbc98db63a/pandas-2.3.3-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e32e7cc9af0f1cc15548288a51a3b681cc2a219faa838e995f7dc53dbab1062d", size = 11709872, upload-time = "2025-09-29T23:21:27.165Z" }, + { url = "https://files.pythonhosted.org/packages/15/07/284f757f63f8a8d69ed4472bfd85122bd086e637bf4ed09de572d575a693/pandas-2.3.3-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:318d77e0e42a628c04dc56bcef4b40de67918f7041c2b061af1da41dcff670ac", size = 12306371, upload-time = "2025-09-29T23:21:40.532Z" }, + { url = "https://files.pythonhosted.org/packages/33/81/a3afc88fca4aa925804a27d2676d22dcd2031c2ebe08aabd0ae55b9ff282/pandas-2.3.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:4e0a175408804d566144e170d0476b15d78458795bb18f1304fb94160cabf40c", size = 12765333, upload-time = "2025-09-29T23:21:55.77Z" }, + { url = "https://files.pythonhosted.org/packages/8d/0f/b4d4ae743a83742f1153464cf1a8ecfafc3ac59722a0b5c8602310cb7158/pandas-2.3.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:93c2d9ab0fc11822b5eece72ec9587e172f63cff87c00b062f6e37448ced4493", size = 13418120, upload-time = "2025-09-29T23:22:10.109Z" }, + { url = "https://files.pythonhosted.org/packages/4f/c7/e54682c96a895d0c808453269e0b5928a07a127a15704fedb643e9b0a4c8/pandas-2.3.3-cp313-cp313-win_amd64.whl", hash = "sha256:f8bfc0e12dc78f777f323f55c58649591b2cd0c43534e8355c51d3fede5f4dee", size = 10993991, upload-time = "2025-09-29T23:25:04.889Z" }, + { url = "https://files.pythonhosted.org/packages/f9/ca/3f8d4f49740799189e1395812f3bf23b5e8fc7c190827d55a610da72ce55/pandas-2.3.3-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:75ea25f9529fdec2d2e93a42c523962261e567d250b0013b16210e1d40d7c2e5", size = 12048227, upload-time = "2025-09-29T23:22:24.343Z" }, + { url = "https://files.pythonhosted.org/packages/0e/5a/f43efec3e8c0cc92c4663ccad372dbdff72b60bdb56b2749f04aa1d07d7e/pandas-2.3.3-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:74ecdf1d301e812db96a465a525952f4dde225fdb6d8e5a521d47e1f42041e21", size = 11411056, upload-time = "2025-09-29T23:22:37.762Z" }, + { url = "https://files.pythonhosted.org/packages/46/b1/85331edfc591208c9d1a63a06baa67b21d332e63b7a591a5ba42a10bb507/pandas-2.3.3-cp313-cp313t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6435cb949cb34ec11cc9860246ccb2fdc9ecd742c12d3304989017d53f039a78", size = 11645189, upload-time = "2025-09-29T23:22:51.688Z" }, + { url = "https://files.pythonhosted.org/packages/44/23/78d645adc35d94d1ac4f2a3c4112ab6f5b8999f4898b8cdf01252f8df4a9/pandas-2.3.3-cp313-cp313t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:900f47d8f20860de523a1ac881c4c36d65efcb2eb850e6948140fa781736e110", size = 12121912, upload-time = "2025-09-29T23:23:05.042Z" }, + { url = "https://files.pythonhosted.org/packages/53/da/d10013df5e6aaef6b425aa0c32e1fc1f3e431e4bcabd420517dceadce354/pandas-2.3.3-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:a45c765238e2ed7d7c608fc5bc4a6f88b642f2f01e70c0c23d2224dd21829d86", size = 12712160, upload-time = "2025-09-29T23:23:28.57Z" }, + { url = "https://files.pythonhosted.org/packages/bd/17/e756653095a083d8a37cbd816cb87148debcfcd920129b25f99dd8d04271/pandas-2.3.3-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:c4fc4c21971a1a9f4bdb4c73978c7f7256caa3e62b323f70d6cb80db583350bc", size = 13199233, upload-time = "2025-09-29T23:24:24.876Z" }, + { url = "https://files.pythonhosted.org/packages/04/fd/74903979833db8390b73b3a8a7d30d146d710bd32703724dd9083950386f/pandas-2.3.3-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:ee15f284898e7b246df8087fc82b87b01686f98ee67d85a17b7ab44143a3a9a0", size = 11540635, upload-time = "2025-09-29T23:25:52.486Z" }, + { url = "https://files.pythonhosted.org/packages/21/00/266d6b357ad5e6d3ad55093a7e8efc7dd245f5a842b584db9f30b0f0a287/pandas-2.3.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:1611aedd912e1ff81ff41c745822980c49ce4a7907537be8692c8dbc31924593", size = 10759079, upload-time = "2025-09-29T23:26:33.204Z" }, + { url = "https://files.pythonhosted.org/packages/ca/05/d01ef80a7a3a12b2f8bbf16daba1e17c98a2f039cbc8e2f77a2c5a63d382/pandas-2.3.3-cp314-cp314-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6d2cefc361461662ac48810cb14365a365ce864afe85ef1f447ff5a1e99ea81c", size = 11814049, upload-time = "2025-09-29T23:27:15.384Z" }, + { url = "https://files.pythonhosted.org/packages/15/b2/0e62f78c0c5ba7e3d2c5945a82456f4fac76c480940f805e0b97fcbc2f65/pandas-2.3.3-cp314-cp314-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ee67acbbf05014ea6c763beb097e03cd629961c8a632075eeb34247120abcb4b", size = 12332638, upload-time = "2025-09-29T23:27:51.625Z" }, + { url = "https://files.pythonhosted.org/packages/c5/33/dd70400631b62b9b29c3c93d2feee1d0964dc2bae2e5ad7a6c73a7f25325/pandas-2.3.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:c46467899aaa4da076d5abc11084634e2d197e9460643dd455ac3db5856b24d6", size = 12886834, upload-time = "2025-09-29T23:28:21.289Z" }, + { url = "https://files.pythonhosted.org/packages/d3/18/b5d48f55821228d0d2692b34fd5034bb185e854bdb592e9c640f6290e012/pandas-2.3.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:6253c72c6a1d990a410bc7de641d34053364ef8bcd3126f7e7450125887dffe3", size = 13409925, upload-time = "2025-09-29T23:28:58.261Z" }, + { url = "https://files.pythonhosted.org/packages/a6/3d/124ac75fcd0ecc09b8fdccb0246ef65e35b012030defb0e0eba2cbbbe948/pandas-2.3.3-cp314-cp314-win_amd64.whl", hash = "sha256:1b07204a219b3b7350abaae088f451860223a52cfb8a6c53358e7948735158e5", size = 11109071, upload-time = "2025-09-29T23:32:27.484Z" }, + { url = "https://files.pythonhosted.org/packages/89/9c/0e21c895c38a157e0faa1fb64587a9226d6dd46452cac4532d80c3c4a244/pandas-2.3.3-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:2462b1a365b6109d275250baaae7b760fd25c726aaca0054649286bcfbb3e8ec", size = 12048504, upload-time = "2025-09-29T23:29:31.47Z" }, + { url = "https://files.pythonhosted.org/packages/d7/82/b69a1c95df796858777b68fbe6a81d37443a33319761d7c652ce77797475/pandas-2.3.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:0242fe9a49aa8b4d78a4fa03acb397a58833ef6199e9aa40a95f027bb3a1b6e7", size = 11410702, upload-time = "2025-09-29T23:29:54.591Z" }, + { url = "https://files.pythonhosted.org/packages/f9/88/702bde3ba0a94b8c73a0181e05144b10f13f29ebfc2150c3a79062a8195d/pandas-2.3.3-cp314-cp314t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a21d830e78df0a515db2b3d2f5570610f5e6bd2e27749770e8bb7b524b89b450", size = 11634535, upload-time = "2025-09-29T23:30:21.003Z" }, + { url = "https://files.pythonhosted.org/packages/a4/1e/1bac1a839d12e6a82ec6cb40cda2edde64a2013a66963293696bbf31fbbb/pandas-2.3.3-cp314-cp314t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:2e3ebdb170b5ef78f19bfb71b0dc5dc58775032361fa188e814959b74d726dd5", size = 12121582, upload-time = "2025-09-29T23:30:43.391Z" }, + { url = "https://files.pythonhosted.org/packages/44/91/483de934193e12a3b1d6ae7c8645d083ff88dec75f46e827562f1e4b4da6/pandas-2.3.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:d051c0e065b94b7a3cea50eb1ec32e912cd96dba41647eb24104b6c6c14c5788", size = 12699963, upload-time = "2025-09-29T23:31:10.009Z" }, + { url = "https://files.pythonhosted.org/packages/70/44/5191d2e4026f86a2a109053e194d3ba7a31a2d10a9c2348368c63ed4e85a/pandas-2.3.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:3869faf4bd07b3b66a9f462417d0ca3a9df29a9f6abd5d0d0dbab15dac7abe87", size = 13202175, upload-time = "2025-09-29T23:31:59.173Z" }, +] + [[package]] name = "pluggy" version = "1.6.0" @@ -823,6 +870,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/f0/d7/a812a0bd0f5160823e647524488cc9734f93782f2c273b8f77e8afc60a37/pytest-8.1.2-py3-none-any.whl", hash = "sha256:6c06dc309ff46a05721e6fd48e492a775ed8165d2ecdf57f156a80c7e95bb142", size = 337456, upload-time = "2024-04-26T18:05:15.452Z" }, ] +[[package]] +name = "python-dateutil" +version = "2.9.0.post0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "six" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/66/c0/0c8b6ad9f17a802ee498c46e004a0eb49bc148f2fd230864601a86dcf6db/python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 342432, upload-time = "2024-03-01T18:36:20.211Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892, upload-time = "2024-03-01T18:36:18.57Z" }, +] + [[package]] name = "python-dotenv" version = "1.2.2" @@ -841,6 +900,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/8f/cb/769cfc37177252872a45a71f3fbdde9d51b471a3f3c14bfe95dde3407386/python_multipart-0.0.29-py3-none-any.whl", hash = "sha256:2ddcc971cef266225f54f552d8fa10bcfbb1f14446caec199060daac59ff2d69", size = 29640, upload-time = "2026-05-17T17:29:45.69Z" }, ] +[[package]] +name = "pytz" +version = "2026.3.post1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/fb/48/fb042503b6ca6cd271261dc559fd6432f7d8c713153e9ec5c591af4dfc1c/pytz-2026.3.post1.tar.gz", hash = "sha256:2211d3fcf9a797d3405cac96ac7f61d80e6a644f72a3309607282fe8a2010c5d", size = 319745, upload-time = "2026-07-25T15:12:07.385Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0f/7b/39c34ca613b0b198cb866466651b26b045e2009864c5183c979a3b83f383/pytz-2026.3.post1-py2.py3-none-any.whl", hash = "sha256:dd95840dd199baea12d9cc096a1d452caa6596a1c1e4b5f3dbd1541855d5e815", size = 508283, upload-time = "2026-07-25T15:12:05.782Z" }, +] + [[package]] name = "pyyaml" version = "6.0.3" @@ -1143,6 +1211,7 @@ dependencies = [ { name = "fastapi" }, { name = "httpx" }, { name = "openai" }, + { name = "pandas" }, { name = "pydantic" }, { name = "pydantic-settings" }, { name = "pyjwt" }, @@ -1165,6 +1234,7 @@ requires-dist = [ { name = "fastapi", specifier = "~=0.115.0" }, { name = "httpx", specifier = "~=0.27.0" }, { name = "openai", specifier = "~=2.41.0" }, + { name = "pandas", specifier = "~=2.3.3" }, { name = "pydantic", specifier = "~=2.7.1" }, { name = "pydantic-settings", specifier = "~=2.2.1" }, { name = "pyjwt", specifier = "~=2.8.0" }, @@ -1196,6 +1266,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/e0/f9/0595336914c5619e5f28a1fb793285925a8cd4b432c9da0a987836c7f822/shellingham-1.5.4-py2.py3-none-any.whl", hash = "sha256:7ecfff8f2fd72616f7481040475a65b2bf8af90a56c89140852d1120324e8686", size = 9755, upload-time = "2023-10-24T04:13:38.866Z" }, ] +[[package]] +name = "six" +version = "1.17.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031, upload-time = "2024-12-04T17:35:28.174Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" }, +] + [[package]] name = "sniffio" version = "1.3.1" @@ -1441,6 +1520,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/18/67/36e9267722cc04a6b9f15c7f3441c2363321a3ea07da7ae0c0707beb2a9c/typing_extensions-4.15.0-py3-none-any.whl", hash = "sha256:f0fa19c6845758ab08074a0cfa8b7aecb71c999ca73d62883bc25cc018c4e548", size = 44614, upload-time = "2025-08-25T13:49:24.86Z" }, ] +[[package]] +name = "tzdata" +version = "2026.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/92/ff/5a28bdfd8c3ebec42564ac7d0e54ca3db65044a9314a97f9564fa7a1e926/tzdata-2026.3.tar.gz", hash = "sha256:4a1518b8993086a7982523e071643f3c0e5f213e75b21318e78bcabfff9d1415", size = 198674, upload-time = "2026-07-10T08:50:37.887Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e5/6d/b53b99a9f2766d095985947a5782f1702cabb129a34f7a802d7197af832f/tzdata-2026.3-py2.py3-none-any.whl", hash = "sha256:dc096730c87af6cab1b171c9d532be840741ff5d459015e7f6947bd7d7e54931", size = 348168, upload-time = "2026-07-10T08:50:36.46Z" }, +] + [[package]] name = "uvicorn" version = "0.29.0" diff --git a/webapp/src/app/api/model/keywordPatentHighlight.ts b/webapp/src/app/api/model/keywordPatentHighlight.ts new file mode 100644 index 00000000..7269e32c --- /dev/null +++ b/webapp/src/app/api/model/keywordPatentHighlight.ts @@ -0,0 +1,18 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/** + * Elasticsearch highlight fragments (terms wrapped in ...). + */ +export interface KeywordPatentHighlight { + title_de?: Array; + title_en?: Array; + abstract?: Array; +} diff --git a/webapp/src/app/api/model/keywordPatentMatch.ts b/webapp/src/app/api/model/keywordPatentMatch.ts index 3e412bdf..48ff2291 100644 --- a/webapp/src/app/api/model/keywordPatentMatch.ts +++ b/webapp/src/app/api/model/keywordPatentMatch.ts @@ -8,6 +8,7 @@ * Do not edit the class manually. */ import { KeywordEvidence } from './keywordEvidence'; +import { KeywordPatentHighlight } from './keywordPatentHighlight'; import { PatentEntry } from './patentEntry'; export interface KeywordPatentMatch { @@ -30,6 +31,7 @@ export interface KeywordPatentMatch { text_score: number; matched_keywords?: Array; matched_ipc_symbols?: Array; + highlight?: KeywordPatentHighlight | null; /** * True when the patent was retrieved via title/abstract keyword search because IPC mapping was uncertain, missing, or yielded no hits. */ diff --git a/webapp/src/app/api/model/patentEntry.ts b/webapp/src/app/api/model/patentEntry.ts index 7f6d7809..18d4fb08 100644 --- a/webapp/src/app/api/model/patentEntry.ts +++ b/webapp/src/app/api/model/patentEntry.ts @@ -15,7 +15,10 @@ export interface PatentEntry { patent_id: string; source: string; title?: string | null; + title_de?: string | null; + title_en?: string | null; 'abstract'?: string | null; + abstract_lang?: string | null; publication_date?: string | null; publication_year?: string | null; application_number?: string | null; diff --git a/webapp/src/app/api/model/patentsByKeywordsRequest.ts b/webapp/src/app/api/model/patentsByKeywordsRequest.ts index 1e9d3021..6a0b41a5 100644 --- a/webapp/src/app/api/model/patentsByKeywordsRequest.ts +++ b/webapp/src/app/api/model/patentsByKeywordsRequest.ts @@ -10,10 +10,30 @@ import { KeywordPatentSearchItem } from './keywordPatentSearchItem'; -export interface PatentsByKeywordsRequest { +export interface PatentsByKeywordsRequest { /** * Keywords to match against patents_openalex_keywords. */ keywords: Array; + /** + * Zero-based page index. + */ + page?: number; + /** + * Page size. + */ + size?: number; + /** + * Filter to a single source: EPO or USPTO. Omit for both. + */ + source?: string | null; + /** + * title | publication_year | source. Omit to sort by match quality. + */ + sort_by?: string | null; + /** + * asc | desc + */ + sort_direction?: string; } diff --git a/webapp/src/app/api/model/patentsByKeywordsResponse.ts b/webapp/src/app/api/model/patentsByKeywordsResponse.ts index f801c6d5..707add21 100644 --- a/webapp/src/app/api/model/patentsByKeywordsResponse.ts +++ b/webapp/src/app/api/model/patentsByKeywordsResponse.ts @@ -13,6 +13,18 @@ import { KeywordPatentMatch } from './keywordPatentMatch'; export interface PatentsByKeywordsResponse { patent_count: number; + /** + * Total matches across all pages (before page/size slicing). + */ + total_count: number; + /** + * Total EPO matches, unfiltered by source. + */ + epo_count: number; + /** + * Total USPTO matches, unfiltered by source. + */ + uspto_count: number; patents: Array; /** * IPC mapping outcome: mapped (IPC used), uncertain (fragmented evidence; may include text-retrieved patents), no_mapping (no usable IPC evidence; may include text-retrieved patents), no_patents_found (neither IPC nor keyword text search produced relevant patents), or search_error (technical failure talking to the search backend). diff --git a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html index 2899e79a..eadc47dc 100644 --- a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html +++ b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html @@ -6,7 +6,7 @@ [diameter]="150" /> } @else if (error()) {

Fehler beim Laden der Patente.

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

{{ emptyMessage() }}

} @else {
@@ -32,13 +32,13 @@
Patente mit passenden Keywords.

- {{ matches().length }} + {{ totalCount() }} Patente
- {{ getEpoCount() }} + {{ epoCount() }} EPO
- {{ getUsptoCount() }} + {{ usptoCount() }} USPTO
diff --git a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.ts b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.ts index ebb5b168..a719442b 100644 --- a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.ts +++ b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.ts @@ -6,13 +6,11 @@ import { output, signal, } from '@angular/core'; -import { toSignal } from '@angular/core/rxjs-interop'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatIconModule } from '@angular/material/icon'; import { MatSelectModule } from '@angular/material/select'; import { PageEvent } from '@angular/material/paginator'; -import { Sort } from '@angular/material/sort'; -import { ActivatedRoute, Router } from '@angular/router'; +import { Router } from '@angular/router'; import { PatentEntry } from '../../../api/model/patentEntry'; import { KeywordPatentMatch } from '../../../api/model/keywordPatentMatch'; import { LoadingComponent } from '../../../shared/ui/loading/loading.component'; @@ -22,14 +20,25 @@ import { getPublicationStageLabel, } from '../../patent-detail/patent-detail.utils'; import { KeywordPatentMappingStatus } from '../../../api'; -import { PatentTableComponent } from '../../../shared/ui/patent-table/patent-table.component'; -import { SourceFilterComponent } from '../../../shared/ui/source-filter/source-filter.component'; +import { + PatentTableComponent, + PatentTableEntry, +} from '../../../shared/ui/patent-table/patent-table.component'; +import { + SourceFilterComponent, + SourceFilterValue, +} from '../../../shared/ui/source-filter/source-filter.component'; -type SourceFilter = 'all' | 'EPO' | 'USPTO'; -type SortColumn = 'title' | 'publication_year' | 'source'; -type SortDirection = 'asc' | 'desc'; +export type PatentSourceFilter = SourceFilterValue; +export type PatentSortColumn = 'title' | 'publication_year' | 'source'; +export type PatentSortDirection = 'asc' | 'desc'; -function isValidSortColumn(value: string | null): value is SortColumn { +export interface PatentSortChange { + column: PatentSortColumn; + direction: PatentSortDirection; +} + +function isValidSortColumn(value: string | null): value is PatentSortColumn { return ( value === 'title' || value === 'publication_year' || value === 'source' ); @@ -50,46 +59,41 @@ function isValidSortColumn(value: string | null): value is SortColumn { styleUrl: './keywords-patents.component.scss', }) export class KeywordsPatentsComponent { - private readonly route = inject(ActivatedRoute); private readonly router = inject(Router); - private readonly queryParams = toSignal(this.route.queryParams); readonly matches = input([]); + readonly totalCount = input(0); + readonly epoCount = input(0); + readonly usptoCount = input(0); + readonly activeFilter = input('all'); + readonly sortColumn = input('publication_year'); + readonly sortDirection = input('desc'); readonly mappingStatus = input(null); readonly loading = input(false); readonly error = input(false); readonly showReload = input(false); readonly reloadDisabled = input(false); readonly reload = output(); + readonly filterChange = output(); + readonly sortChange = output(); - activeFilter = signal('all'); - sortColumn = signal('publication_year'); - sortDirection = signal('desc'); selectedMatch = signal(null); - readonly pageIndex = computed(() => { - const params = this.queryParams(); - return params?.['page'] ? +params['page'] || 0 : 0; - }); - - readonly pageSize = computed(() => { - const params = this.queryParams(); - return params?.['size'] ? +params['size'] || 10 : 10; - }); - - readonly filteredMatches = computed(() => { - const filter = this.activeFilter(); - let items = this.matches(); - if (filter !== 'all') { - items = items.filter((item) => item.patent.source === filter); - } - return this.sortMatches(items); - }); - readonly selectedPatent = computed( () => this.selectedMatch()?.patent ?? null, ); + // Memoized so row objects keep a stable identity across change-detection + // cycles — the table's expand/collapse state tracks the selected row by + // reference, which breaks if a fresh object is spread on every read. + readonly pagedPatents = computed(() => + this.matches().map((item) => ({ + ...item.patent, + matched_keywords: item.matched_keywords, + highlight: item.highlight, + })), + ); + emptyMessage(): string { switch (this.mappingStatus()) { case 'search_error': @@ -99,44 +103,41 @@ export class KeywordsPatentsComponent { } } - getPagedMatches(): KeywordPatentMatch[] { - const start = this.pageIndex() * this.pageSize(); - return this.filteredMatches().slice(start, start + this.pageSize()); - } - - getPagedPatents(): PatentEntry[] { - return this.getPagedMatches().map((item) => item.patent); - } - - setFilter(filter: SourceFilter): void { - this.activeFilter.set(filter); + setFilter(filter: PatentSourceFilter): void { + this.filterChange.emit(filter); this.selectedMatch.set(null); - this.resetPage(); } - onSortChange(sort: Sort): void { + onSortChange(sort: { active: string; direction: string }): void { if (!sort.direction || !isValidSortColumn(sort.active)) { return; } - this.sortColumn.set(sort.active); - this.sortDirection.set(sort.direction); + this.sortChange.emit({ + column: sort.active, + direction: sort.direction as PatentSortDirection, + }); this.selectedMatch.set(null); - this.resetPage(); } - setSort(column: SortColumn): void { + setSort(column: PatentSortColumn): void { if (this.sortColumn() === column) { - this.sortDirection.set(this.sortDirection() === 'asc' ? 'desc' : 'asc'); + this.sortChange.emit({ + column, + direction: this.sortDirection() === 'asc' ? 'desc' : 'asc', + }); } else { - this.sortColumn.set(column); - this.sortDirection.set(column === 'publication_year' ? 'desc' : 'asc'); + this.sortChange.emit({ + column, + direction: column === 'publication_year' ? 'desc' : 'asc', + }); } this.selectedMatch.set(null); - this.resetPage(); } selectPatentFromTable(patent: PatentEntry): void { - const match = this.matches().find((item) => item.patent === patent); + const match = this.matches().find( + (item) => item.patent.patent_id === patent.patent_id, + ); if (match) { this.selectMatch(match); } @@ -146,15 +147,6 @@ export class KeywordsPatentsComponent { this.selectedMatch.set(null); } - private resetPage(): void { - void this.router.navigate([], { - relativeTo: this.route, - queryParams: { page: 0 }, - queryParamsHandling: 'merge', - replaceUrl: true, - }); - } - selectMatch(item: KeywordPatentMatch): void { this.selectedMatch.set(item); } @@ -165,15 +157,6 @@ export class KeywordsPatentsComponent { void this.router.navigate(['/patent', match.patent.patent_id]); } - getEpoCount(): number { - return this.matches().filter((item) => item.patent.source === 'EPO').length; - } - - getUsptoCount(): number { - return this.matches().filter((item) => item.patent.source === 'USPTO') - .length; - } - formatDate(date: string | null | undefined): string { return formatPatentDate(date); } @@ -192,31 +175,4 @@ export class KeywordsPatentsComponent { } return `${text.slice(0, 160).trimEnd()}…`; } - - private sortMatches(items: KeywordPatentMatch[]): KeywordPatentMatch[] { - const column = this.sortColumn(); - const direction = this.sortDirection() === 'asc' ? 1 : -1; - return [...items].sort((a, b) => { - switch (column) { - case 'publication_year': { - const yearA = - a.patent.publication_date ?? - String(a.patent.publication_year ?? ''); - const yearB = - b.patent.publication_date ?? - String(b.patent.publication_year ?? ''); - return direction * yearA.localeCompare(yearB); - } - case 'source': - return direction * a.patent.source.localeCompare(b.patent.source); - default: - return ( - direction * - (a.patent.title ?? '').localeCompare(b.patent.title ?? '', 'de', { - sensitivity: 'base', - }) - ); - } - }); - } } 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 2253d1b1..b5f3b596 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.ts +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.ts @@ -54,7 +54,6 @@ import { MatTooltipModule } from '@angular/material/tooltip'; import { A11yModule } from '@angular/cdk/a11y'; import { DomSanitizer } from '@angular/platform-browser'; import { SearchResultsPayload } from './search-results/search-results-state.service'; -import { clearPatentsCache } from './patent-search.utils'; type InputMode = 'url' | 'text' | 'file'; type KeywordCategory = 'broad' | 'coarse' | 'fine' | 'manual'; type KeywordView = 'llm' | 'topic'; @@ -325,7 +324,6 @@ export class KeywordsSearchComponent { this.broadKeywordEntries.set([]); this.coarseKeywordEntries.set([]); this.fineKeywordEntries.set([]); - clearPatentsCache(); this.websocketService.close(); this.isExtracting.set(false); this.loadingNewKeyword.set(false); @@ -576,7 +574,6 @@ export class KeywordsSearchComponent { this.manualKeywordEntries.set([]); this.sourceContent.set(''); this.sourceUrl.set(null); - clearPatentsCache(); const manualSet = new Set(this.getKeywordLabels(this.manualKeywords())); this.selectedKeywords.set( this.selectedKeywords().filter((k) => manualSet.has(k)), diff --git a/webapp/src/app/modules/keywords-search/patent-search.utils.ts b/webapp/src/app/modules/keywords-search/patent-search.utils.ts index 46c879af..5965f25a 100644 --- a/webapp/src/app/modules/keywords-search/patent-search.utils.ts +++ b/webapp/src/app/modules/keywords-search/patent-search.utils.ts @@ -1,25 +1,10 @@ -import { KeywordPatentMappingStatus } from '../../api'; import { KeywordEntryWithTopic } from '../../api/model/keywordEntryWithTopic'; -import { KeywordPatentMatch } from '../../api/model/keywordPatentMatch'; import { KeywordPatentSearchItem } from '../../api/model/keywordPatentSearchItem'; import { PatentKeywordEntry, SearchResultsPayload, } from './search-results/search-results-state.service'; -export const PATENTS_CACHE_KEY = 'keywords-patents-cache'; - -export interface PatentsCache { - keywords: string[]; - matches: KeywordPatentMatch[]; - mappingStatus?: KeywordPatentMappingStatus | null; -} - -export interface PatentsCacheResult { - matches: KeywordPatentMatch[]; - mappingStatus: KeywordPatentMappingStatus | null; -} - export function buildPatentSearchItems( items: PatentKeywordEntry[], ): KeywordPatentSearchItem[] { @@ -63,48 +48,6 @@ export function buildPatentSearchItemsFromPayload( return buildPatentSearchItems(fallbackEntries); } -export function readPatentsCache( - keywords: string[], -): PatentsCacheResult | null { - const raw = sessionStorage.getItem(PATENTS_CACHE_KEY); - if (!raw) return null; - - try { - const cache = JSON.parse(raw) as PatentsCache; - if (!sameKeywordSet(cache.keywords, keywords)) return null; - return { - matches: cache.matches ?? [], - mappingStatus: cache.mappingStatus ?? null, - }; - } catch { - sessionStorage.removeItem(PATENTS_CACHE_KEY); - return null; - } -} - -export function writePatentsCache( - keywords: string[], - matches: KeywordPatentMatch[], - mappingStatus: KeywordPatentMappingStatus | null = null, -): void { - try { - const cache: PatentsCache = { keywords, matches, mappingStatus }; - sessionStorage.setItem(PATENTS_CACHE_KEY, JSON.stringify(cache)); - } catch (error) { - console.error('Failed to cache patent results:', error); - } -} - -export function clearPatentsCache(): void { - sessionStorage.removeItem(PATENTS_CACHE_KEY); -} - function normalizeKeyword(value: string): string { return value.trim().toLowerCase(); } - -function sameKeywordSet(a: string[], b: string[]): boolean { - if (a.length !== b.length) return false; - const setA = new Set(a.map((keyword) => normalizeKeyword(keyword))); - return b.every((keyword) => setA.has(normalizeKeyword(keyword))); -} diff --git a/webapp/src/app/modules/keywords-search/search-results/patents-results/patents-results.component.html b/webapp/src/app/modules/keywords-search/search-results/patents-results/patents-results.component.html index bd5b16b4..b38b1081 100644 --- a/webapp/src/app/modules/keywords-search/search-results/patents-results/patents-results.component.html +++ b/webapp/src/app/modules/keywords-search/search-results/patents-results/patents-results.component.html @@ -2,11 +2,19 @@
+ (reload)="reloadPatents()" + (filterChange)="setFilter($event)" + (sortChange)="setSort($event.column, $event.direction)" />
diff --git a/webapp/src/app/modules/keywords-search/search-results/patents-results/patents-results.component.ts b/webapp/src/app/modules/keywords-search/search-results/patents-results/patents-results.component.ts index 572229f3..ded27672 100644 --- a/webapp/src/app/modules/keywords-search/search-results/patents-results/patents-results.component.ts +++ b/webapp/src/app/modules/keywords-search/search-results/patents-results/patents-results.component.ts @@ -1,15 +1,17 @@ -import { Component, inject, OnInit, signal } from '@angular/core'; +import { Component, effect, inject, signal } from '@angular/core'; +import { ActivatedRoute } from '@angular/router'; +import { toSignal } from '@angular/core/rxjs-interop'; import { KeywordsService } from '../../../../api/api/keywords.service'; -import { KeywordPatentMatch } from '../../../../api/model/keywordPatentMatch'; import { PatentsByKeywordsResponse } from '../../../../api/model/patentsByKeywordsResponse'; -import { KeywordsPatentsComponent } from '../../keywords-patents/keywords-patents.component'; +import { KeywordPatentMatch } from '../../../../api/model/keywordPatentMatch'; import { - buildPatentSearchItemsFromPayload, - clearPatentsCache, - readPatentsCache, - writePatentsCache, -} from '../../patent-search.utils'; + KeywordsPatentsComponent, + PatentSortColumn, + PatentSortDirection, + PatentSourceFilter, +} from '../../keywords-patents/keywords-patents.component'; +import { buildPatentSearchItemsFromPayload } from '../../patent-search.utils'; import { SearchResultsStateService } from '../search-results-state.service'; import { KeywordPatentMappingStatus } from '../../../../api'; @@ -19,63 +21,117 @@ import { KeywordPatentMappingStatus } from '../../../../api'; templateUrl: './patents-results.component.html', styleUrl: './patents-results.component.scss', }) -export class KeywordsToPatentsResultsComponent implements OnInit { +export class KeywordsToPatentsResultsComponent { protected readonly state = inject(SearchResultsStateService); private readonly keywordsService = inject(KeywordsService); + private readonly route = inject(ActivatedRoute); + + private readonly queryParams = toSignal(this.route.queryParams, { + initialValue: this.route.snapshot.queryParams, + }); + + readonly pageIndex = signal(0); + readonly pageSize = signal(10); + readonly activeFilter = signal('all'); + readonly sortColumn = signal('publication_year'); + readonly sortDirection = signal('desc'); readonly patentMatches = signal([]); + readonly totalCount = signal(0); + readonly epoCount = signal(0); + readonly usptoCount = signal(0); readonly mappingStatus = signal(null); readonly loadingPatents = signal(false); readonly patentsError = signal(false); - ngOnInit(): void { - const cached = readPatentsCache(this.state.keywords()); - if (cached) { - this.setPatentMatches(cached.matches, cached.mappingStatus); - return; - } + constructor() { + effect(() => { + const params = this.queryParams(); + this.pageIndex.set(params?.['page'] ? +params['page'] || 0 : 0); + this.pageSize.set(params?.['size'] ? +params['size'] || 10 : 10); + }); - this.loadMatchingPatents(); + effect(() => { + // Re-run whenever the search keywords or any page/filter/sort state changes. + const keywords = buildPatentSearchItemsFromPayload(this.state.payload()); + const page = this.pageIndex(); + const size = this.pageSize(); + const source = this.activeFilter(); + const sortBy = this.sortColumn(); + const sortDirection = this.sortDirection(); + + this.loadMatchingPatents(keywords, page, size, source, sortBy, sortDirection); + }); } reloadPatents(): void { - clearPatentsCache(); - this.loadMatchingPatents(); + const keywords = buildPatentSearchItemsFromPayload(this.state.payload()); + this.loadMatchingPatents( + keywords, + this.pageIndex(), + this.pageSize(), + this.activeFilter(), + this.sortColumn(), + this.sortDirection(), + ); } - private loadMatchingPatents(): void { - const keywords = buildPatentSearchItemsFromPayload(this.state.payload()); + setFilter(filter: PatentSourceFilter): void { + this.activeFilter.set(filter); + } + + setSort(column: PatentSortColumn, direction: PatentSortDirection): void { + this.sortColumn.set(column); + this.sortDirection.set(direction); + } + + private loadMatchingPatents( + keywords: ReturnType, + page: number, + size: number, + source: PatentSourceFilter, + sortBy: PatentSortColumn, + sortDirection: PatentSortDirection, + ): void { if (keywords.length === 0) { - this.setPatentMatches([], 'no_mapping'); + this.patentMatches.set([]); + this.totalCount.set(0); + this.epoCount.set(0); + this.usptoCount.set(0); + this.mappingStatus.set('no_mapping'); return; } this.loadingPatents.set(true); this.patentsError.set(false); - this.keywordsService.getPatentsByKeywords({ keywords }).subscribe({ - next: (response: PatentsByKeywordsResponse) => { - this.setPatentMatches( - response.patents ?? [], - response.mapping_status ?? null, - ); - this.loadingPatents.set(false); - }, - error: (error: unknown) => { - console.error('Patent search failed:', error); - this.setPatentMatches([], null); - this.patentsError.set(true); - this.loadingPatents.set(false); - }, - }); - } - - private setPatentMatches( - matches: KeywordPatentMatch[], - mappingStatus: KeywordPatentMappingStatus | null = null, - ): void { - this.patentMatches.set(matches); - this.mappingStatus.set(mappingStatus); - writePatentsCache(this.state.keywords(), matches, mappingStatus); + this.keywordsService + .getPatentsByKeywords({ + keywords, + page, + size, + source: source === 'all' ? null : source, + sort_by: sortBy, + sort_direction: sortDirection, + }) + .subscribe({ + next: (response: PatentsByKeywordsResponse) => { + this.patentMatches.set(response.patents ?? []); + this.totalCount.set(response.total_count ?? 0); + this.epoCount.set(response.epo_count ?? 0); + this.usptoCount.set(response.uspto_count ?? 0); + this.mappingStatus.set(response.mapping_status ?? null); + this.loadingPatents.set(false); + }, + error: (error: unknown) => { + console.error('Patent search failed:', error); + this.patentMatches.set([]); + this.totalCount.set(0); + this.epoCount.set(0); + this.usptoCount.set(0); + this.patentsError.set(true); + this.loadingPatents.set(false); + }, + }); } } diff --git a/webapp/src/app/shared/ui/patent-table/patent-table.component.html b/webapp/src/app/shared/ui/patent-table/patent-table.component.html index cd86abe3..cb69ba37 100644 --- a/webapp/src/app/shared/ui/patent-table/patent-table.component.html +++ b/webapp/src/app/shared/ui/patent-table/patent-table.component.html @@ -1,6 +1,7 @@ @@ -125,3 +126,55 @@ open_in_new + + + @if (hasAnyHighlight(patent)) { + +
+

Fundstelle im Patent

+
+ + +
+
+ + +
+
+ @if (getDisplayedTitle(patent); as displayedTitle) { +
+

Titel

+ +
+ } + + @if (patent.abstract) { +
+

Abstract

+ +
+ } +
+
+ } +
diff --git a/webapp/src/app/shared/ui/patent-table/patent-table.component.ts b/webapp/src/app/shared/ui/patent-table/patent-table.component.ts index 7e4d449a..e61eb75d 100644 --- a/webapp/src/app/shared/ui/patent-table/patent-table.component.ts +++ b/webapp/src/app/shared/ui/patent-table/patent-table.component.ts @@ -1,6 +1,7 @@ import { Component, TemplateRef, + computed, inject, input, output, @@ -14,6 +15,7 @@ import { MatTooltipModule } from '@angular/material/tooltip'; import { Sort } from '@angular/material/sort'; import { PatentEntry } from '../../../api/model/patentEntry'; import { MatchedAuthor } from '../../../api/model/matchedAuthor'; +import { KeywordPatentHighlight } from '../../../api/model/keywordPatentHighlight'; import { DataTableComponent, GenericColumn, @@ -21,12 +23,22 @@ import { import { ChipComponent } from '../chip/chip.component'; import { AppAuthorChipComponent } from '../app-author-chip/app-author-chip.component'; import { isAssigneeLikelyPerson } from '../../../modules/patent-detail/patent-detail.utils'; +import { SearchResultsStateService } from '../../../modules/keywords-search/search-results/search-results-state.service'; +import { + HighlightedTextComponent, + HighlightTerm, +} from '../highlighted-text/highlighted-text.component'; +import { TableDetailRowComponent } from '../table-detail-row/table-detail-row.component'; export interface PatentTableEntry extends PatentEntry { match_type?: string; matched_authors?: MatchedAuthor[]; + matched_keywords?: string[]; + highlight?: KeywordPatentHighlight | null; } +type TitleLanguage = 'de' | 'en'; + @Component({ selector: 'app-patent-table', imports: [ @@ -37,6 +49,8 @@ export interface PatentTableEntry extends PatentEntry { DataTableComponent, ChipComponent, AppAuthorChipComponent, + HighlightedTextComponent, + TableDetailRowComponent, ], templateUrl: './patent-table.component.html', styleUrl: './patent-table.component.scss', @@ -45,6 +59,10 @@ export class PatentTableComponent< T extends PatentTableEntry = PatentTableEntry, > { private readonly router = inject(Router); + private readonly searchResultsStateService = inject( + SearchResultsStateService, + { optional: true }, + ); patents = input.required(); selectedPatent = input(null); @@ -56,6 +74,10 @@ export class PatentTableComponent< selectPatent = output(); handleSortChange = output(); + highlightRowEnabled = computed(() => + this.patents().some((patent) => this.hasAnyHighlight(patent)), + ); + titleTmp = viewChild.required>('titleTmp'); sourceTmp = viewChild.required>('sourceTmp'); yearTmp = viewChild.required>('yearTmp'); @@ -149,7 +171,92 @@ export class PatentTableComponent< } isSelected(patent: T): boolean { - return this.selectedPatent() === patent; + const selected = this.selectedPatent(); + return !!selected && selected.patent_id === patent.patent_id; + } + + /** + * Extracts the distinct matched terms out of Elasticsearch-style + * highlight fragments (terms wrapped in ...). + */ + extractHighlightTerms(fragments: string[] | null | undefined): string[] { + const terms = new Set(); + + for (const fragment of fragments ?? []) { + if (typeof fragment !== 'string') continue; + + const matches = fragment.matchAll(/(.*?)<\/em>/gi); + for (const match of matches) { + const term = match[1]?.trim(); + if (term) { + terms.add(term); + } + } + } + + return Array.from(terms); + } + + getHighlightTerms(terms: string[] | null | undefined): HighlightTerm[] { + return (terms ?? []).map((term) => ({ + term, + topic: this.searchResultsStateService?.resolveTopicForTerm(term) ?? null, + })); + } + + hasAnyHighlight(patent: T): boolean { + const highlight = patent.highlight; + return !!( + highlight?.title_de?.length || + highlight?.title_en?.length || + highlight?.abstract?.length + ); + } + + getTitleHighlightTerms(patent: T): HighlightTerm[] { + const highlight = patent.highlight; + const fragments = + this.getTitleLanguage(patent) === 'de' + ? highlight?.title_de + : highlight?.title_en; + return this.getHighlightTerms(this.extractHighlightTerms(fragments)); + } + + getAbstractHighlightTerms(patent: T): HighlightTerm[] { + return this.getHighlightTerms( + this.extractHighlightTerms(patent.highlight?.abstract), + ); + } + + private readonly selectedTitleLanguage = new Map(); + + hasDeTitle(patent: T): boolean { + return !!patent.title_de?.trim(); + } + + hasEnTitle(patent: T): boolean { + return !!patent.title_en?.trim(); + } + + getTitleLanguage(patent: T): TitleLanguage { + return ( + this.selectedTitleLanguage.get(patent.patent_id) ?? + (this.hasDeTitle(patent) ? 'de' : 'en') + ); + } + + setTitleLanguage(patent: T, language: TitleLanguage): void { + this.selectedTitleLanguage.set(patent.patent_id, language); + } + + getDisplayedTitle(patent: T): string { + if (this.getTitleLanguage(patent) === 'de' && this.hasDeTitle(patent)) { + return patent.title_de!; + } + if (this.hasEnTitle(patent)) { + return patent.title_en!; + } + return patent.title_de ?? patent.title ?? patent.patent_id; } isAssigneeLikelyPerson(assignee: string, patent: T): boolean {