From 1a2b1a1970e33d38e15fd27acf2fed94a24231ba Mon Sep 17 00:00:00 2001 From: taguesokoudjou Date: Mon, 13 Jul 2026 23:03:42 +0200 Subject: [PATCH 1/7] feat(keywords): show ranked patent matches with adjustable IPC/topic/text weights --- .../src/main/inse/patents/keywords/logic.py | 27 +- .../src/main/inse/patents/keywords/model.py | 3 + .../main/inse/patents/keywords/test_logic.py | 6 + .../patents_openalex_keywords/resolver.py | 64 +++- .../test_resolver.py | 55 ++++ .../api/model/patentsByKeywordsResponse.ts | 3 + .../keywords-patents.component.html | 292 ++++++++++-------- .../keywords-patents.component.scss | 37 ++- .../keywords-patents.component.ts | 217 +++++++------ .../keywords-search.component.html | 17 - .../keywords-search.component.scss | 14 +- .../keywords-search.component.ts | 82 +---- .../keywords-search/patent-search.utils.ts | 175 +++++++++++ .../patents-results.component.html | 24 +- .../patents-results.component.scss | 17 +- .../patents-results.component.ts | 172 +++++++---- .../search-results-state.service.ts | 8 + .../search-results.component.ts | 4 + 18 files changed, 793 insertions(+), 424 deletions(-) create mode 100644 webapp/src/app/modules/keywords-search/patent-search.utils.ts diff --git a/service/src/main/inse/patents/keywords/logic.py b/service/src/main/inse/patents/keywords/logic.py index 28d95c6e..47e51161 100644 --- a/service/src/main/inse/patents/keywords/logic.py +++ b/service/src/main/inse/patents/keywords/logic.py @@ -50,6 +50,7 @@ _MAX_SEARCH_KEYWORDS = 10 _MIN_KEYWORD_RELEVANCE = 0.0 _MIN_IPC_MATCH_SCORE = 0.65 _MIN_PATENT_MATCH_SCORE = 0.50 +_DEFAULT_SCORE_WEIGHTS = {"ipc": 0.60, "topic": 0.25, "text": 0.15} _SEARCHABLE_IPC_LEVELS = frozenset({"subgroup", "group", "subclass"}) # Soft field overlap for natural-science / engineering patent domains. _SOFT_MATCH_FIELD_NAMES = frozenset( @@ -492,15 +493,32 @@ def _patent_passes_relevance_gate( return has_topic_match or text_score > 0.0 +def _normalize_score_weights( + weights: dict[str, float] | None = None, +) -> dict[str, float]: + raw = { + "ipc": float((weights or {}).get("ipc", _DEFAULT_SCORE_WEIGHTS["ipc"])), + "topic": float((weights or {}).get("topic", _DEFAULT_SCORE_WEIGHTS["topic"])), + "text": float((weights or {}).get("text", _DEFAULT_SCORE_WEIGHTS["text"])), + } + total = sum(raw.values()) + if total <= 0: + return dict(_DEFAULT_SCORE_WEIGHTS) + return {key: value / total for key, value in raw.items()} + + def _compute_final_score( ipc_score: float, topic_score: float, text_score: float, + *, + weights: dict[str, float] | None = None, ) -> float: + normalized = _normalize_score_weights(weights) return round( - 0.60 * ipc_score - + 0.25 * topic_score - + 0.15 * text_score, + normalized["ipc"] * ipc_score + + normalized["topic"] * topic_score + + normalized["text"] * text_score, 4, ) @@ -753,6 +771,9 @@ async def get_patents_by_keywords( KeywordPatentMatch( patent=patent, match_score=score, + ipc_score=ipc_score, + topic_score=topic_score, + text_score=text_score, matched_keywords=matched_keywords, matched_ipc_symbols=matched_symbols, ) diff --git a/service/src/main/inse/patents/keywords/model.py b/service/src/main/inse/patents/keywords/model.py index fe274cad..56423282 100644 --- a/service/src/main/inse/patents/keywords/model.py +++ b/service/src/main/inse/patents/keywords/model.py @@ -45,6 +45,9 @@ class PatentsByKeywordsRequest(BaseModel): class KeywordPatentMatch(BaseModel): patent: PatentEntry match_score: float = Field(description="Combined match quality score.") + ipc_score: float = Field(description="IPC/CPC classification match score.") + topic_score: float = Field(description="OpenAlex topic overlap score (0 or 1).") + 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) diff --git a/service/src/main/inse/patents/keywords/test_logic.py b/service/src/main/inse/patents/keywords/test_logic.py index cb6dda70..0a6af63c 100644 --- a/service/src/main/inse/patents/keywords/test_logic.py +++ b/service/src/main/inse/patents/keywords/test_logic.py @@ -417,6 +417,12 @@ def test_compute_final_score_weights_ipc_topic_and_text() -> None: 4, ) assert _compute_final_score(0.6742, 0.0, 0.0) == round(0.60 * 0.6742, 4) + assert _compute_final_score( + 0.8, + 1.0, + 0.5, + weights={"ipc": 0.2, "topic": 0.2, "text": 0.6}, + ) == round(0.2 * 0.8 + 0.2 * 1.0 + 0.6 * 0.5, 4) def test_score_patent_rejects_subclass_only_without_topic_or_text() -> None: diff --git a/service/src/main/inse/patents/patents_openalex_keywords/resolver.py b/service/src/main/inse/patents/patents_openalex_keywords/resolver.py index bb33970b..31c70225 100644 --- a/service/src/main/inse/patents/patents_openalex_keywords/resolver.py +++ b/service/src/main/inse/patents/patents_openalex_keywords/resolver.py @@ -15,7 +15,10 @@ from inse.patents.authors.ipc_openalex_mapping import ( ) 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.client import ( + PatentsOpenAlexKeywordsClient, + candidate_doc_ids, +) from inse.patents.patents_openalex_keywords.ipc_entries import infer_subclass, normalize_symbol logger = logging.getLogger(__name__) @@ -215,6 +218,16 @@ class PatentOpenAlexMappingResolver: ) -> dict[str, list[MappedOpenAlexTopic]]: from inse.patents.common.parsing import patent_map_key + if not patents: + return {} + + candidate_symbols: list[str] = [] + for patent in patents: + for raw_code in (*patent.ipc, *patent.cpc): + candidate_symbols.extend(_lookup_candidates(raw_code)) + + await self._preload_documents(candidate_symbols) + result: dict[str, list[MappedOpenAlexTopic]] = {} for patent in patents: result[patent_map_key(patent)] = await self.resolve_mapped_topics_for_patent( @@ -222,6 +235,55 @@ class PatentOpenAlexMappingResolver: ) return result + async def _preload_documents(self, symbols: list[str]) -> None: + """Resolve all IPC/CPC candidate symbols in one or few ES _search requests.""" + pending = list( + dict.fromkeys( + normalized + for symbol in symbols + if (normalized := normalize_symbol(symbol)) + and normalized not in self._doc_cache + ) + ) + if not pending: + return + + all_doc_ids = list( + dict.fromkeys( + doc_id + for symbol in pending + for doc_id in candidate_doc_ids(symbol) + ) + ) + + docs_by_id: dict[str, dict] = {} + if all_doc_ids and await self._elasticsearch_enabled_for_request(): + try: + batch_size = 500 + for start in range(0, len(all_doc_ids), batch_size): + batch = all_doc_ids[start : start + batch_size] + docs_by_id.update(await self.client.lookup_ids(batch)) + except Exception as exc: + logger.warning( + "patents_openalex_keywords batch preload failed: %s", + exc, + ) + self._elasticsearch_enabled = False + + json_table = load_patents_openalex_keywords_json() + for symbol in pending: + doc = next( + ( + docs_by_id[doc_id] + for doc_id in candidate_doc_ids(symbol) + if doc_id in docs_by_id + ), + None, + ) + if doc is None: + doc = _json_lookup_symbol(symbol, json_table) + self._doc_cache[symbol] = doc + async def _elasticsearch_enabled_for_request(self) -> bool: if not self.use_elasticsearch: return False 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 index f46378de..3fe2dfcd 100644 --- a/service/src/main/inse/patents/patents_openalex_keywords/test_resolver.py +++ b/service/src/main/inse/patents/patents_openalex_keywords/test_resolver.py @@ -45,13 +45,26 @@ def test_mapped_topics_from_index_doc_includes_topics_and_keywords() -> None: class _FakeKeywordsClient: def __init__(self, docs: dict[str, dict]): self.docs = docs + self.lookup_ids_calls = 0 + self.lookup_symbol_calls = 0 async def index_exists(self) -> bool: return True async def lookup_symbol(self, symbol: str): + self.lookup_symbol_calls += 1 return self.docs.get(symbol) + async def lookup_ids(self, doc_ids: list[str]) -> dict[str, dict]: + self.lookup_ids_calls += 1 + result: dict[str, dict] = {} + for doc_id in doc_ids: + _level, symbol = doc_id.split(":", 1) + doc = self.docs.get(symbol) + if doc is not None: + result[doc_id] = doc + return result + def test_resolver_uses_index_doc_before_legacy_fallback() -> None: resolver = PatentOpenAlexMappingResolver( @@ -100,3 +113,45 @@ def test_filter_uses_patent_topic_map_from_resolver() -> None: patent_topic_map=topic_map, ) assert len(filtered) == 1 + + +def test_resolve_topics_for_patents_preloads_documents_in_one_batch() -> None: + 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": [], + }, + "C07C": { + "ipc_level": "subclass", + "ipc_symbol": "C07C", + "topic_matches": [ + { + "topic_id": "https://openalex.org/T11111", + "topic_display_name": "Organic chemistry", + } + ], + "keyword_matches": [], + }, + } + ) + resolver = PatentOpenAlexMappingResolver(client=client, use_elasticsearch=True) + patents = [ + model.PatentEntry(patent_id="EP1", source="EPO", ipc=["H01L 21/02"]), + model.PatentEntry(patent_id="EP2", source="EPO", ipc=["C07C 31/20"]), + model.PatentEntry(patent_id="US1", source="USPTO", ipc=["H01L 27/04"]), + ] + + topic_map = asyncio.run(resolver.resolve_topics_for_patents(patents)) + + assert client.lookup_ids_calls == 1 + assert client.lookup_symbol_calls == 0 + assert len(topic_map) == 3 + assert all(topics for topics in topic_map.values()) diff --git a/webapp/src/app/api/model/patentsByKeywordsResponse.ts b/webapp/src/app/api/model/patentsByKeywordsResponse.ts index 8af22a4b..538f553d 100644 --- a/webapp/src/app/api/model/patentsByKeywordsResponse.ts +++ b/webapp/src/app/api/model/patentsByKeywordsResponse.ts @@ -19,6 +19,9 @@ export interface PatentsByKeywordsRequest { export interface KeywordPatentMatch { patent: PatentEntry; match_score: number; + ipc_score: number; + topic_score: number; + text_score: number; matched_keywords?: string[]; matched_ipc_symbols?: string[]; } 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 a2649375..0481a3b9 100644 --- a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html +++ b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html @@ -1,132 +1,160 @@ -@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)) { - - - - - - - } - -
PatentScoreQuelleJahr
- {{ item.patent.title ?? item.patent.patent_id }} - {{ formatScore(item.match_score) }} - - {{ item.patent.source }} - - {{ item.patent.publication_year ?? '-' }}
- - @if (hasPagination()) { - - } -
- - @if (selectedMatch(); as match) { -
-

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

-
-
- Match-Score - {{ formatScore(match.match_score) }} -
-
- Gematchte Keywords - {{ - formatMatchList(match.matched_keywords) - }} -
-
- Gematchte IPC/CPC - {{ - formatMatchList(match.matched_ipc_symbols) - }} -
-
- Quelle - - - {{ match.patent.source }} - - -
-
- Patent-Nr. - {{ match.patent.patent_id }} -
-
- Datum - {{ - formatDate(match.patent.publication_date) - }} -
- @if (getPublicationStageLabel(match.patent); as stageLabel) { -
- Publikationsstufe - {{ stageLabel }} -
- } -
- - -
- } -
-
-} +@if (loading()) { +
+ +

Lade passende Patente...

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

Fehler beim Laden der Patente.

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

Keine passenden Patente gefunden.

+
+} @else { +
+ + +
+
+ + + + + + + + + + + @for (item of pagedMatches(); track trackMatch($index, item)) { + + + + + + + } + +
PatentScoreQuelleJahr
+ {{ item.patent.title ?? item.patent.patent_id }} + {{ formatScore(item.match_score) }} + + {{ item.patent.source }} + + {{ item.patent.publication_year ?? '-' }}
+ + @if (hasPagination()) { + + } +
+ + @if (selectedMatch(); as match) { +
+

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

+
+
+ Match-Score + {{ formatScore(match.match_score) }} +
+
+ Gematchte Keywords + {{ + formatMatchList(match.matched_keywords) + }} +
+
+ Gematchte IPC/CPC + {{ + formatMatchList(match.matched_ipc_symbols) + }} +
+
+ Quelle + + + {{ match.patent.source }} + + +
+
+ Patent-Nr. + {{ match.patent.patent_id }} +
+
+ Datum + {{ + formatDate(match.patent.publication_date) + }} +
+ @if (getPublicationStageLabel(match.patent); as stageLabel) { +
+ Publikationsstufe + {{ stageLabel }} +
+ } +
+ + +
+ } +
+
+} + + +
+

Passende Patente

+
+ @if (matches().length > 0) { + + } + + @if (showReload()) { + + } +
+
+
diff --git a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.scss b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.scss index d700ff61..ae2481f3 100644 --- a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.scss +++ b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.scss @@ -4,18 +4,41 @@ } .section-title { - margin: 0 0 16px; + margin: 0; font-size: 1.25rem; } .patents-container { - margin-top: 1.5rem; + margin-top: 0; padding: 16px; border-radius: 12px; background: #fff; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08); } +.patents-header { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 12px; + margin-bottom: 16px; +} + +.patents-header-actions { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: flex-end; + gap: 10px; + margin-left: auto; +} + +.reload-btn { + min-height: 40px; + white-space: nowrap; +} + .sort-control { display: inline-flex; align-items: center; @@ -145,6 +168,16 @@ } @media (max-width: 900px) { + .patents-header { + flex-direction: column; + align-items: stretch; + } + + .patents-header-actions { + margin-left: 0; + justify-content: space-between; + } + .patents-content { flex-direction: column; } 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 8b1b26d8..145d7ed3 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 @@ -1,103 +1,114 @@ -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'); - selectedMatch = 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.selectedMatch.set(null); - } - - setPage(page: number): void { - this.selectedPage.set(Math.min(Math.max(page, 1), this.pageCount())); - } - - selectMatch(item: KeywordPatentMatch): void { - this.selectedMatch.set(item); - } - - openDetail(): void { - const match = this.selectedMatch(); - if (!match) return; - void this.router.navigate(['/patent', match.patent.patent_id]); - } - - formatDate(date: string | null | undefined): string { - return formatPatentDate(date); - } - - getPublicationStageLabel(patent: PatentEntry): string | null { - return getPublicationStageLabel(patent); - } - - formatScore(score: number | null | undefined): string { - if (score == null || Number.isNaN(score)) { - return '-'; - } - return score.toFixed(2); - } - - formatMatchList(values: string[] | null | undefined): string { - if (!values || values.length === 0) { - return '-'; - } - return values.join(', '); - } - - trackMatch(_index: number, item: KeywordPatentMatch): string { - const patent = item.patent; - return [ - patent.source, - patent.patent_id, - patent.publication_date ?? '', - patent.kind ?? patent.application_type ?? '', - item.match_score, - ].join('|'); - } -} +import { NgTemplateOutlet } from '@angular/common'; +import { Component, input, output, signal } from '@angular/core'; +import { MatButtonModule } from '@angular/material/button'; +import { MatIconModule } from '@angular/material/icon'; +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', + imports: [NgTemplateOutlet, MatButtonModule, MatIconModule], + templateUrl: './keywords-patents.component.html', + styleUrl: './keywords-patents.component.scss', +}) +export class KeywordsPatentsComponent { + readonly matches = input([]); + readonly loading = input(false); + readonly error = input(false); + readonly showReload = input(false); + readonly reloadDisabled = input(false); + readonly reload = output(); + + activeFilter = signal('all'); + selectedMatch = 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.selectedMatch.set(null); + } + + setPage(page: number): void { + this.selectedPage.set(Math.min(Math.max(page, 1), this.pageCount())); + } + + selectMatch(item: KeywordPatentMatch): void { + this.selectedMatch.set(item); + } + + openDetail(): void { + const match = this.selectedMatch(); + if (!match) return; + void this.router.navigate(['/patent', match.patent.patent_id]); + } + + onReload(): void { + this.reload.emit(); + } + + formatDate(date: string | null | undefined): string { + return formatPatentDate(date); + } + + getPublicationStageLabel(patent: PatentEntry): string | null { + return getPublicationStageLabel(patent); + } + + formatScore(score: number | null | undefined): string { + if (score == null || Number.isNaN(score)) { + return '-'; + } + return score.toFixed(2); + } + + formatMatchList(values: string[] | null | undefined): string { + if (!values || values.length === 0) { + return '-'; + } + return values.join(', '); + } + + trackMatch(_index: number, item: KeywordPatentMatch): string { + const patent = item.patent; + return [ + patent.source, + patent.patent_id, + patent.publication_date ?? '', + patent.kind ?? patent.application_type ?? '', + item.match_score, + ].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 de7b6a82..a55164f9 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.html +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.html @@ -396,25 +396,8 @@ show_chart Visualisierung - - - - @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 8fd54f67..0d8e0958 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.scss +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.scss @@ -460,19 +460,13 @@ mat-button-toggle-group { } .search-btn, -.visualize-btn, -.patents-btn { +.visualize-btn { min-width: 220px; min-height: $touch-target; align-self: center; white-space: nowrap; } -.patents-btn { - background: #0f766e !important; - color: #fff !important; -} - /* Tablet */ @media (max-width: $tablet) { .search-container { @@ -484,8 +478,7 @@ mat-button-toggle-group { } .search-btn, - .visualize-btn, - .patents-btn { + .visualize-btn { width: 100%; } } @@ -508,8 +501,7 @@ mat-button-toggle-group { } .search-btn, - .visualize-btn, - .patents-btn { + .visualize-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 088edbd0..3e62f012 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.ts +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.ts @@ -47,14 +47,9 @@ 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'; -import { DomSanitizer } from '@angular/platform-browser'; import { SearchResultsPayload } from './search-results/search-results-state.service'; +import { clearPatentsCache } from './patent-search.utils'; +import { DomSanitizer } from '@angular/platform-browser'; type InputMode = 'url' | 'text'; type KeywordCategory = 'broad' | 'coarse' | 'fine' | 'manual'; type KeywordView = 'llm' | 'topic'; @@ -81,7 +76,6 @@ type KeywordPatentLevel = 'broad' | 'coarse' | 'fine' | 'custom'; MatTooltipModule, A11yModule, NgTemplateOutlet, - KeywordsPatentsComponent, LoadingComponent, MatSlideToggleModule, MatSliderModule, @@ -97,7 +91,6 @@ 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, @@ -134,11 +127,6 @@ 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 topicMappingSearch = signal(false); readonly keywordsExist = computed( @@ -303,10 +291,7 @@ 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); + clearPatentsCache(); this.websocketService.close(); this.isExtracting.set(false); this.loadingNewKeyword.set(false); @@ -522,12 +507,7 @@ 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 + clearPatentsCache(); const manualSet = new Set(this.getKeywordLabels(this.manualKeywords())); this.selectedKeywords.set( this.selectedKeywords().filter((k) => manualSet.has(k)), @@ -630,11 +610,11 @@ export class KeywordsSearchComponent { search(): void { this.showVisualization.set(false); - this.showPatents.set(false); const payload: SearchResultsPayload = { extractedKeywords: this.getSelectedExtractedKeywordEntries(), manualKeywords: this.getSelectedManualKeywordEntries(), + patentKeywordEntries: this.getSelectedPatentKeywordEntries(), keywords: this.selectedKeywords(), options: { softSearch: this.topicMappingSearch(), @@ -662,16 +642,9 @@ export class KeywordsSearchComponent { } 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 { @@ -1109,35 +1082,6 @@ export class KeywordsSearchComponent { } } - private loadMatchingPatents(): void { - const keywords = this.buildPatentSearchItems( - this.getSelectedPatentKeywordEntries(), - ); - 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 getSelectedPatentKeywordEntries(): Array<{ entry: KeywordEntryWithTopic; level: KeywordPatentLevel; @@ -1163,20 +1107,4 @@ export class KeywordsSearchComponent { .map((entry) => ({ entry, level: 'custom' as const })), ]; } - - private buildPatentSearchItems( - items: Array<{ entry: KeywordEntryWithTopic; level: KeywordPatentLevel }>, - ): KeywordPatentSearchItem[] { - return items - .map(({ entry, level }) => ({ - keyword: entry.llm_keyword.keyword, - keyword_level: level, - 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); - } } diff --git a/webapp/src/app/modules/keywords-search/patent-search.utils.ts b/webapp/src/app/modules/keywords-search/patent-search.utils.ts new file mode 100644 index 00000000..6aad52ec --- /dev/null +++ b/webapp/src/app/modules/keywords-search/patent-search.utils.ts @@ -0,0 +1,175 @@ +import { KeywordEntryWithTopic } from '../../api/model/keywordEntryWithTopic'; +import { + KeywordPatentMatch, + KeywordPatentSearchItem, +} from '../../api/model/patentsByKeywordsResponse'; +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[]; +} + +export function buildPatentSearchItems( + items: PatentKeywordEntry[], +): KeywordPatentSearchItem[] { + return items + .map(({ entry, level }) => ({ + keyword: entry.llm_keyword.keyword, + keyword_level: level, + 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); +} + +export function buildPatentSearchItemsFromPayload( + payload: SearchResultsPayload | null, +): KeywordPatentSearchItem[] { + if (!payload) return []; + + if (payload.patentKeywordEntries?.length) { + return buildPatentSearchItems(payload.patentKeywordEntries); + } + + const selected = new Set( + payload.keywords.map((keyword) => normalizeKeyword(keyword)), + ); + const isSelected = (entry: KeywordEntryWithTopic) => + selected.has(normalizeKeyword(entry.llm_keyword.keyword)); + + const fallbackEntries: PatentKeywordEntry[] = [ + ...payload.extractedKeywords + .filter(isSelected) + .map((entry) => ({ entry, level: 'coarse' as const })), + ...payload.manualKeywords + .filter(isSelected) + .map((entry) => ({ entry, level: 'custom' as const })), + ]; + + return buildPatentSearchItems(fallbackEntries); +} + +export function readPatentsCache(keywords: string[]): KeywordPatentMatch[] | null { + const raw = sessionStorage.getItem(PATENTS_CACHE_KEY); + if (!raw) return null; + + try { + const cache = JSON.parse(raw) as PatentsCache; + if (!sameKeywordSet(cache.keywords, keywords)) return null; + return cache.matches ?? []; + } catch { + sessionStorage.removeItem(PATENTS_CACHE_KEY); + return null; + } +} + +export function writePatentsCache( + keywords: string[], + matches: KeywordPatentMatch[], +): void { + try { + const cache: PatentsCache = { keywords, matches }; + 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))); +} + +export interface PatentScoreWeights { + ipc: number; + topic: number; + text: number; +} + +export const DEFAULT_PATENT_SCORE_WEIGHTS: PatentScoreWeights = { + ipc: 0.6, + topic: 0.25, + text: 0.15, +}; + +export function normalizePatentScoreWeights( + raw: Record, +): PatentScoreWeights { + const ipc = raw['ipc'] ?? DEFAULT_PATENT_SCORE_WEIGHTS.ipc; + const topic = raw['topic'] ?? DEFAULT_PATENT_SCORE_WEIGHTS.topic; + const text = raw['text'] ?? DEFAULT_PATENT_SCORE_WEIGHTS.text; + const sum = ipc + topic + text; + if (sum <= 0) { + return { ...DEFAULT_PATENT_SCORE_WEIGHTS }; + } + return { ipc: ipc / sum, topic: topic / sum, text: text / sum }; +} + +export function computePatentMatchScore( + match: Pick, + weights: PatentScoreWeights, +): number { + return ( + Math.round( + (weights.ipc * match.ipc_score + + weights.topic * match.topic_score + + weights.text * match.text_score) * + 10000, + ) / 10000 + ); +} + +export function applyPatentScoreWeights( + matches: KeywordPatentMatch[], + weights: PatentScoreWeights, +): KeywordPatentMatch[] { + return [...matches] + .map((match) => ({ + ...match, + match_score: computePatentMatchScore(match, weights), + })) + .sort((a, b) => { + const scoreDiff = b.match_score - a.match_score; + if (scoreDiff !== 0) { + return scoreDiff; + } + + const dateA = a.patent.publication_date ?? ''; + const dateB = b.patent.publication_date ?? ''; + if (dateA !== dateB) { + return dateB.localeCompare(dateA); + } + + return a.patent.patent_id.localeCompare(b.patent.patent_id); + }); +} + +function hasPatentComponentScores(match: KeywordPatentMatch): boolean { + return ( + typeof match.ipc_score === 'number' && + typeof match.topic_score === 'number' && + typeof match.text_score === 'number' + ); +} + +export function canReweightPatentMatches(matches: KeywordPatentMatch[]): boolean { + return matches.length > 0 && matches.every(hasPatentComponentScores); +} 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 0073d8fd..87d668f6 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 @@ -1,22 +1,12 @@
- - - groups -

Patentenliste

-

- Die aktuelle Gewichtung ist unter normalized verfügbar. -

-
-
- + +
+ +
diff --git a/webapp/src/app/modules/keywords-search/search-results/patents-results/patents-results.component.scss b/webapp/src/app/modules/keywords-search/search-results/patents-results/patents-results.component.scss index ffeea20d..adf24e22 100644 --- a/webapp/src/app/modules/keywords-search/search-results/patents-results/patents-results.component.scss +++ b/webapp/src/app/modules/keywords-search/search-results/patents-results/patents-results.component.scss @@ -3,22 +3,22 @@ ============================================================ */ .result-layout { display: grid; - grid-template-columns: minmax(300px, 420px) 1fr; + grid-template-columns: minmax(280px, 360px) minmax(0, 1fr); grid-template-areas: 'summary results'; gap: 0.75rem; align-items: start; } -.search-summary-card { +.weights-card { grid-area: summary; } .results-card { grid-area: results; + min-width: 0; } -.search-summary-card, -.results-card { +.weights-card { background: var(--sg-surface, #ffffff); border: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.12)); box-shadow: none; @@ -27,3 +27,12 @@ padding: 0.75rem; } } + +@media (max-width: 960px) { + .result-layout { + grid-template-columns: 1fr; + grid-template-areas: + 'summary' + 'results'; + } +} 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 659c9064..e18dde3c 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,112 +1,160 @@ -import { Component, inject, signal } from '@angular/core'; +import { Component, inject, OnInit, signal } from '@angular/core'; +import { MatButtonModule } from '@angular/material/button'; import { MatCardModule } from '@angular/material/card'; import { MatIconModule } from '@angular/material/icon'; +import { PatentsService } from '../../../../api/api/patents.service'; +import { KeywordPatentMatch } from '../../../../api/model/patentsByKeywordsResponse'; import { WeightMap, WeightSliderOption, WeightsSlidersComponent, WeightsSlidersValue, } from '../../../../shared/ui/weights-sliders/weights-sliders.component'; +import { KeywordsPatentsComponent } from '../../keywords-patents/keywords-patents.component'; +import { + applyPatentScoreWeights, + buildPatentSearchItemsFromPayload, + canReweightPatentMatches, + clearPatentsCache, + DEFAULT_PATENT_SCORE_WEIGHTS, + normalizePatentScoreWeights, + readPatentsCache, + writePatentsCache, +} from '../../patent-search.utils'; import { SearchResultsStateService } from '../search-results-state.service'; @Component({ selector: 'app-patents-results', - imports: [MatCardModule, MatIconModule, WeightsSlidersComponent], + imports: [ + MatCardModule, + MatIconModule, + MatButtonModule, + WeightsSlidersComponent, + KeywordsPatentsComponent, + ], templateUrl: './patents-results.component.html', styleUrl: './patents-results.component.scss', }) -export class KeywordsToPatentsResultsComponent { - // injects the state set by the parent route — no duplicate parsing here - private readonly state = inject(SearchResultsStateService); +export class KeywordsToPatentsResultsComponent implements OnInit { + protected readonly state = inject(SearchResultsStateService); + private readonly patentsService = inject(PatentsService); - readonly defaultWeights: WeightMap = { - param1: 0.33, - param2: 0.33, - param3: 0.34, - }; + readonly defaultWeights: WeightMap = { ...DEFAULT_PATENT_SCORE_WEIGHTS }; readonly weightOptions: WeightSliderOption[] = [ { - key: 'param1', - label: 'Parameter 1', - icon: 'workspace_premium', - description: 'Gewichtet Parameter 1.', - defaultValue: 0.5, - queryParamName: 'wParam1', + key: 'ipc', + label: 'IPC/CPC-Match', + icon: 'category', + description: + 'Gewichtet die Übereinstimmung der Patent-Klassifikation (IPC/CPC) mit den Keywords.', + defaultValue: DEFAULT_PATENT_SCORE_WEIGHTS.ipc, + queryParamName: 'wIpc', }, { - key: 'param2', - label: 'Parameter 2', - icon: 'workspace_premium', - description: 'Gewichtet Parameter 2.', - defaultValue: 0.5, - queryParamName: 'wParam2', + key: 'topic', + label: 'OpenAlex-Topic', + icon: 'hub', + description: + 'Gewichtet die thematische Übereinstimmung über OpenAlex-Topics und Fachgebiete.', + defaultValue: DEFAULT_PATENT_SCORE_WEIGHTS.topic, + queryParamName: 'wTopic', }, { - key: 'param3', - label: 'Parameter 3', - icon: 'workspace_premium', - description: 'Gewichtet Parameter 3.', - defaultValue: 0.5, - queryParamName: 'wParam3', + key: 'text', + label: 'Text-Match', + icon: 'article', + description: + 'Gewichtet Treffer der Keywords im Patenttitel und in der Zusammenfassung.', + defaultValue: DEFAULT_PATENT_SCORE_WEIGHTS.text, + queryParamName: 'wText', }, ]; readonly currentWeights = signal({ raw: this.defaultWeights, - normalized: { - param1: 0.33, - param2: 0.33, - param3: 0.34, - }, - rawSum: 2.5, + normalized: { ...DEFAULT_PATENT_SCORE_WEIGHTS }, + rawSum: 1, normalizedSum: 1, valid: true, }); - readonly projects = signal([]); // placeholder until the results service lands + readonly patentMatches = signal([]); + readonly loadingPatents = signal(false); + readonly patentsError = signal(false); - private hasLoadedInitial = false; + private readonly patentMatchesBase = signal([]); + + ngOnInit(): void { + const cached = readPatentsCache(this.state.keywords()); + if (cached) { + this.setPatentMatches(cached); + return; + } + + this.loadMatchingPatents(); + } onWeightsChange(value: WeightsSlidersValue): void { this.currentWeights.set(value); - - // fires once with the query-param-aware initial state — use it to load - if (!this.hasLoadedInitial) { - this.hasLoadedInitial = true; - this.loadprojects(); - } } onApplyWeights(value: WeightsSlidersValue): void { this.currentWeights.set(value); - this.loadprojects(); + if (!canReweightPatentMatches(this.patentMatchesBase())) { + this.reloadPatents(); + return; + } + this.updateDisplayedMatches(); } - private loadprojects(): void { - const weights = this.currentWeights(); + reloadPatents(): void { + clearPatentsCache(); + this.loadMatchingPatents(); + } - const requestPayload = { - manualKeywords: this.state.manualKeywords(), - extractedKeywords: this.state.extractedKeywords(), - keywords: this.state.keywords(), - softSearch: this.state.softSearch(), - weights: { - raw: weights.raw, - normalized: weights.normalized, + private loadMatchingPatents(): void { + const keywords = buildPatentSearchItemsFromPayload(this.state.payload()); + if (keywords.length === 0) { + this.setPatentMatches([]); + return; + } + + this.loadingPatents.set(true); + this.patentsError.set(false); + + this.patentsService.getPatentsByKeywords({ keywords }).subscribe({ + next: (response) => { + this.setPatentMatches(response.patents ?? []); + this.loadingPatents.set(false); }, - }; + error: (error) => { + console.error('Patent search failed:', error); + this.setPatentMatches([]); + this.patentsError.set(true); + this.loadingPatents.set(false); + }, + }); + } - console.log(requestPayload); + private setPatentMatches(matches: KeywordPatentMatch[]): void { + this.patentMatchesBase.set(matches); + this.updateDisplayedMatches(); + writePatentsCache(this.state.keywords(), this.patentMatchesBase()); + } - /** - * TODO: - * this.projectsService.searchprojects(requestPayload).subscribe({ - * next: results => this.projects.set(results), - * error: error => console.error(error), - * }); - */ + private updateDisplayedMatches(): void { + const base = this.patentMatchesBase(); + if (!canReweightPatentMatches(base)) { + this.patentMatches.set(base); + return; + } + + const weights = normalizePatentScoreWeights( + this.currentWeights().normalized, + ); + this.patentMatches.set(applyPatentScoreWeights(base, weights)); } } diff --git a/webapp/src/app/modules/keywords-search/search-results/search-results-state.service.ts b/webapp/src/app/modules/keywords-search/search-results/search-results-state.service.ts index b5b91234..0b991354 100644 --- a/webapp/src/app/modules/keywords-search/search-results/search-results-state.service.ts +++ b/webapp/src/app/modules/keywords-search/search-results/search-results-state.service.ts @@ -1,10 +1,18 @@ import { Injectable, computed, signal } from '@angular/core'; import { KeywordEntryWithTopic } from '../../../api/model/keywordEntryWithTopic'; +export type KeywordPatentLevel = 'broad' | 'coarse' | 'fine' | 'custom'; + +export interface PatentKeywordEntry { + entry: KeywordEntryWithTopic; + level: KeywordPatentLevel; +} + export interface SearchResultsPayload { extractedKeywords: KeywordEntryWithTopic[]; manualKeywords: KeywordEntryWithTopic[]; keywords: string[]; + patentKeywordEntries?: PatentKeywordEntry[]; options: { softSearch: boolean; }; diff --git a/webapp/src/app/modules/keywords-search/search-results/search-results.component.ts b/webapp/src/app/modules/keywords-search/search-results/search-results.component.ts index e425de4c..5f853b57 100644 --- a/webapp/src/app/modules/keywords-search/search-results/search-results.component.ts +++ b/webapp/src/app/modules/keywords-search/search-results/search-results.component.ts @@ -130,6 +130,9 @@ export class KeywordsSearchResultsComponent { options: { softSearch }, extractedKeywords: cacheMatches ? cached!.extractedKeywords : [], manualKeywords: cacheMatches ? cached!.manualKeywords : [], + patentKeywordEntries: cacheMatches + ? cached!.patentKeywordEntries + : undefined, }); }); } @@ -202,6 +205,7 @@ export class KeywordsSearchResultsComponent { extractedKeywords: maybePayload.extractedKeywords ?? [], manualKeywords: maybePayload.manualKeywords ?? [], keywords: maybePayload.keywords ?? [], + patentKeywordEntries: maybePayload.patentKeywordEntries, options: { softSearch: maybePayload.options?.softSearch ?? false, }, -- 2.56.1 From 8c981be503f984a9d0df9c404f772d834acc1c42 Mon Sep 17 00:00:00 2001 From: Khuder Khalti Date: Tue, 14 Jul 2026 20:30:25 +0200 Subject: [PATCH 2/7] fix(patents): fix broken ES doc lookup for slash-containing ids and batch resolver requests to avoid 10k result-window errors Co-Authored-By: Claude Sonnet 5 --- .../patents_openalex_keywords/client.py | 32 +++++++++++------- .../patents_openalex_keywords/resolver.py | 6 ++++ .../patents_openalex_keywords/test_client.py | 33 ++++++++++++++++++- 3 files changed, 59 insertions(+), 12 deletions(-) diff --git a/service/src/main/inse/patents/patents_openalex_keywords/client.py b/service/src/main/inse/patents/patents_openalex_keywords/client.py index d60c9b42..e73b006c 100644 --- a/service/src/main/inse/patents/patents_openalex_keywords/client.py +++ b/service/src/main/inse/patents/patents_openalex_keywords/client.py @@ -17,6 +17,7 @@ from inse.patents.patents_openalex_keywords.mapping import ( logger = logging.getLogger(__name__) _LEVEL_LOOKUP_ORDER = ("subgroup", "group", "subclass", "class", "section") +_MAX_SEARCH_WINDOW = 10_000 # Elasticsearch's default index.max_result_window def candidate_doc_ids(symbol: str) -> list[str]: @@ -179,26 +180,35 @@ class PatentsOpenAlexKeywordsClient: return hits[0].get("_source") if hits else None async def lookup_ids(self, doc_ids: list[str]) -> dict[str, dict[str, Any]]: - """Resolves multiple doc ids in a single _search request (id -> _source).""" + """Resolves multiple doc ids in as few _search requests as possible + (id -> _source). Chunked to stay under Elasticsearch's + index.max_result_window (10000) — a single query with more ids than + that fails with a 400 "Result window is too large" error, which hit + real org_patents rebuilds resolving topics for many patents at once. + """ unique_ids = list(dict.fromkeys(doc_ids)) if not unique_ids: return {} + results: dict[str, dict[str, Any]] = {} async with httpx.AsyncClient( base_url=self.base_url, timeout=self.timeout, transport=self.transport, ) as client: - response = await client.post( - f"/{PATENTS_OPENALEX_KEYWORDS_INDEX}/_search", - headers=self._headers(), - json={"size": len(unique_ids), "query": {"ids": {"values": unique_ids}}}, - ) - if response.status_code == 404: - return {} - response.raise_for_status() - hits = response.json().get("hits", {}).get("hits", []) - return {hit["_id"]: hit.get("_source", {}) for hit in hits} + for start in range(0, len(unique_ids), _MAX_SEARCH_WINDOW): + chunk = unique_ids[start : start + _MAX_SEARCH_WINDOW] + response = await client.post( + f"/{PATENTS_OPENALEX_KEYWORDS_INDEX}/_search", + headers=self._headers(), + json={"size": len(chunk), "query": {"ids": {"values": chunk}}}, + ) + if response.status_code == 404: + continue + response.raise_for_status() + hits = response.json().get("hits", {}).get("hits", []) + results.update({hit["_id"]: hit.get("_source", {}) for hit in hits}) + return results async def lookup_symbol(self, symbol: str) -> dict[str, Any] | None: ordered_ids = candidate_doc_ids(symbol) diff --git a/service/src/main/inse/patents/patents_openalex_keywords/resolver.py b/service/src/main/inse/patents/patents_openalex_keywords/resolver.py index 31c70225..8f7bfddc 100644 --- a/service/src/main/inse/patents/patents_openalex_keywords/resolver.py +++ b/service/src/main/inse/patents/patents_openalex_keywords/resolver.py @@ -216,6 +216,12 @@ class PatentOpenAlexMappingResolver: self, patents: list[model.PatentEntry], ) -> dict[str, list[MappedOpenAlexTopic]]: + """Resolves topics for many patents at once via a single batched + Elasticsearch request, instead of the sequential per-patent / + per-code lookups in resolve_mapped_topics_for_patent(). This matters + a lot when called for many patents at once (e.g. building + org_patents across thousands of authors) — one request per code, + repeated per patent, previously added minutes of latency.""" from inse.patents.common.parsing import patent_map_key if not patents: diff --git a/service/src/main/inse/patents/patents_openalex_keywords/test_client.py b/service/src/main/inse/patents/patents_openalex_keywords/test_client.py index ec74f4c2..bfe6afea 100644 --- a/service/src/main/inse/patents/patents_openalex_keywords/test_client.py +++ b/service/src/main/inse/patents/patents_openalex_keywords/test_client.py @@ -3,7 +3,10 @@ import json import httpx import pytest -from inse.patents.patents_openalex_keywords.client import PatentsOpenAlexKeywordsClient +from inse.patents.patents_openalex_keywords.client import ( + _MAX_SEARCH_WINDOW, + PatentsOpenAlexKeywordsClient, +) from inse.patents.patents_openalex_keywords.mapping import PATENTS_OPENALEX_KEYWORDS_INDEX @@ -97,6 +100,34 @@ async def test_lookup_symbol_resolves_via_a_single_batched_request(): assert doc == {"ipc_label": "match"} +@pytest.mark.anyio +async def test_lookup_ids_chunks_requests_over_max_search_window(): + """A single _search with more than index.max_result_window (10000) ids + fails with a 400 "Result window is too large" error — confirmed against + the real cluster. lookup_ids() must split large id lists into chunks + that each stay within that limit.""" + captured_sizes: list[int] = [] + + def handler(request: httpx.Request) -> httpx.Response: + body = json.loads(request.content) + values = body["query"]["ids"]["values"] + captured_sizes.append(len(values)) + hits = [{"_id": doc_id, "_source": {"ipc_label": doc_id}} for doc_id in values[:1]] + return httpx.Response(200, json={"hits": {"hits": hits}}) + + client = PatentsOpenAlexKeywordsClient( + api_key="test-key", + transport=httpx.MockTransport(handler), + ) + doc_ids = [f"subgroup:X{i}" for i in range(_MAX_SEARCH_WINDOW + 500)] + + result = await client.lookup_ids(doc_ids) + + assert captured_sizes == [_MAX_SEARCH_WINDOW, 500] + assert all(size <= _MAX_SEARCH_WINDOW for size in captured_sizes) + assert len(result) == 2 + + @pytest.mark.anyio async def test_lookup_symbol_prefers_more_specific_level_when_multiple_match(): def handler(request: httpx.Request) -> httpx.Response: -- 2.56.1 From 86d65b2d5a9c6e0d176e2f2c67b3748ba3a09cc7 Mon Sep 17 00:00:00 2001 From: Khuder Khalti Date: Wed, 15 Jul 2026 11:12:58 +0200 Subject: [PATCH 3/7] feat(patents): corroborate ambiguous inventor-name matches via shared OpenAlex topics Co-Authored-By: Claude Sonnet 5 --- service/README.md | 5 +- service/scripts/index_org_patents.py | 5 +- service/src/main/inse/patents/org/logic.py | 74 ++++++++++++++++- .../src/main/inse/patents/org/test_logic.py | 82 ++++++++++++++++++- 4 files changed, 161 insertions(+), 5 deletions(-) diff --git a/service/README.md b/service/README.md index 25961c24..7d6c4964 100644 --- a/service/README.md +++ b/service/README.md @@ -25,7 +25,10 @@ OpenAlex authors, searches EPO/USPTO for patents matched via institution assigne and/or inventor name, and reindexes. Each patent is tagged with a `match_type` (`institution`, `name`, or `both`, the latter being highest confidence). For common inventor names, a name match is only kept if the assignee is the institution itself or -the person, to avoid pulling in unrelated patents via a shared name. +the person, or if the patent's IPC/CPC-derived OpenAlex topics share at least two exact +topic IDs with the author's own research topics — a single shared topic isn't reliable +enough, since broad, common topics coincidentally show up on unrelated patents and +profiles alike. This avoids pulling in unrelated patents via a shared name. ```bash python scripts/index_org_patents.py --institution-id diff --git a/service/scripts/index_org_patents.py b/service/scripts/index_org_patents.py index f315f2f9..cd057117 100644 --- a/service/scripts/index_org_patents.py +++ b/service/scripts/index_org_patents.py @@ -4,7 +4,10 @@ index_org_patents.py — Build the org_patents Elasticsearch index for one insti Fetches all OpenAlex authors affiliated with the institution, searches EPO/USPTO for patents matched via institution assignee and/or author name (match_type: "institution", -"name", or "both"), deletes existing documents for the institution, and reindexes. +"name", or "both"), deletes existing documents for the institution, and reindexes. For +common inventor names, a name match is only kept with institution/assignee evidence or +at least two shared OpenAlex topic IDs between the patent (via IPC/CPC) and the +author's own research topics. Usage: python scripts/index_org_patents.py --institution-id diff --git a/service/src/main/inse/patents/org/logic.py b/service/src/main/inse/patents/org/logic.py index c6cc79e4..574f6a33 100644 --- a/service/src/main/inse/patents/org/logic.py +++ b/service/src/main/inse/patents/org/logic.py @@ -17,6 +17,7 @@ from inse.patents.authors.identity import ( patent_institution_match, patent_personal_assignee_match, ) +from inse.patents.authors.ipc_openalex_mapping import normalize_openalex_id from inse.patents.authors.name_matching import filter_patents_by_author_name from inse.patents.common.elastic_search_client import MissingApiKeyError from inse.patents.common.model import PatentEntry @@ -27,10 +28,12 @@ from inse.patents.common.parsing import ( parse_epo_hits, parse_uspto_hits, patent_dedup_key, + patent_map_key, ) from inse.patents.institutions.logic import get_patents_by_institution_id from inse.patents.ipc_search_client import IpcSearchClient from inse.patents.patents_openalex_keywords.client import PatentsOpenAlexKeywordsClient +from inse.patents.patents_openalex_keywords.resolver import PatentOpenAlexMappingResolver from inse.patents.org.elastic_search_client import ( OrgPatentsSearchClient, fetch_authors_by_institution_name, @@ -218,6 +221,52 @@ def org_patent_to_es_document(patent: OrgPatentEntry) -> dict: } +MIN_CORROBORATING_TOPIC_OVERLAP = 2 + + +def topic_corroborated_patents( + patents: list[PatentEntry], + author: Author, + patent_topic_map: dict[str, list], +) -> list[PatentEntry]: + """Keeps only patents whose IPC/CPC-derived OpenAlex topics share at + least MIN_CORROBORATING_TOPIC_OVERLAP exact topic IDs with the author's + own research topics — used to disambiguate common inventor names where + institution/self-assignee matching alone isn't enough. + + Requiring a single shared topic ID was still too loose: broad, + genuinely common topics (e.g. "Image Processing Techniques") show up on + many unrelated patents *and* on many unrelated researchers' profiles, so + one coincidental overlap doesn't mean much (confirmed against a real + org_patents rebuild: match_type=name patents still ballooned to ~2000). + Two independent topic overlaps happening by chance is far less likely, + while a patent genuinely invented by the author would typically share + more than one topic with their own body of work. If the author has no + topic profile at all, there is nothing to corroborate against. + """ + author_topic_ids = { + normalize_openalex_id(topic.id) + for topic in (author.topics or []) + if topic.id + } + author_topic_ids.discard(None) + if not author_topic_ids: + return [] + + kept: list[PatentEntry] = [] + for patent in patents: + mapped_topics = patent_topic_map.get(patent_map_key(patent), []) + patent_topic_ids = { + normalize_openalex_id(topic.topic_id) + for topic in mapped_topics + if topic.topic_id + } + patent_topic_ids.discard(None) + if len(patent_topic_ids & author_topic_ids) >= MIN_CORROBORATING_TOPIC_OVERLAP: + kept.append(patent) + return kept + + async def _search_patents_by_author( author: Author, institution_name: str | None, @@ -273,13 +322,34 @@ async def _search_patents_by_author( if is_ambiguous: # Common names (Zhang, Li, Wang): only keep if the assignee matches the # institution we're building this index for (not any institution from - # the author's whole affiliation history) or the person themselves. + # the author's whole affiliation history), the person themselves, or + # their own OpenAlex research topics share at least + # MIN_CORROBORATING_TOPIC_OVERLAP exact topic IDs with the patent's + # IPC/CPC-derived topics. inst_names = [institution_name] if institution_name else [] - return [ + strong_identity_matched = [ p for p in name_matched if patent_institution_match(p, inst_names) or patent_personal_assignee_match(p, author_name) ] + matched_keys = {patent_dedup_key(p) for p in strong_identity_matched} + remaining = [p for p in name_matched if patent_dedup_key(p) not in matched_keys] + if not remaining: + return strong_identity_matched + + topic_matched: list[PatentEntry] = [] + try: + resolver = PatentOpenAlexMappingResolver() + patent_topic_map = await resolver.resolve_topics_for_patents(remaining) + topic_matched = topic_corroborated_patents(remaining, author, patent_topic_map) + except Exception: + logger.warning( + "OpenAlex topic corroboration failed for ambiguous name %s", + author_name, + exc_info=True, + ) + + return strong_identity_matched + topic_matched else: return name_matched diff --git a/service/src/main/inse/patents/org/test_logic.py b/service/src/main/inse/patents/org/test_logic.py index bb0313ef..26588f43 100644 --- a/service/src/main/inse/patents/org/test_logic.py +++ b/service/src/main/inse/patents/org/test_logic.py @@ -1,11 +1,15 @@ +from inse.models.openalex.author import Author +from inse.models.openalex.work_topic import WorkTopic +from inse.patents.authors.ipc_openalex_mapping import MappedOpenAlexTopic from inse.patents.common.model import PatentEntry +from inse.patents.common.parsing import patent_map_key from inse.patents.org.logic import ( merge_org_patents, org_patent_document_id, resolve_match_type, + topic_corroborated_patents, ) from inse.patents.org.model import MatchedAuthor -from inse.models.openalex.author import Author def _patent( @@ -27,6 +31,14 @@ def _author(author_id: str, name: str) -> Author: ) +def _author_with_topics(author_id: str, name: str, topic_ids: list[str]) -> Author: + return Author( + id=f"https://openalex.org/{author_id}", + display_name=name, + topics=[WorkTopic(id=tid, display_name=f"Topic {tid}") for tid in topic_ids], + ) + + def test_resolve_match_type() -> None: assert resolve_match_type(True, True) == "both" assert resolve_match_type(True, False) == "institution" @@ -102,3 +114,71 @@ def test_org_patent_document_id_is_stable() -> None: doc_id = org_patent_document_id("I62318514", patent) assert doc_id == "I62318514_EPO_EP1234567_20240101_A1" + + +def _mapped_topics(*topic_ids: str) -> list[MappedOpenAlexTopic]: + return [ + MappedOpenAlexTopic(topic_id=tid, topic_display_name=f"Topic {tid}") + for tid in topic_ids + ] + + +def test_topic_corroborated_patents_keeps_two_overlapping_topics() -> None: + author = _author_with_topics( + "A123", "Wei Zhang", + ["https://openalex.org/T1", "https://openalex.org/T2"], + ) + patent = _patent("EP1") + patent_topic_map = { + patent_map_key(patent): _mapped_topics( + "https://openalex.org/T1", "https://openalex.org/T2", "https://openalex.org/T3" + ), + } + + result = topic_corroborated_patents([patent], author, patent_topic_map) + + assert result == [patent] + + +def test_topic_corroborated_patents_drops_single_coincidental_overlap() -> None: + """A single shared topic isn't enough — broad, common topics show up on + many unrelated patents and profiles by coincidence. Confirmed against a + real org_patents rebuild where single-topic matching still let through + ~2000 mostly-unrelated "name"-matched patents.""" + author = _author_with_topics( + "A123", "Xin Wang", + ["https://openalex.org/T1", "https://openalex.org/T9"], + ) + patent = _patent("EP2") + patent_topic_map = { + patent_map_key(patent): _mapped_topics( + "https://openalex.org/T1", "https://openalex.org/T2", "https://openalex.org/T3" + ), + } + + result = topic_corroborated_patents([patent], author, patent_topic_map) + + assert result == [] + + +def test_topic_corroborated_patents_drops_patent_without_mapped_topics() -> None: + author = _author_with_topics("A123", "Wei Zhang", ["https://openalex.org/T1"]) + patent = _patent("EP3") + + result = topic_corroborated_patents([patent], author, {}) + + assert result == [] + + +def test_topic_corroborated_patents_rejects_everything_without_author_topic_profile() -> None: + author = Author(id="https://openalex.org/A999", display_name="Wei Zhang") + patent = _patent("EP4") + patent_topic_map = { + patent_map_key(patent): _mapped_topics( + "https://openalex.org/T1", "https://openalex.org/T2" + ), + } + + result = topic_corroborated_patents([patent], author, patent_topic_map) + + assert result == [] -- 2.56.1 From 9254dcf115aee9ee28ffbf80987e25b94721bef4 Mon Sep 17 00:00:00 2001 From: taguesokoudjou Date: Wed, 15 Jul 2026 13:25:30 +0200 Subject: [PATCH 4/7] fix(patents): disambiguate author patents with patents_openalex_keywords index --- .../src/main/inse/patents/authors/identity.py | 44 ++++-- .../inse/patents/authors/test_identity.py | 24 +++- .../authors/test_ipc_openalex_mapping.py | 129 ++++++++++++++++-- .../main/inse/patents/authors/topic_filter.py | 59 ++++++-- 4 files changed, 217 insertions(+), 39 deletions(-) diff --git a/service/src/main/inse/patents/authors/identity.py b/service/src/main/inse/patents/authors/identity.py index 320ce506..e3496202 100644 --- a/service/src/main/inse/patents/authors/identity.py +++ b/service/src/main/inse/patents/authors/identity.py @@ -32,17 +32,19 @@ def is_ambiguous_name( openalex_full_name_count: int | None = None, openalex_last_name_count: int | None = None, ) -> bool: - """Decide whether a name is ambiguous using only internal project data. + """Decide whether a name is strictly ambiguous using internal project data. - A name is treated as ambiguous (and therefore handled strictly) when: + A name is treated as strictly ambiguous when: - it is a mononym / cannot be parsed into given + family name, or - - several authors in the local OpenAlex index share the exact name, or - - many authors in the local OpenAlex index share the family name, or - - the patent name search returns a very large number of hits. + - several authors in the local OpenAlex index share the exact full name. - Ambiguous names need a strong identity signal (institution/assignee or a - full given-name match with a matching research field) before a patent is - attributed to the person. + A frequent last name alone does **not** make a uniquely named author + strictly ambiguous (``openalex_full_name_count == 1``). In that case + personal-assignee identity can count when inventor and assignee both + match the full OpenAlex name. + + When the full-name count is unknown, last-name frequency and patent-hit + volume remain as safety fallbacks. """ parsed = parse_person_name(display_name) if parsed is None or parsed.is_single_token: @@ -54,6 +56,9 @@ def is_ambiguous_name( ): return True + if openalex_full_name_count == 1: + return False + if ( openalex_last_name_count is not None and openalex_last_name_count >= OPENALEX_LAST_NAME_COUNT_THRESHOLD @@ -105,6 +110,29 @@ def patent_institution_match( return False +def patent_personal_assignee_full_match( + patent: model.PatentEntry, + display_name: str, +) -> bool: + """True when a personal assignee matches the author's full given name.""" + if not display_name or not display_name.strip(): + return False + for assignee in patent.assignees: + if assignee and first_name_match_kind_for_person(assignee, display_name) == "full": + return True + return False + + +def patent_full_personal_identity_match( + patent: model.PatentEntry, + display_name: str, +) -> bool: + """Strong personal identity: full inventor name and full personal assignee.""" + if best_name_match_kind(patent, display_name) != "full": + return False + return patent_personal_assignee_full_match(patent, display_name) + + def patent_personal_assignee_match( patent: model.PatentEntry, display_name: str, diff --git a/service/src/main/inse/patents/authors/test_identity.py b/service/src/main/inse/patents/authors/test_identity.py index a4ac8a05..224bb19c 100644 --- a/service/src/main/inse/patents/authors/test_identity.py +++ b/service/src/main/inse/patents/authors/test_identity.py @@ -30,7 +30,7 @@ def test_full_name_collision_makes_name_ambiguous() -> None: ) -def test_last_name_collision_makes_name_ambiguous() -> None: +def test_last_name_collision_makes_name_ambiguous_without_full_name_count() -> None: assert ( is_ambiguous_name( "Christian Weber", @@ -43,7 +43,27 @@ def test_last_name_collision_makes_name_ambiguous() -> None: ) -def test_many_patent_hits_make_name_ambiguous() -> None: +def test_last_name_collision_not_ambiguous_when_full_name_unique() -> None: + assert ( + is_ambiguous_name( + "Pedro José Marrón", + openalex_full_name_count=1, + openalex_last_name_count=OPENALEX_LAST_NAME_COUNT_THRESHOLD, + patent_hit_count=PATENT_HIT_COUNT_THRESHOLD, + ) + is False + ) + + +def test_many_patent_hits_not_ambiguous_when_full_name_unique() -> None: + assert ( + is_ambiguous_name( + "Pedro José Marrón", + openalex_full_name_count=1, + patent_hit_count=PATENT_HIT_COUNT_THRESHOLD, + ) + is False + ) assert ( is_ambiguous_name("Christian Weber", patent_hit_count=PATENT_HIT_COUNT_THRESHOLD) is True diff --git a/service/src/main/inse/patents/authors/test_ipc_openalex_mapping.py b/service/src/main/inse/patents/authors/test_ipc_openalex_mapping.py index c7a7467f..c4b82d1a 100644 --- a/service/src/main/inse/patents/authors/test_ipc_openalex_mapping.py +++ b/service/src/main/inse/patents/authors/test_ipc_openalex_mapping.py @@ -11,8 +11,13 @@ from inse.patents.authors.ipc_openalex_mapping import ( patent_topics_match_author, resolve_mapped_topics_for_code, ) +from inse.patents.authors.identity import ( + patent_full_personal_identity_match, + patent_personal_assignee_full_match, +) from inse.patents.authors.topic_filter import filter_patents_by_ipc_topic_mapping from inse.patents.common import model +from inse.patents.common.parsing import patent_map_key def _author_with_topic( @@ -172,19 +177,12 @@ def test_filter_rejects_ambiguous_name_on_fuzzy_label_only_match() -> None: [tire_patent], author, is_ambiguous=True, - patent_topic_map={"USPTO:US12508845": [spurious_cardiac]}, + patent_topic_map={patent_map_key(tire_patent): [spurious_cardiac]}, ) assert filtered == [] -def test_filter_keeps_ambiguous_name_on_legacy_ipc_subclass_match() -> None: - custom = _custom_mapping() - custom["subclass"]["C07K"] = mapping_module.MappedOpenAlexTopic( - topic_id="https://openalex.org/T10158", - topic_display_name="Cancer Immunotherapy and Biomarkers", - ipc_level="subclass", - ipc_symbol="C07K", - ) +def test_filter_keeps_ambiguous_name_on_keywords_index_topic_match() -> None: author = _author_with_topic( "https://openalex.org/T10158", "Cancer Immunotherapy and Biomarkers", @@ -199,21 +197,124 @@ def test_filter_keeps_ambiguous_name_on_legacy_ipc_subclass_match() -> None: ipc=["C07K 14/705"], inventors=["Schadendorf, Dirk"], ) - spurious = mapping_module.MappedOpenAlexTopic( - topic_id="https://openalex.org/T99999", - topic_display_name="Antimicrobial Peptides and Activities", + index_mapped = mapping_module.MappedOpenAlexTopic( + topic_id="https://openalex.org/T10158", + topic_display_name="Cancer Immunotherapy and Biomarkers", + subfield_id="https://openalex.org/subfields/2705", + field_id="https://openalex.org/fields/27", field_name="Medicine", ) filtered = filter_patents_by_ipc_topic_mapping( [patent], author, is_ambiguous=True, - mapping=custom, - patent_topic_map={"EPO:EP1555271": [spurious]}, + patent_topic_map={patent_map_key(patent): [index_mapped]}, ) assert len(filtered) == 1 +def test_filter_rejects_ambiguous_personal_assignee_without_keywords_match() -> None: + author = _author_with_topic( + "https://openalex.org/T12345", + "Millimeter-Wave Propagation and Modeling", + subfield_id="https://openalex.org/subfields/2208", + field_id="https://openalex.org/fields/22", + domain_id="https://openalex.org/domains/3", + ) + grill_patent = model.PatentEntry( + patent_id="EP999", + source="EPO", + title="FIRE BASIN", + ipc=["A47J 37/07"], + assignees=["Kaiser, Thomas"], + inventors=["Kaiser, Thomas"], + ) + unrelated = mapping_module.MappedOpenAlexTopic( + topic_id="https://openalex.org/T88888", + topic_display_name="Food Science and Culinary Arts", + subfield_id="https://openalex.org/subfields/1106", + field_id="https://openalex.org/fields/11", + field_name="Agricultural and Biological Sciences", + ) + filtered = filter_patents_by_ipc_topic_mapping( + [grill_patent], + author, + is_ambiguous=True, + patent_topic_map={patent_map_key(grill_patent): [unrelated]}, + ) + assert filtered == [] + + +def test_filter_keeps_unique_name_on_full_personal_identity_without_topic_match() -> None: + author = _author_with_topic( + "https://openalex.org/T12345", + "Energy Efficient Wireless Sensor Networks", + subfield_id="https://openalex.org/subfields/1706", + field_id="https://openalex.org/fields/17", + domain_id="https://openalex.org/domains/3", + ) + author.display_name = "Pedro José Marrón" + patent = model.PatentEntry( + patent_id="EP1542159", + source="EPO", + title="Card and reader/writer apparatus for cards", + ipc=["G06K 19/077"], + assignees=["Marron, Pedro José, Dr."], + inventors=["Marron, Pedro José"], + ) + unrelated = mapping_module.MappedOpenAlexTopic( + topic_id="https://openalex.org/T88888", + topic_display_name="Advanced Image Processing Techniques", + subfield_id="https://openalex.org/subfields/1704", + field_id="https://openalex.org/fields/17", + field_name="Computer Science", + ) + assert patent_full_personal_identity_match(patent, author.display_name) is True + filtered = filter_patents_by_ipc_topic_mapping( + [patent], + author, + is_ambiguous=False, + patent_topic_map={patent_map_key(patent): [unrelated]}, + ) + assert len(filtered) == 1 + assert filtered[0].personal_assignee_match is True + + +def test_filter_rejects_initial_only_personal_assignee_without_topic_match() -> None: + author = _author_with_topic( + "https://openalex.org/T12345", + "Energy Efficient Wireless Sensor Networks", + subfield_id="https://openalex.org/subfields/1706", + field_id="https://openalex.org/fields/17", + domain_id="https://openalex.org/domains/3", + ) + author.display_name = "Pedro José Marrón" + patent = model.PatentEntry( + patent_id="EP999", + source="EPO", + title="Card reader", + ipc=["G06K 19/077"], + assignees=["Marron, P. J."], + inventors=["Marron, P. J."], + ) + unrelated = mapping_module.MappedOpenAlexTopic( + topic_id="https://openalex.org/T88888", + topic_display_name="Advanced Image Processing Techniques", + subfield_id="https://openalex.org/subfields/1704", + field_id="https://openalex.org/fields/17", + field_name="Computer Science", + ) + assert patent_personal_assignee_full_match(patent, author.display_name) is False + assert patent_full_personal_identity_match(patent, author.display_name) is False + filtered = filter_patents_by_ipc_topic_mapping( + [patent], + author, + is_ambiguous=False, + patent_topic_map={patent_map_key(patent): [unrelated]}, + ) + assert filtered == [] + + def test_custom_mapping_table() -> None: custom = _custom_mapping() author = Author( diff --git a/service/src/main/inse/patents/authors/topic_filter.py b/service/src/main/inse/patents/authors/topic_filter.py index 4ded689c..79ab8e20 100644 --- a/service/src/main/inse/patents/authors/topic_filter.py +++ b/service/src/main/inse/patents/authors/topic_filter.py @@ -1,10 +1,11 @@ -"""Filter name-matched patents using precomputed IPC/CPC → OpenAlex topic mappings.""" +"""Filter name-matched patents using IPC/CPC → OpenAlex topic mappings.""" from __future__ import annotations from dataclasses import dataclass from inse.models.openalex.author import Author from inse.patents.authors.identity import ( + patent_full_personal_identity_match, patent_institution_match, patent_personal_assignee_match, ) @@ -14,6 +15,7 @@ from inse.patents.authors.ipc_openalex_mapping import ( load_ipc_openalex_mapping, mapped_topics_match_author, mapped_topics_match_author_for_ambiguous, + mapped_topics_match_author_strict, patent_topics_match_author, resolve_mapped_topics_for_patent, ) @@ -70,7 +72,15 @@ def filter_patents_by_ipc_topic_mapping( mapping=None, patent_topic_map: dict[str, list[MappedOpenAlexTopic]] | None = None, ) -> list[TopicFilterResult]: + """Filter patents by comparing IPC/CPC codes with the author's OpenAlex topics. + + When ``patent_topic_map`` is provided (from the ``patents_openalex_keywords`` + index via :class:`PatentOpenAlexMappingResolver`), that mapping is the primary + signal: patents must share a topic or subfield with the author, unless the + assignee matches one of the author's institutions. + """ table = mapping if mapping is not None else load_ipc_openalex_mapping() + using_keywords_index = patent_topic_map is not None institution_names = [ name for institution in author.last_known_institutions or [] @@ -87,17 +97,31 @@ def filter_patents_by_ipc_topic_mapping( for patent in patents: institution_match = patent_institution_match(patent, institution_names) personal_assignee_match = patent_personal_assignee_match(patent, display_name) - strong_identity = institution_match or personal_assignee_match + if using_keywords_index: + if is_ambiguous: + strong_identity = institution_match + else: + strong_identity = institution_match or patent_full_personal_identity_match( + patent, + display_name, + ) + else: + strong_identity = institution_match or personal_assignee_match + mapped_topics = _resolve_patent_topics(patent, table, patent_topic_map) - if is_ambiguous: + + if using_keywords_index: + matched_via_mapping = mapped_topics_match_author_strict( + mapped_topics, + author, + ) + elif is_ambiguous: matched_via_mapping = mapped_topics_match_author_for_ambiguous( patent, author, mapped_topics, table, ) - elif patent_topic_map is not None: - matched_via_mapping = mapped_topics_match_author(mapped_topics, author) else: matched_via_mapping = patent_topics_match_author(patent, author, table) @@ -113,17 +137,22 @@ def filter_patents_by_ipc_topic_mapping( ) continue - if is_ambiguous: - if matched_via_mapping: - filtered.append( - TopicFilterResult( - patent=patent, - decision="keep", - matched_via_mapping=True, - institution_match=False, - personal_assignee_match=False, - ) + if matched_via_mapping: + filtered.append( + TopicFilterResult( + patent=patent, + decision="keep", + matched_via_mapping=True, + institution_match=False, + personal_assignee_match=False, ) + ) + continue + + if using_keywords_index: + continue + + if is_ambiguous: continue if _topic_conflict(mapped_topics, author): -- 2.56.1 From 4e8e744fc57eee803e3958b8673d041d35ae26c6 Mon Sep 17 00:00:00 2001 From: taguesokoudjou Date: Wed, 15 Jul 2026 14:25:53 +0200 Subject: [PATCH 5/7] fix(webapp): use KeywordsService for patent keyword search after dev merge --- .../patents-results/patents-results.component.ts | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) 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 9e7844af..aad267f5 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 @@ -4,8 +4,9 @@ import { MatButtonModule } from '@angular/material/button'; import { MatCardModule } from '@angular/material/card'; import { MatIconModule } from '@angular/material/icon'; -import { PatentsService } from '../../../../api/api/patents.service'; +import { KeywordsService } from '../../../../api/api/keywords.service'; import { KeywordPatentMatch } from '../../../../api/model/keywordPatentMatch'; +import { PatentsByKeywordsResponse } from '../../../../api/model/patentsByKeywordsResponse'; import { WeightMap, WeightSliderOption, @@ -39,7 +40,7 @@ import { SearchResultsStateService } from '../search-results-state.service'; }) export class KeywordsToPatentsResultsComponent implements OnInit { protected readonly state = inject(SearchResultsStateService); - private readonly patentsService = inject(PatentsService); + private readonly keywordsService = inject(KeywordsService); readonly defaultWeights: WeightMap = { ...DEFAULT_PATENT_SCORE_WEIGHTS }; @@ -125,12 +126,12 @@ export class KeywordsToPatentsResultsComponent implements OnInit { this.loadingPatents.set(true); this.patentsError.set(false); - this.patentsService.getPatentsByKeywords({ keywords }).subscribe({ - next: (response) => { + this.keywordsService.getPatentsByKeywords({ keywords }).subscribe({ + next: (response: PatentsByKeywordsResponse) => { this.setPatentMatches(response.patents ?? []); this.loadingPatents.set(false); }, - error: (error) => { + error: (error: unknown) => { console.error('Patent search failed:', error); this.setPatentMatches([]); this.patentsError.set(true); -- 2.56.1 From 538d73c1b18c45cb02195673f8b2f19c7024983a Mon Sep 17 00:00:00 2001 From: taguesokoudjou Date: Thu, 16 Jul 2026 13:34:28 +0200 Subject: [PATCH 6/7] Improve patent loading UI --- .../institution-patents.component.html | 6 +++++- .../institution-patents/institution-patents.component.ts | 3 ++- webapp/src/app/modules/patents/patents.component.html | 9 +++++---- webapp/src/app/modules/patents/patents.component.ts | 4 ++-- .../modules/person-patents/person-patents.component.html | 6 +++++- .../modules/person-patents/person-patents.component.ts | 3 ++- 6 files changed, 21 insertions(+), 10 deletions(-) diff --git a/webapp/src/app/modules/institution-patents/institution-patents.component.html b/webapp/src/app/modules/institution-patents/institution-patents.component.html index a68cbaea..70702f6a 100644 --- a/webapp/src/app/modules/institution-patents/institution-patents.component.html +++ b/webapp/src/app/modules/institution-patents/institution-patents.component.html @@ -1,5 +1,9 @@ @if (loading) { -

Lade Patente...

+ } @else if (error) {

Fehler beim Laden der Patente.

} @else if (patents.length === 0) { diff --git a/webapp/src/app/modules/institution-patents/institution-patents.component.ts b/webapp/src/app/modules/institution-patents/institution-patents.component.ts index 099e3335..94c6abca 100644 --- a/webapp/src/app/modules/institution-patents/institution-patents.component.ts +++ b/webapp/src/app/modules/institution-patents/institution-patents.component.ts @@ -7,6 +7,7 @@ import { formatPatentDate, getPublicationStageLabel, } from '../patent-detail/patent-detail.utils'; +import { LoadingComponent } from '../../shared/ui/loading/loading.component'; type SortMode = 'date' | 'title'; type SourceFilter = 'all' | 'EPO' | 'USPTO'; @@ -14,7 +15,7 @@ type OrgPatentMatchTypeFilter = 'all' | 'institution' | 'name' | 'both'; @Component({ selector: 'app-institution-patents', - imports: [CommonModule, RouterLink], + imports: [CommonModule, RouterLink, LoadingComponent], templateUrl: './institution-patents.component.html', styleUrl: './institution-patents.component.scss', }) diff --git a/webapp/src/app/modules/patents/patents.component.html b/webapp/src/app/modules/patents/patents.component.html index 762b9610..a3177536 100644 --- a/webapp/src/app/modules/patents/patents.component.html +++ b/webapp/src/app/modules/patents/patents.component.html @@ -81,10 +81,11 @@ @if (loading) { -
- - Lade Patente... -
+ } @else if (error) {

Fehler beim Laden der Patente.

} @else if (showDetail && selectedPatent) { diff --git a/webapp/src/app/modules/patents/patents.component.ts b/webapp/src/app/modules/patents/patents.component.ts index 0804a5a7..d1c99016 100644 --- a/webapp/src/app/modules/patents/patents.component.ts +++ b/webapp/src/app/modules/patents/patents.component.ts @@ -7,7 +7,6 @@ import { MatCardModule } from '@angular/material/card'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatInputModule } from '@angular/material/input'; import { MatPaginatorModule, PageEvent } from '@angular/material/paginator'; -import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; import { MatChipsModule } from '@angular/material/chips'; import { MatDividerModule } from '@angular/material/divider'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; @@ -17,6 +16,7 @@ import { PatentEntry } from '../../api/model/patentEntry'; import { IpcClassification } from '../../api'; import { OpenAlexTopicTag } from '../../api/model/openAlexTopicTag'; import { TopicChipComponent } from '../../shared/ui/topic-chip/topic-chip.component'; +import { LoadingComponent } from '../../shared/ui/loading/loading.component'; import { topicHierarchyColor } from '../../resolvers/utils/topic-colors'; type SourceFilter = 'all' | 'EPO' | 'USPTO'; @@ -47,10 +47,10 @@ const MIN_YEAR = 1978; MatFormFieldModule, MatInputModule, MatPaginatorModule, - MatProgressSpinnerModule, MatChipsModule, MatDividerModule, TopicChipComponent, + LoadingComponent, ], templateUrl: './patents.component.html', styleUrl: './patents.component.scss', diff --git a/webapp/src/app/modules/person-patents/person-patents.component.html b/webapp/src/app/modules/person-patents/person-patents.component.html index 08433aea..1c7114aa 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.html +++ b/webapp/src/app/modules/person-patents/person-patents.component.html @@ -1,5 +1,9 @@ @if (loading) { -

Lade Patente...

+ } @else if (error) {

Fehler beim Laden der Patente.

} @else if (patents.length === 0) { diff --git a/webapp/src/app/modules/person-patents/person-patents.component.ts b/webapp/src/app/modules/person-patents/person-patents.component.ts index b92b2cf2..739aac5d 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.ts +++ b/webapp/src/app/modules/person-patents/person-patents.component.ts @@ -9,13 +9,14 @@ import { formatPatentDate, getPublicationStageLabel, } from '../patent-detail/patent-detail.utils'; +import { LoadingComponent } from '../../shared/ui/loading/loading.component'; type SortMode = 'date' | 'title'; type SourceFilter = 'all' | 'EPO' | 'USPTO'; @Component({ selector: 'app-person-patents', - imports: [CommonModule], + imports: [CommonModule, LoadingComponent], templateUrl: './person-patents.component.html', styleUrl: './person-patents.component.scss', }) -- 2.56.1 From f813314d839804b61bbb36432da21e8526bfc7f8 Mon Sep 17 00:00:00 2001 From: Khuder Khalti Date: Thu, 16 Jul 2026 22:27:30 +0200 Subject: [PATCH 7/7] fix(patents): require topic corroboration for ambiguous-name matches beyond institution assignee, and tighten given-name comparison to stop cross-matching different people who share one common name component Co-Authored-By: Claude Sonnet 5 --- service/README.md | 14 +-- service/scripts/index_org_patents.py | 9 +- .../inse/patents/authors/name_matching.py | 46 ++++----- service/src/main/inse/patents/org/logic.py | 96 ++++++++++++------- .../src/main/inse/patents/org/test_logic.py | 52 +++++++--- .../main/inse/patents/test_name_matching.py | 2 + 6 files changed, 142 insertions(+), 77 deletions(-) diff --git a/service/README.md b/service/README.md index 7d6c4964..5785d883 100644 --- a/service/README.md +++ b/service/README.md @@ -23,12 +23,14 @@ Run tests: `./gradlew :service:test` Builds the `org_patents` Elasticsearch index for a given institution: fetches its OpenAlex authors, searches EPO/USPTO for patents matched via institution assignee and/or inventor name, and reindexes. Each patent is tagged with a `match_type` -(`institution`, `name`, or `both`, the latter being highest confidence). For common -inventor names, a name match is only kept if the assignee is the institution itself or -the person, or if the patent's IPC/CPC-derived OpenAlex topics share at least two exact -topic IDs with the author's own research topics — a single shared topic isn't reliable -enough, since broad, common topics coincidentally show up on unrelated patents and -profiles alike. This avoids pulling in unrelated patents via a shared name. +(`institution`, `name`, or `both`, the latter being highest confidence). For rare enough +names, an inventor-name match counts on its own. For common names (shared by several +real people in OpenAlex), a match counts outright only if the assignee is the +institution itself; everything else matched on name alone — a personal-assignee match +or a third-party assignee (e.g. an industry partner on a co-invented patent) — only +counts if the patent's primary IPC/CPC classification also maps to OpenAlex research +topics that appear on the author's own profile — since first/last names collide across +many real people, this confirms the patent's subject matter actually matches theirs. ```bash python scripts/index_org_patents.py --institution-id diff --git a/service/scripts/index_org_patents.py b/service/scripts/index_org_patents.py index cd057117..7aa2bf28 100644 --- a/service/scripts/index_org_patents.py +++ b/service/scripts/index_org_patents.py @@ -5,9 +5,12 @@ index_org_patents.py — Build the org_patents Elasticsearch index for one insti Fetches all OpenAlex authors affiliated with the institution, searches EPO/USPTO for patents matched via institution assignee and/or author name (match_type: "institution", "name", or "both"), deletes existing documents for the institution, and reindexes. For -common inventor names, a name match is only kept with institution/assignee evidence or -at least two shared OpenAlex topic IDs between the patent (via IPC/CPC) and the -author's own research topics. +rare enough names, an inventor-name match counts on its own. For common names, a match +counts outright only if the assignee is the institution itself; everything else +matched on name alone (a personal-assignee match or a third-party assignee) only +counts if the patent's primary IPC/CPC classification also maps to OpenAlex research +topics that appear on the author's own profile — since first/last names collide across +many real people, to avoid pulling in unrelated patents via a shared name. Usage: python scripts/index_org_patents.py --institution-id diff --git a/service/src/main/inse/patents/authors/name_matching.py b/service/src/main/inse/patents/authors/name_matching.py index f55ff54f..3934e465 100644 --- a/service/src/main/inse/patents/authors/name_matching.py +++ b/service/src/main/inse/patents/authors/name_matching.py @@ -271,29 +271,31 @@ def _given_name_matches(author: ParsedPersonName, inventor: ParsedPersonName) -> if not inventor.given_names: return False - # Accept immediately when at least one inventor given-name token matches - # one of the author's given names as a full token (not only initial), - # e.g. "Maria Schmidt" vs "Anna Maria Schmidt". This only counts if at - # least one side is a spelled-out name, not a bare initial — two - # coincidentally identical single-letter tokens (e.g. both just "K.") - # are far too weak a signal on their own and would otherwise match - # anyone sharing that one middle initial regardless of their actual - # first name (e.g. "Mahendra K. Sharma" incorrectly matching inventor - # "Vivek K." or "Virender K." on an unrelated patent). - if any( - any( - tokens_equal(author_given, inventor_given, allow_initial=False) - and not (_initial_letter(author_given) and _initial_letter(inventor_given)) - for author_given in author.given_names - ) - for inventor_given in inventor.given_names - ): - return True + author_full = [g for g in author.given_names if _initial_letter(g) is None] + inventor_full = [g for g in inventor.given_names if _initial_letter(g) is None] - inventor_tokens_full = [ - token for token in inventor.given_names - if _initial_letter(token) is None - ] + # Accept when one side's full (spelled-out) given names are entirely + # covered by the other's — e.g. "Maria Schmidt" vs "Anna Maria Schmidt" + # (shortened form). A single shared given-name token is not enough by + # itself when both sides also carry other, non-matching full given + # names: that pattern matches different people who happen to share one + # common given-name component rather than the same person (e.g. "Kim, + # Young Gil" vs "Moon Young Kim" both contain "Young", but "Gil" and + # "Moon" don't match — these are two different people, not the same + # person under a shortened name). + if author_full and inventor_full: + smaller, larger = ( + (author_full, inventor_full) + if len(author_full) <= len(inventor_full) + else (inventor_full, author_full) + ) + if all( + any(tokens_equal(token, other, allow_initial=False) for other in larger) + for token in smaller + ): + return True + + inventor_tokens_full = inventor_full # Prevent false positives like "Karem C Weber" for "Christian Weber": # if inventor has full given-name tokens but none matches the author, diff --git a/service/src/main/inse/patents/org/logic.py b/service/src/main/inse/patents/org/logic.py index 574f6a33..d2d5d3d0 100644 --- a/service/src/main/inse/patents/org/logic.py +++ b/service/src/main/inse/patents/org/logic.py @@ -15,7 +15,6 @@ from inse.patents.authors.identity import ( author_institution_names, is_ambiguous_name, patent_institution_match, - patent_personal_assignee_match, ) from inse.patents.authors.ipc_openalex_mapping import normalize_openalex_id from inse.patents.authors.name_matching import filter_patents_by_author_name @@ -224,6 +223,22 @@ def org_patent_to_es_document(patent: OrgPatentEntry) -> dict: MIN_CORROBORATING_TOPIC_OVERLAP = 2 +def primary_classification_codes(patent: PatentEntry) -> list[str]: + """Returns only the patent's primary IPC/CPC code(s) (marked "AFI" in the + raw EPO/USPTO string), falling back to all codes if none are marked. + + Patents can carry dozens of secondary/incidental classification codes + (marked "ALI") alongside their real subject. Resolving OpenAlex topics + from *all* of them gives some patents a huge, unfocused topic cloud — + confirmed against a real org_patents rebuild, where a 20-code patent + picked up 70+ unrelated topics, making a coincidental two-topic overlap + with an unrelated same-named author far more likely than intended. + """ + all_codes = [*patent.ipc, *patent.cpc] + primary = [code for code in all_codes if "AFI" in code] + return primary or all_codes + + def topic_corroborated_patents( patents: list[PatentEntry], author: Author, @@ -271,7 +286,6 @@ async def _search_patents_by_author( author: Author, institution_name: str | None, search_client: PatentSearchClient, - ipc_client: IpcSearchClient, ) -> list[PatentEntry]: author_name = author.display_name if not author_name: @@ -319,40 +333,52 @@ async def _search_patents_by_author( openalex_last_name_count=last_name_count, ) - if is_ambiguous: - # Common names (Zhang, Li, Wang): only keep if the assignee matches the - # institution we're building this index for (not any institution from - # the author's whole affiliation history), the person themselves, or - # their own OpenAlex research topics share at least - # MIN_CORROBORATING_TOPIC_OVERLAP exact topic IDs with the patent's - # IPC/CPC-derived topics. - inst_names = [institution_name] if institution_name else [] - strong_identity_matched = [ - p for p in name_matched - if patent_institution_match(p, inst_names) - or patent_personal_assignee_match(p, author_name) - ] - matched_keys = {patent_dedup_key(p) for p in strong_identity_matched} - remaining = [p for p in name_matched if patent_dedup_key(p) not in matched_keys] - if not remaining: - return strong_identity_matched - - topic_matched: list[PatentEntry] = [] - try: - resolver = PatentOpenAlexMappingResolver() - patent_topic_map = await resolver.resolve_topics_for_patents(remaining) - topic_matched = topic_corroborated_patents(remaining, author, patent_topic_map) - except Exception: - logger.warning( - "OpenAlex topic corroboration failed for ambiguous name %s", - author_name, - exc_info=True, - ) - - return strong_identity_matched + topic_matched - else: + if not is_ambiguous: + # A rare enough name that a bare inventor-field match is already a + # reliable signal — no other same-named person is realistically + # going to show up in the search results. return name_matched + # Common names (Zhang, Li, Wang): the institution itself being the + # assignee is the only unambiguous case — accepted outright. Everything + # else matched on name alone, including a personal-assignee match + # (several different same-named people could each be listed as their + # own patent's assignee) or a third-party assignee (e.g. an industry + # partner on a co-invented patent — the normal case for academic + # patents, not a red flag by itself), only counts if the patent's + # IPC/CPC-derived OpenAlex topics also overlap with the author's own + # research topics. + inst_names = [institution_name] if institution_name else [] + strong_identity_matched = [ + p for p in name_matched + if patent_institution_match(p, inst_names) + ] + matched_keys = {patent_dedup_key(p) for p in strong_identity_matched} + remaining = [p for p in name_matched if patent_dedup_key(p) not in matched_keys] + if not remaining: + return strong_identity_matched + + topic_matched: list[PatentEntry] = [] + try: + resolver = PatentOpenAlexMappingResolver() + primary_only = [ + patent.model_copy(update={ + "ipc": primary_classification_codes(patent), + "cpc": [], + }) + for patent in remaining + ] + patent_topic_map = await resolver.resolve_topics_for_patents(primary_only) + topic_matched = topic_corroborated_patents(remaining, author, patent_topic_map) + except Exception: + logger.warning( + "OpenAlex topic corroboration failed for author %s", + author_name, + exc_info=True, + ) + + return strong_identity_matched + topic_matched + async def build_org_patents_for_institution( institution_id: str, @@ -390,7 +416,7 @@ async def build_org_patents_for_institution( async def _fetch_for_author(author: Author) -> tuple[Author, list[PatentEntry]]: async with semaphore: patents = await _search_patents_by_author( - author, institution_name, patent_client, ipc_search_client + author, institution_name, patent_client ) return author, patents diff --git a/service/src/main/inse/patents/org/test_logic.py b/service/src/main/inse/patents/org/test_logic.py index 26588f43..82a2aa21 100644 --- a/service/src/main/inse/patents/org/test_logic.py +++ b/service/src/main/inse/patents/org/test_logic.py @@ -6,6 +6,7 @@ from inse.patents.common.parsing import patent_map_key from inse.patents.org.logic import ( merge_org_patents, org_patent_document_id, + primary_classification_codes, resolve_match_type, topic_corroborated_patents, ) @@ -31,14 +32,6 @@ def _author(author_id: str, name: str) -> Author: ) -def _author_with_topics(author_id: str, name: str, topic_ids: list[str]) -> Author: - return Author( - id=f"https://openalex.org/{author_id}", - display_name=name, - topics=[WorkTopic(id=tid, display_name=f"Topic {tid}") for tid in topic_ids], - ) - - def test_resolve_match_type() -> None: assert resolve_match_type(True, True) == "both" assert resolve_match_type(True, False) == "institution" @@ -116,6 +109,14 @@ def test_org_patent_document_id_is_stable() -> None: assert doc_id == "I62318514_EPO_EP1234567_20240101_A1" +def _author_with_topics(author_id: str, name: str, topic_ids: list[str]) -> Author: + return Author( + id=f"https://openalex.org/{author_id}", + display_name=name, + topics=[WorkTopic(id=tid, display_name=f"Topic {tid}") for tid in topic_ids], + ) + + def _mapped_topics(*topic_ids: str) -> list[MappedOpenAlexTopic]: return [ MappedOpenAlexTopic(topic_id=tid, topic_display_name=f"Topic {tid}") @@ -142,9 +143,7 @@ def test_topic_corroborated_patents_keeps_two_overlapping_topics() -> None: def test_topic_corroborated_patents_drops_single_coincidental_overlap() -> None: """A single shared topic isn't enough — broad, common topics show up on - many unrelated patents and profiles by coincidence. Confirmed against a - real org_patents rebuild where single-topic matching still let through - ~2000 mostly-unrelated "name"-matched patents.""" + many unrelated patents and profiles by coincidence.""" author = _author_with_topics( "A123", "Xin Wang", ["https://openalex.org/T1", "https://openalex.org/T9"], @@ -182,3 +181,34 @@ def test_topic_corroborated_patents_rejects_everything_without_author_topic_prof result = topic_corroborated_patents([patent], author, patent_topic_map) assert result == [] + + +def test_primary_classification_codes_keeps_only_afi_marked_codes() -> None: + """A patent with many secondary ("ALI") codes alongside its one primary + ("AFI") code must only contribute the primary one — otherwise a large + secondary-code topic cloud makes coincidental multi-topic overlaps with + an unrelated same-named author far too easy (confirmed against a real + org_patents rebuild: a 20-code patent picked up 70+ topics).""" + patent = _patent("EP1") + patent.ipc = [ + "G06V 10/776 20220101AFI20250422BHUS", + "G01N 33/569 20060101ALI20250422BHUS", + "G06T 5/20 20060101ALI20250422BHUS", + ] + patent.cpc = ["G16H 30/40 20180101ALI20250422BHUS"] + + result = primary_classification_codes(patent) + + assert result == ["G06V 10/776 20220101AFI20250422BHUS"] + + +def test_primary_classification_codes_falls_back_to_all_codes_without_afi_marker() -> None: + patent = _patent("EP2") + patent.ipc = ["G06V 10/776 20220101ALI20250422BHUS"] + patent.cpc = ["G01N 33/569 20060101ALI20250422BHUS"] + + result = primary_classification_codes(patent) + + assert result == patent.ipc + patent.cpc + + diff --git a/service/src/main/inse/patents/test_name_matching.py b/service/src/main/inse/patents/test_name_matching.py index 828a1082..675b93fd 100644 --- a/service/src/main/inse/patents/test_name_matching.py +++ b/service/src/main/inse/patents/test_name_matching.py @@ -136,6 +136,8 @@ def test_first_name_match_kind() -> None: ("Schmitz, Oliver", "Oliver J. Schmitz", False), ("Schmitz, Oliver J.", "Oliver J. Schmitz", True), ("Schmitz, O. J.", "Oliver J. Schmitz", True), + ("Kim, Young Gil", "Moon Young Kim", False), + ("Kim, Young Hwan", "Moon Young Kim", False), ], ) def test_name_matches_person_multi_part( -- 2.56.1