feat(keywords): show ranked patent matches with adjustable IPC/topic/text weights
LocationBasedServices/smartguide/pipeline/head This commit looks good

This commit is contained in:
2026-07-13 23:03:42 +02:00
parent b3af72a6ae
commit 1a2b1a1970
18 changed files with 793 additions and 424 deletions
@@ -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,
)
@@ -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)
@@ -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:
@@ -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
@@ -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())
@@ -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[];
}
@@ -1,132 +1,160 @@
@if (loading()) {␍
<p class="message">Lade passende Patente...</p>␍
} @else if (error()) {␍
<p class="message">Fehler beim Laden der Patente.</p>␍
} @else if (matches().length === 0) {␍
<p class="message">Keine passenden Patente gefunden.</p>␍
} @else {␍
<div class="patents-container">␍
<h2 class="section-title">Passende Patente</h2>␍
␍
<div class="patents-content">␍
<div class="patents-list">␍
<div class="patents-list-toolbar">␍
<label class="sort-control">␍
<span>Filter nach Quelle:</span>␍
<select␍
[value]="activeFilter()"␍
(change)="setFilter($any($event.target).value)">␍
<option value="all">Alle</option>␍
<option value="EPO">EPO</option>␍
<option value="USPTO">USPTO</option>␍
</select>␍
</label>␍
</div>␍
␍
<table>␍
<thead>␍
<tr>␍
<th>Patent</th>␍
<th>Score</th>␍
<th>Quelle</th>␍
<th>Jahr</th>␍
</tr>␍
</thead>␍
<tbody>␍
@for (item of pagedMatches(); track trackMatch($index, item)) {␍
<tr␍
[class.selected]="selectedMatch() === item"␍
(click)="selectMatch(item)">␍
<td class="patent-title">␍
{{ item.patent.title ?? item.patent.patent_id }}␍
</td>␍
<td class="match-score">{{ formatScore(item.match_score) }}</td>␍
<td>␍
<span␍
class="source-badge source-badge--{{␍
item.patent.source.toLowerCase()␍
}}">␍
{{ item.patent.source }}␍
</span>␍
</td>␍
<td>{{ item.patent.publication_year ?? '-' }}</td>␍
</tr>␍
}␍
</tbody>␍
</table>␍
␍
@if (hasPagination()) {␍
<div class="pagination">␍
<button␍
[disabled]="selectedPage() === 1"␍
(click)="setPage(selectedPage() - 1)">␍
Zurück␍
</button>␍
<span>Seite {{ selectedPage() }} von {{ pageCount() }}</span>␍
<button␍
[disabled]="selectedPage() === pageCount()"␍
(click)="setPage(selectedPage() + 1)">␍
Weiter␍
</button>␍
</div>␍
}␍
</div>␍
␍
@if (selectedMatch(); as match) {␍
<div class="patent-detail">␍
<h3>{{ match.patent.title ?? match.patent.patent_id }}</h3>␍
<div class="detail-stats">␍
<div class="stat">␍
<span class="stat-label">Match-Score</span>␍
<span class="stat-value">{{ formatScore(match.match_score) }}</span>␍
</div>␍
<div class="stat">␍
<span class="stat-label">Gematchte Keywords</span>␍
<span class="stat-value">{{␍
formatMatchList(match.matched_keywords)␍
}}</span>␍
</div>␍
<div class="stat">␍
<span class="stat-label">Gematchte IPC/CPC</span>␍
<span class="stat-value">{{␍
formatMatchList(match.matched_ipc_symbols)␍
}}</span>␍
</div>␍
<div class="stat">␍
<span class="stat-label">Quelle</span>␍
<span class="stat-value">␍
<span␍
class="source-badge source-badge--{{␍
match.patent.source.toLowerCase()␍
}}">␍
{{ match.patent.source }}␍
</span>␍
</span>␍
</div>␍
<div class="stat">␍
<span class="stat-label">Patent-Nr.</span>␍
<span class="stat-value">{{ match.patent.patent_id }}</span>␍
</div>␍
<div class="stat">␍
<span class="stat-label">Datum</span>␍
<span class="stat-value">{{␍
formatDate(match.patent.publication_date)␍
}}</span>␍
</div>␍
@if (getPublicationStageLabel(match.patent); as stageLabel) {␍
<div class="stat">␍
<span class="stat-label">Publikationsstufe</span>␍
<span class="stat-value">{{ stageLabel }}</span>␍
</div>␍
}␍
</div>␍
␍
<button type="button" class="patent-detail-action" (click)="openDetail()">␍
<span class="patent-detail-action__label">Patentdetails anzeigen</span>␍
<span class="material-icons" aria-hidden="true">chevron_right</span>␍
</button>␍
</div>␍
}␍
</div>␍
</div>␍
}␍
@if (loading()) {
<div class="patents-container">
<ng-container *ngTemplateOutlet="patentsHeader" />
<p class="message">Lade passende Patente...</p>
</div>
} @else if (error()) {
<div class="patents-container">
<ng-container *ngTemplateOutlet="patentsHeader" />
<p class="message">Fehler beim Laden der Patente.</p>
</div>
} @else if (matches().length === 0) {
<div class="patents-container">
<ng-container *ngTemplateOutlet="patentsHeader" />
<p class="message">Keine passenden Patente gefunden.</p>
</div>
} @else {
<div class="patents-container">
<ng-container *ngTemplateOutlet="patentsHeader" />
<div class="patents-content">
<div class="patents-list">
<table>
<thead>
<tr>
<th>Patent</th>
<th>Score</th>
<th>Quelle</th>
<th>Jahr</th>
</tr>
</thead>
<tbody>
@for (item of pagedMatches(); track trackMatch($index, item)) {
<tr
[class.selected]="selectedMatch() === item"
(click)="selectMatch(item)">
<td class="patent-title">
{{ item.patent.title ?? item.patent.patent_id }}
</td>
<td class="match-score">{{ formatScore(item.match_score) }}</td>
<td>
<span
class="source-badge source-badge--{{
item.patent.source.toLowerCase()
}}">
{{ item.patent.source }}
</span>
</td>
<td>{{ item.patent.publication_year ?? '-' }}</td>
</tr>
}
</tbody>
</table>
@if (hasPagination()) {
<div class="pagination">
<button
[disabled]="selectedPage() === 1"
(click)="setPage(selectedPage() - 1)">
Zurück
</button>
<span>Seite {{ selectedPage() }} von {{ pageCount() }}</span>
<button
[disabled]="selectedPage() === pageCount()"
(click)="setPage(selectedPage() + 1)">
Weiter
</button>
</div>
}
</div>
@if (selectedMatch(); as match) {
<div class="patent-detail">
<h3>{{ match.patent.title ?? match.patent.patent_id }}</h3>
<div class="detail-stats">
<div class="stat">
<span class="stat-label">Match-Score</span>
<span class="stat-value">{{ formatScore(match.match_score) }}</span>
</div>
<div class="stat">
<span class="stat-label">Gematchte Keywords</span>
<span class="stat-value">{{
formatMatchList(match.matched_keywords)
}}</span>
</div>
<div class="stat">
<span class="stat-label">Gematchte IPC/CPC</span>
<span class="stat-value">{{
formatMatchList(match.matched_ipc_symbols)
}}</span>
</div>
<div class="stat">
<span class="stat-label">Quelle</span>
<span class="stat-value">
<span
class="source-badge source-badge--{{
match.patent.source.toLowerCase()
}}">
{{ match.patent.source }}
</span>
</span>
</div>
<div class="stat">
<span class="stat-label">Patent-Nr.</span>
<span class="stat-value">{{ match.patent.patent_id }}</span>
</div>
<div class="stat">
<span class="stat-label">Datum</span>
<span class="stat-value">{{
formatDate(match.patent.publication_date)
}}</span>
</div>
@if (getPublicationStageLabel(match.patent); as stageLabel) {
<div class="stat">
<span class="stat-label">Publikationsstufe</span>
<span class="stat-value">{{ stageLabel }}</span>
</div>
}
</div>
<button type="button" class="patent-detail-action" (click)="openDetail()">
<span class="patent-detail-action__label">Patentdetails anzeigen</span>
<span class="material-icons" aria-hidden="true">chevron_right</span>
</button>
</div>
}
</div>
</div>
}
<ng-template #patentsHeader>
<div class="patents-header">
<h2 class="section-title">Passende Patente</h2>
<div class="patents-header-actions">
@if (matches().length > 0) {
<label class="sort-control">
<span>Filter nach Quelle:</span>
<select
[value]="activeFilter()"
(change)="setFilter($any($event.target).value)">
<option value="all">Alle</option>
<option value="EPO">EPO</option>
<option value="USPTO">USPTO</option>
</select>
</label>
}
@if (showReload()) {
<button
mat-stroked-button
type="button"
class="reload-btn"
[disabled]="reloadDisabled()"
(click)="onReload()">
<mat-icon>refresh</mat-icon>
Neu laden
</button>
}
</div>
</div>
</ng-template>
@@ -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;
}
@@ -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<KeywordPatentMatch[]>([]);␍
readonly loading = input(false);␍
readonly error = input(false);␍
␍
activeFilter = signal<SourceFilter>('all');␍
selectedMatch = signal<KeywordPatentMatch | null>(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<KeywordPatentMatch[]>([]);
readonly loading = input(false);
readonly error = input(false);
readonly showReload = input(false);
readonly reloadDisabled = input(false);
readonly reload = output<void>();
activeFilter = signal<SourceFilter>('all');
selectedMatch = signal<KeywordPatentMatch | null>(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('|');
}
}
@@ -396,25 +396,8 @@
<mat-icon>show_chart</mat-icon>
Visualisierung
</button>
<button
mat-flat-button
class="patents-btn"
[disabled]="isSearchDisabled()"
(click)="loadPatentsForSelection()">
<mat-icon>description</mat-icon>
Patente
</button>
</div>
</div>
@if (showPatents()) {
<app-keywords-patents
[matches]="patentMatches()"
[loading]="loadingPatents()"
[error]="patentsError()">
</app-keywords-patents>
}
}
<!-- Trend Comparison Section -->
@@ -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%;
}
}
@@ -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<InputMode | null>(null);
readonly showVisualization = signal<boolean>(false);
readonly showPatents = signal(false);
readonly patentMatches = signal<KeywordPatentMatch[]>([]);
readonly loadingPatents = signal(false);
readonly patentsError = signal(false);
readonly patentsLoaded = signal(false);
readonly topicMappingSearch = signal<boolean>(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);
}
}
@@ -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<string, number>,
): 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<KeywordPatentMatch, 'ipc_score' | 'topic_score' | 'text_score'>,
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);
}
@@ -1,22 +1,12 @@
<div class="result-layout">
<mat-card class="results-card">
<mat-card-content class="results-placeholder">
<mat-icon>groups</mat-icon>
<h2>Patentenliste</h2>
<p>
Die aktuelle Gewichtung ist unter <code>normalized</code> verfügbar.
</p>
</mat-card-content>
</mat-card>
<mat-card class="weights-card">
<mat-card-content>
<app-weights-sliders
[options]="weightOptions"
[initialWeights]="defaultWeights"
title="Patenten-Gewichtung"
description="Werte zwischen 0 und 1. Summe wird normalisiert zu 1."
resetLabel="Ausgewogen"
description="Steuert die Gewichtung von IPC/CPC-Match, OpenAlex-Topic und Text-Match für den Gesamt-Score."
resetLabel="Standard"
applyLabel="Neu gewichten"
normalizedTitle="Normalisiert"
queryParamPrefix="patentW_"
@@ -28,4 +18,14 @@
(applyWeights)="onApplyWeights($event)" />
</mat-card-content>
</mat-card>
<div class="results-card">
<app-keywords-patents
[matches]="patentMatches()"
[loading]="loadingPatents()"
[error]="patentsError()"
[showReload]="state.hasValidSearch()"
[reloadDisabled]="loadingPatents() || !state.hasValidSearch()"
(reload)="reloadPatents()" />
</div>
</div>
@@ -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';
}
}
@@ -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<WeightsSlidersValue>({
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<unknown[]>([]); // placeholder until the results service lands
readonly patentMatches = signal<KeywordPatentMatch[]>([]);
readonly loadingPatents = signal(false);
readonly patentsError = signal(false);
private hasLoadedInitial = false;
private readonly patentMatchesBase = signal<KeywordPatentMatch[]>([]);
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));
}
}
@@ -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;
};
@@ -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,
},