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, },