From bc7b7784ea978c0847f8b96785ae0f022c526b4f Mon Sep 17 00:00:00 2001 From: Khuder Khalti Date: Sun, 14 Jun 2026 11:43:48 +0200 Subject: [PATCH 1/8] feat: add patent-to-researchers backend and frontend --- service/src/main/inse/.env | 16 +- service/src/main/inse/config.py | 5 + service/src/main/inse/main.py | 2 + service/src/main/inse/patents/__init__.py | 5 + .../inse/patents/elastic_search_client.py | 140 +++++++++ service/src/main/inse/patents/logic.py | 269 ++++++++++++++++ service/src/main/inse/patents/model.py | 22 ++ service/src/main/inse/patents/service.py | 21 ++ webapp/src/app/api/api/patents.service.ts | 167 ++++++++++ webapp/src/app/app.routes.ts | 7 + .../person-patents.component.html | 150 +++++++++ .../person-patents.component.scss | 293 ++++++++++++++++++ .../person-patents.component.ts | 157 ++++++++++ .../app/modules/person/person.component.ts | 1 + 14 files changed, 1249 insertions(+), 6 deletions(-) create mode 100644 service/src/main/inse/patents/__init__.py create mode 100644 service/src/main/inse/patents/elastic_search_client.py create mode 100644 service/src/main/inse/patents/logic.py create mode 100644 service/src/main/inse/patents/model.py create mode 100644 service/src/main/inse/patents/service.py create mode 100644 webapp/src/app/api/api/patents.service.ts create mode 100644 webapp/src/app/modules/person-patents/person-patents.component.html create mode 100644 webapp/src/app/modules/person-patents/person-patents.component.scss create mode 100644 webapp/src/app/modules/person-patents/person-patents.component.ts diff --git a/service/src/main/inse/.env b/service/src/main/inse/.env index f2fc4762..44365fb2 100644 --- a/service/src/main/inse/.env +++ b/service/src/main/inse/.env @@ -1,6 +1,10 @@ -ELASTICSEARCH_URL=https://project.nes.uni-due.de/elastic/ -ELASTICSEARCH_API_KEY=am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ - -LLM_API_URL=https://project.nes.uni-due.de/llm2/v1/ -LLM_API_KEY=c2d5e7ccf7a4760dd3d19bed2caed9d85ff7437400e0ea82a6d6f912ebc2f212 -LLM_MODEL=gemma4-e4b \ No newline at end of file +ELASTICSEARCH_URL=https://project.nes.uni-due.de/elastic/ +ELASTICSEARCH_API_KEY=am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ + +LLM_API_URL=https://project.nes.uni-due.de/llm2/v1/ +LLM_API_KEY=c2d5e7ccf7a4760dd3d19bed2caed9d85ff7437400e0ea82a6d6f912ebc2f212 +LLM_MODEL=gemma4-e4b + +# Patent search (EPO + USPTO) +PATENT_ELASTICSEARCH_URL=https://inse.nes.uni-due.de/elastic +PATENT_ELASTICSEARCH_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== \ No newline at end of file diff --git a/service/src/main/inse/config.py b/service/src/main/inse/config.py index 4d83fe03..cdc232d5 100644 --- a/service/src/main/inse/config.py +++ b/service/src/main/inse/config.py @@ -39,6 +39,11 @@ class Settings(BaseSettings): openalex_api_key: Optional[str] = None openalex_api_timeout_seconds: float = 30.0 + # Patent elasticsearch config + patent_elasticsearch_url: str = "https://inse.nes.uni-due.de/elastic" + patent_elasticsearch_api_key: str = "" + + # LLM config llm_api_url: Optional[str] = None llm_api_key: Optional[str] = None diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index a1e4614e..52fa7b1f 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -16,6 +16,7 @@ from inse.topics.service import router as topics_service_router from inse.works.service import router as works_service_router from inse.persons.service import router as persons_service_router from inse.funders.service import router as funders_service_router +from inse.patents.service import router as patents_service_router from . import config from .service import router as service_router @@ -42,6 +43,7 @@ app.include_router(persons_service_router) app.include_router(funders_service_router) app.include_router(service_router) app.include_router(account_router) +app.include_router(patents_service_router) app.add_middleware( CORSMiddleware, diff --git a/service/src/main/inse/patents/__init__.py b/service/src/main/inse/patents/__init__.py new file mode 100644 index 00000000..d10d63ca --- /dev/null +++ b/service/src/main/inse/patents/__init__.py @@ -0,0 +1,5 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" + Patents domain package. +""" diff --git a/service/src/main/inse/patents/elastic_search_client.py b/service/src/main/inse/patents/elastic_search_client.py new file mode 100644 index 00000000..ac20fbb2 --- /dev/null +++ b/service/src/main/inse/patents/elastic_search_client.py @@ -0,0 +1,140 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" + HTTP client for patent searches in EPO and USPTO Elasticsearch indices. +""" +from typing import Any + +import httpx + +from .. import config + +EPO_INDEX = "epo_index_1.0" +USPTO_INDEX = "uspto_patents_2.0" + + +class MissingApiKeyError(Exception): + pass + + +class PatentSearchClient: + def __init__( + self, + base_url: str | None = None, + api_key: str | None = None, + timeout: float = 30.0, + transport: httpx.AsyncBaseTransport | None = None, + ): + self.base_url = (base_url or config.settings.patent_elasticsearch_url).rstrip("/") + self.api_key = api_key if api_key is not None else config.settings.patent_elasticsearch_api_key + self.timeout = timeout + self.transport = transport + + def _headers(self) -> dict[str, str]: + if not self.api_key: + raise MissingApiKeyError("Patent Elasticsearch API key is not configured.") + return { + "Authorization": f"ApiKey {self.api_key}", + "Content-Type": "application/json", + } + + def epo_query_by_inventor(self, last_name: str, size: int = 100) -> dict[str, Any]: + """Search EPO index by inventor last name.""" + return { + "size": size, + "track_total_hits": True, + "_source": [ + "doc_number", + "country", + "kind", + "date_publication", + "date_publication_year", + "title_en", + "title_de", + "abstract", + "inventors_name", + "applicants_name", + "ipc", + "ipc_text", + ], + "query": { + "bool": { + "should": [ + { + "match": { + "inventors_name_text": { + "query": last_name, + "operator": "and", + } + } + }, + { + "term": { + "inventors_name": last_name + } + }, + ], + "minimum_should_match": 1, + } + }, + } + + def uspto_query_by_inventor(self, last_name: str, size: int = 100) -> dict[str, Any]: + """Search USPTO index by inventor last name.""" + return { + "size": size, + "track_total_hits": True, + "_source": [ + "publication_number", + "country", + "publication_date", + "publication_year", + "title", + "abstract", + "inventors_names", + "inventors_names_text", + "assignees_orgs", + "ipcr", + "ipcr_text", + ], + "query": { + "bool": { + "should": [ + { + "match": { + "inventors_names_text": { + "query": last_name, + "operator": "and", + } + } + }, + { + "term": { + "inventors_names": last_name + } + }, + ], + "minimum_should_match": 1, + } + }, + } + + async def search_epo(self, payload: dict[str, Any]) -> dict[str, Any]: + return await self._search(EPO_INDEX, payload) + + async def search_uspto(self, payload: dict[str, Any]) -> dict[str, Any]: + return await self._search(USPTO_INDEX, payload) + + async def _search(self, index: str, payload: dict[str, Any]) -> 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"/{index}/_search", + headers=self._headers(), + json=payload, + ) + response.raise_for_status() + return response.json() \ No newline at end of file diff --git a/service/src/main/inse/patents/logic.py b/service/src/main/inse/patents/logic.py new file mode 100644 index 00000000..e503f042 --- /dev/null +++ b/service/src/main/inse/patents/logic.py @@ -0,0 +1,269 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" + Business logic for patent matching by author name. +""" +import logging +from collections import defaultdict + +import httpx +from fastapi import HTTPException +from starlette.status import HTTP_502_BAD_GATEWAY +from starlette.status import HTTP_503_SERVICE_UNAVAILABLE + +from ..persons import logic as person_logic +from ..models.author import Author +from . import model +from .elastic_search_client import MissingApiKeyError +from .elastic_search_client import PatentSearchClient + +logger = logging.getLogger(__name__) + +_MIN_CONFIDENCE_SCORE = 4 + + +async def get_patents_by_author_id( + author_id: str, + client: PatentSearchClient | None = None, +) -> model.PatentsByAuthorResponse: + search_client = client or PatentSearchClient() + + author = _get_author(author_id) + if not author: + return model.PatentsByAuthorResponse( + author_id=author_id, + author_name=None, + patent_count=0, + patents=[], + ) + + author_name = author.display_name + last_name = _extract_last_name(author_name) + first_name = _extract_first_name(author_name) + + if not last_name: + return model.PatentsByAuthorResponse( + author_id=author_id, + author_name=author_name, + patent_count=0, + patents=[], + ) + + institutions = _extract_all_institutions(author) + topics = _extract_topics(author) + orcid = _extract_orcid(author) + + try: + epo_data, uspto_data = await _search_both_indices(search_client, last_name) + except MissingApiKeyError as exc: + raise HTTPException(status_code=HTTP_503_SERVICE_UNAVAILABLE, + detail="Patent search is not configured.") from exc + except httpx.HTTPError as exc: + raise HTTPException(status_code=HTTP_502_BAD_GATEWAY, + detail="Patent search request failed.") from exc + + all_patents = _parse_epo_hits(epo_data) + _parse_uspto_hits(uspto_data) + + # Group by patent_id to check all versions together + grouped: dict[str, list[model.PatentEntry]] = defaultdict(list) + for patent in all_patents: + grouped[patent.patent_id].append(patent) + + result_patents = [] + for patent_id, versions in grouped.items(): + + # Step 1: Check if first+last name appear together in ONE inventor entry + # across any version + if first_name and last_name: + name_ok = any( + first_name.lower() in inv.lower() and last_name.lower() in inv.lower() + for version in versions + for inv in version.inventors + ) + if not name_ok: + continue + + # Step 2: Check institution across ALL versions that have assignees + # If ANY version has assignees that don't match our institutions → reject all + versions_with_assignees = [v for v in versions if v.assignees] + if versions_with_assignees: + institution_ok = False + for version in versions_with_assignees: + for institution in institutions: + inst_words = set(institution.lower().split()) + for asg in version.assignees: + asg_words = set(asg.lower().split()) + meaningful = {w for w in (inst_words & asg_words) if len(w) > 3} + if len(meaningful) >= 2: + institution_ok = True + break + if institution_ok: + break + if institution_ok: + break + if not institution_ok: + continue + + # Step 3: Score all versions, keep best + best: model.PatentEntry | None = None + for patent in versions: + score = _compute_score(patent, first_name, last_name, + orcid, institutions, topics) + if score >= _MIN_CONFIDENCE_SCORE: + patent.confidence_score = score + if best is None or score > best.confidence_score: + best = patent + + if best: + result_patents.append(best) + + result_patents.sort(key=lambda p: p.confidence_score, reverse=True) + + return model.PatentsByAuthorResponse( + author_id=author_id, + author_name=author_name, + patent_count=len(result_patents), + patents=result_patents, + ) + + +def _compute_score( + patent: model.PatentEntry, + first_name: str | None, + last_name: str | None, + orcid: str | None, + institutions: list[str], + topics: list[str], +) -> int: + score = 0 + inventors_lower = [inv.lower() for inv in patent.inventors] + title_abstract = ((patent.title or "") + " " + (patent.abstract or "")).lower() + + # Last name match (+2) + if last_name and any(last_name.lower() in inv for inv in inventors_lower): + score += 2 + + # First name match (+2) + if first_name and any(first_name.lower() in inv for inv in inventors_lower): + score += 2 + + # Institution match (+3) + for institution in institutions: + inst_words = set(institution.lower().split()) + for asg in patent.assignees: + asg_words = set(asg.lower().split()) + meaningful = {w for w in (inst_words & asg_words) if len(w) > 3} + if len(meaningful) >= 2: + score += 3 + break + + # ORCID match (+5) + if orcid and getattr(patent, "orcid", None): + if orcid.lower() in patent.orcid.lower(): + score += 5 + + # Topics match (+1 each, max +3) + topic_score = 0 + for topic in topics: + if topic.lower() in title_abstract: + topic_score += 1 + if topic_score >= 3: + break + score += topic_score + + return score + + +async def _search_both_indices(client, last_name): + import asyncio + epo_result, uspto_result = await asyncio.gather( + client.search_epo(client.epo_query_by_inventor(last_name)), + client.search_uspto(client.uspto_query_by_inventor(last_name)), + ) + return epo_result, uspto_result + + +def _parse_epo_hits(data: dict) -> list[model.PatentEntry]: + patents = [] + for hit in data.get("hits", {}).get("hits", []): + src = hit.get("_source", {}) + inventors = src.get("inventors_name") or [] + applicants = src.get("applicants_name") or [] + ipc = src.get("ipc") or [] + patents.append(model.PatentEntry( + patent_id=f"EP{src.get('doc_number', hit.get('_id', ''))}", + source="EPO", + title=src.get("title_en") or src.get("title_de"), + abstract=src.get("abstract"), + publication_date=src.get("date_publication"), + publication_year=src.get("date_publication_year"), + inventors=inventors if isinstance(inventors, list) else [inventors], + assignees=applicants if isinstance(applicants, list) else [applicants], + ipc=ipc if isinstance(ipc, list) else [ipc], + country=src.get("country", "EP"), + )) + return patents + + +def _parse_uspto_hits(data: dict) -> list[model.PatentEntry]: + patents = [] + for hit in data.get("hits", {}).get("hits", []): + src = hit.get("_source", {}) + inventors = src.get("inventors_names") or [] + assignees = src.get("assignees_orgs") or [] + ipc = src.get("ipcr") or [] + patents.append(model.PatentEntry( + patent_id=f"US{src.get('publication_number', hit.get('_id', ''))}", + source="USPTO", + title=src.get("title"), + abstract=src.get("abstract"), + publication_date=src.get("publication_date"), + publication_year=src.get("publication_year"), + inventors=inventors if isinstance(inventors, list) else [inventors], + assignees=assignees if isinstance(assignees, list) else [assignees], + ipc=ipc if isinstance(ipc, list) else [ipc], + country=src.get("country", "US"), + )) + return patents + + +def _get_author(author_id: str) -> Author | None: + short_id = author_id.replace("https://openalex.org/", "") + result = person_logic.search_persons(author_id=short_id) + return result.results[0] if result.results else None + + +def _extract_last_name(name: str | None) -> str | None: + if not name: + return None + parts = name.strip().split() + return parts[-1] if parts else None + + +def _extract_first_name(name: str | None) -> str | None: + if not name: + return None + parts = name.strip().split() + return parts[0] if len(parts) > 1 else None + + +def _extract_orcid(author: Author) -> str | None: + if author.ids and author.ids.orcid: + return str(author.ids.orcid) + return str(author.orcid) if author.orcid else None + + +def _extract_all_institutions(author: Author) -> list[str]: + institutions: set[str] = set() + for inst in (author.last_known_institutions or []): + if inst and inst.display_name: + institutions.add(inst.display_name) + for aff in (author.affiliations or []): + inst = getattr(aff, "institution", None) + if inst and getattr(inst, "display_name", None): + institutions.add(inst.display_name) + return list(institutions) + + +def _extract_topics(author: Author) -> list[str]: + return [t.display_name for t in (author.topics or []) if t and t.display_name] \ No newline at end of file diff --git a/service/src/main/inse/patents/model.py b/service/src/main/inse/patents/model.py new file mode 100644 index 00000000..2bed084c --- /dev/null +++ b/service/src/main/inse/patents/model.py @@ -0,0 +1,22 @@ +from pydantic import BaseModel, Field + + +class PatentEntry(BaseModel): + patent_id: str + source: str # "EPO" or "USPTO" + title: str | None = None + abstract: str | None = None + publication_date: str | None = None + publication_year: str | None = None + inventors: list[str] = Field(default_factory=list) + assignees: list[str] = Field(default_factory=list) + ipc: list[str] = Field(default_factory=list) + country: str | None = None + confidence_score: int = 0 + + +class PatentsByAuthorResponse(BaseModel): + author_id: str + author_name: str | None = None + patent_count: int + patents: list[PatentEntry] \ No newline at end of file diff --git a/service/src/main/inse/patents/service.py b/service/src/main/inse/patents/service.py new file mode 100644 index 00000000..7bdcbb82 --- /dev/null +++ b/service/src/main/inse/patents/service.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" + REST API for patent matching by author. +""" +from fastapi import APIRouter + +from . import logic +from . import model + +router = APIRouter(prefix="/api/inse-service/authors", tags=["Patents"]) + + +@router.get( + "/{author_id}/patents", + operation_id="getPatentsByAuthor", + response_model=model.PatentsByAuthorResponse, + summary="Get patents matched to an author by name.", +) +async def get_patents_by_author(author_id: str): + return await logic.get_patents_by_author_id(author_id) \ No newline at end of file diff --git a/webapp/src/app/api/api/patents.service.ts b/webapp/src/app/api/api/patents.service.ts new file mode 100644 index 00000000..880467cb --- /dev/null +++ b/webapp/src/app/api/api/patents.service.ts @@ -0,0 +1,167 @@ +/** + * Innovation Search Engine API + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Inject, Injectable, Optional } from '@angular/core'; +import { + HttpClient, + HttpHeaders, + HttpParams, + HttpResponse, + HttpEvent, + HttpParameterCodec, + HttpContext, +} from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; +import { BaseService } from '../api.base.service'; + +export interface PatentEntry { + patent_id: string; + source: string; + title: string | null; + abstract: string | null; + publication_date: string | null; + publication_year: string | null; + inventors: string[]; + assignees: string[]; + ipc: string[]; + country: string | null; + confidence_score: number; +} + +export interface PatentsByAuthorResponse { + author_id: string; + author_name: string | null; + patent_count: number; + patents: PatentEntry[]; +} + +@Injectable({ + providedIn: 'root', +}) +export class PatentsService extends BaseService { + constructor( + protected httpClient: HttpClient, + @Optional() @Inject(BASE_PATH) basePath: string | string[], + @Optional() configuration?: Configuration, + ) { + super(basePath, configuration); + } + + /** + * Get patents by author. + * @endpoint get /api/inse-service/authors/{author_id}/patents + * @param authorId + * @param observe + * @param reportProgress + */ + public getPatentsByAuthor( + authorId: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getPatentsByAuthor( + authorId: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getPatentsByAuthor( + authorId: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getPatentsByAuthor( + authorId: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (authorId === null || authorId === undefined) { + throw new Error( + 'Required parameter authorId was null or undefined when calling getPatentsByAuthor.', + ); + } + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam({ + name: 'authorId', + value: authorId, + in: 'path', + style: 'simple', + explode: false, + dataType: 'string', + dataFormat: undefined, + })}/patents`; + + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } +} diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 23a85220..7b6ab180 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -126,6 +126,13 @@ export const routes: Routes = [ (mod) => mod.PersonFundingComponent, ), }, + { + path: 'patents', + loadComponent: () => + import('./modules/person-patents/person-patents.component').then( + (mod) => mod.PersonPatentsComponent, + ), + }, ], }, { diff --git a/webapp/src/app/modules/person-patents/person-patents.component.html b/webapp/src/app/modules/person-patents/person-patents.component.html new file mode 100644 index 00000000..8d083698 --- /dev/null +++ b/webapp/src/app/modules/person-patents/person-patents.component.html @@ -0,0 +1,150 @@ +@if (loading) { +

Lade Patente...

+} @else if (error) { +

Fehler beim Laden der Patente.

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

Keine Patente gefunden.

+} @else { +
+ +
+

+ {{ filteredPatents.length }} + Patente +

+

+ {{ getEpoCount() }} + EPO +

+

+ {{ getUsptoCount() }} + USPTO +

+
+ +
+ +
+
+
+ Filter nach Quelle: + + + +
+ +
+ + + + + + + + + + + + @for (patent of getPagedPatents(); track patent.patent_id) { + + + + + + + } + +
PatentQuelleJahrScore
{{ patent.title ?? patent.patent_id }} + + {{ patent.source }} + + {{ patent.publication_year ?? '-' }}{{ patent.confidence_score }}
+ + @if (hasPagination()) { + + } +
+ + @if (selectedPatent) { +
+

{{ selectedPatent.title ?? selectedPatent.patent_id }}

+ +
+
+ Quelle + {{ selectedPatent.source }} +
+
+ Patent-Nr. + {{ selectedPatent.patent_id }} +
+
+ Datum + {{ formatDate(selectedPatent.publication_date) }} +
+
+ Relevanz + {{ selectedPatent.confidence_score }} +
+
+ + @if (selectedPatent.abstract) { +
+

Abstract

+

{{ selectedPatent.abstract }}

+
+ } + +
+

Erfinder

+
    + @for (inventor of selectedPatent.inventors; track inventor) { +
  • {{ inventor }}
  • + } +
+
+ + @if (selectedPatent.assignees.length > 0) { +
+

Anmelder

+
    + @for (assignee of selectedPatent.assignees; track assignee) { +
  • {{ assignee }}
  • + } +
+
+ } + + @if (selectedPatent.ipc.length > 0) { +
+

Klassifikation (IPC)

+
    + @for (ipc of selectedPatent.ipc; track ipc) { +
  • {{ ipc }}
  • + } +
+
+ } +
+ } @else { +
+

Klicke auf ein Patent für Details.

+
+ } + +
+
+} diff --git a/webapp/src/app/modules/person-patents/person-patents.component.scss b/webapp/src/app/modules/person-patents/person-patents.component.scss new file mode 100644 index 00000000..762cf458 --- /dev/null +++ b/webapp/src/app/modules/person-patents/person-patents.component.scss @@ -0,0 +1,293 @@ +.message { + padding: 16px; + color: #666; +} + +.patents-container { + padding: 16px; + display: flex; + flex-direction: column; + gap: 16px; +} + +.patents-summary { + margin-bottom: 8px; + display: flex; + gap: 24px; + + .summary-line { + margin: 0; + font-size: 14px; + color: #333; + } + + .summary-label { + color: #333; + } + + .summary-value { + font-weight: 600; + color: #333; + } +} + +.filter-bar { + display: flex; + align-items: center; + gap: 8px; + flex-wrap: wrap; + + span { + font-weight: 500; + color: #555; + } + + button { + padding: 6px 14px; + border: 1px solid #ccc; + border-radius: 20px; + background: white; + cursor: pointer; + font-size: 14px; + + &:hover { + background: #f0f0f0; + } + + &.active { + background: #f0f6ff; + color: #0b63ce; + border-color: #bdd4ff; + font-weight: 600; + } + } +} + +.sort-control { + display: inline-flex; + align-items: center; + gap: 6px; + width: fit-content; + padding: 10px 14px; + border-radius: 20px; + background: #f2f2f2; + color: #333; + font-size: 14px; + + span { + color: #555; + } + + select { + border: 0; + background: transparent; + color: #111827; + font: inherit; + cursor: pointer; + outline: none; + } +} + +.patents-content { + display: flex; + gap: 24px; + align-items: flex-start; +} + +.patents-list { + flex: 1; + + .patents-list-toolbar { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + margin-bottom: 18px; + flex-wrap: wrap; + } + + table { + width: 100%; + border-collapse: collapse; + + th { + text-align: left; + padding: 10px 12px; + border-bottom: 2px solid #e0e0e0; + font-weight: 600; + color: #333; + } + + tr { + cursor: pointer; + + &:hover { + background: #f5f5f5; + } + + &.selected { + background: #f0f0f0; + } + } + + td { + padding: 10px 12px; + border-bottom: 1px solid #f0f0f0; + } + + .patent-title { + color: #333; + font-weight: 500; + max-width: 400px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + } + } +} + +.source-badge { + display: inline-flex; + align-items: center; + padding: 3px 10px; + border-radius: 999px; + font-size: 0.75rem; + font-weight: 700; + + &--epo { + background: #effaf3; + color: #24834f; + border: 1px solid #bdebcf; + } + + &--uspto { + background: #f0f6ff; + color: #0b63ce; + border: 1px solid #bdd4ff; + } +} + +.patent-detail { + width: 440px; + border: 1px solid #e0e0e0; + border-radius: 8px; + padding: 20px; + background: #fafafa; + + &.empty { + display: flex; + align-items: center; + justify-content: center; + color: #999; + min-height: 200px; + } + + h3 { + margin: 0 0 16px 0; + font-size: 16px; + color: #333; + line-height: 1.4; + } + + h4 { + margin: 16px 0 8px 0; + font-size: 14px; + color: #555; + font-weight: 600; + } + + p { + font-size: 13px; + color: #444; + line-height: 1.6; + margin: 0; + } +} + +.detail-stats { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 10px; + margin-bottom: 16px; + + .stat { + background: white; + border: 1px solid #e0e0e0; + border-radius: 8px; + padding: 10px; + text-align: center; + + .stat-label { + display: block; + font-size: 11px; + color: #666; + margin-bottom: 4px; + text-transform: uppercase; + letter-spacing: 0.03em; + } + + .stat-value { + display: block; + font-size: 15px; + font-weight: bold; + color: #333; + } + } +} + +.detail-section { + margin-top: 12px; + padding-top: 12px; + border-top: 1px solid #eee; +} + +.tag-list { + display: flex; + flex-wrap: wrap; + gap: 6px; + margin: 0; + padding: 0; + list-style: none; + + &--compact .tag { + font-size: 0.75rem; + padding: 3px 8px; + } +} + +.tag { + padding: 4px 10px; + border-radius: 999px; + background: #f0f6ff; + border: 1px solid #dbeafe; + color: #1e40af; + font-size: 0.8rem; + line-height: 1.3; +} + +.pagination { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + margin-top: 12px; + + button { + padding: 4px 10px; + border: 1px solid #d0d0d0; + border-radius: 6px; + background: white; + cursor: pointer; + font-size: 12px; + + &:disabled { + opacity: 0.5; + cursor: default; + } + } + + span { + font-size: 12px; + color: #666; + } +} diff --git a/webapp/src/app/modules/person-patents/person-patents.component.ts b/webapp/src/app/modules/person-patents/person-patents.component.ts new file mode 100644 index 00000000..4d73e943 --- /dev/null +++ b/webapp/src/app/modules/person-patents/person-patents.component.ts @@ -0,0 +1,157 @@ +import { Component, OnInit, inject } from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { ActivatedRoute, Router } from '@angular/router'; +import { PatentsService, PatentEntry } from '../../api/api/patents.service'; + +type SortMode = 'score' | 'date' | 'title'; +type SourceFilter = 'all' | 'EPO' | 'USPTO'; + +@Component({ + selector: 'app-person-patents', + imports: [CommonModule], + templateUrl: './person-patents.component.html', + styleUrl: './person-patents.component.scss', +}) +export class PersonPatentsComponent implements OnInit { + private route = inject(ActivatedRoute); + private router = inject(Router); + private patentsApi = inject(PatentsService); + + patents: PatentEntry[] = []; + filteredPatents: PatentEntry[] = []; + authorName: string | null = null; + selectedPatent: PatentEntry | null = null; + + loading = true; + error = false; + + activeFilter: SourceFilter = 'all'; + sortMode: SortMode = 'score'; + + selectedPage = 1; + readonly pageSize = 10; + + ngOnInit(): void { + this.route.parent?.paramMap.subscribe((params) => { + const authorId = params.get('id') ?? ''; + + const filterFromUrl = this.route.snapshot.queryParamMap.get('filter'); + const sortFromUrl = this.route.snapshot.queryParamMap.get('sortBy'); + + if (this.isValidFilter(filterFromUrl)) { + this.activeFilter = filterFromUrl; + } + if (this.isValidSortMode(sortFromUrl)) { + this.sortMode = sortFromUrl; + } + + if (authorId) { + this.patentsApi.getPatentsByAuthor(authorId, 'body').subscribe({ + next: (result) => { + this.patents = result.patents ?? []; + this.authorName = result.author_name ?? null; + this.applyFilter(); + this.loading = false; + }, + error: () => { + this.error = true; + this.loading = false; + }, + }); + } + }); + } + + setFilter(filter: SourceFilter): void { + this.activeFilter = filter; + this.selectedPage = 1; + this.selectedPatent = null; + this.applyFilter(); + this.updateQueryParams(); + } + + setSortMode(sortMode: SortMode): void { + this.sortMode = sortMode; + this.applyFilter(); + this.updateQueryParams(); + } + + selectPatent(patent: PatentEntry): void { + this.selectedPatent = patent; + this.updateQueryParams(); + } + + private applyFilter(): void { + let patents = this.patents; + + if (this.activeFilter !== 'all') { + patents = patents.filter((p) => p.source === this.activeFilter); + } + + this.filteredPatents = this.sortPatents(patents); + } + + private sortPatents(patents: PatentEntry[]): PatentEntry[] { + return [...patents].sort((a, b) => { + if (this.sortMode === 'score') { + return b.confidence_score - a.confidence_score; + } + if (this.sortMode === 'date') { + return (b.publication_date ?? '').localeCompare(a.publication_date ?? ''); + } + return (a.title ?? '').localeCompare(b.title ?? '', 'de', { sensitivity: 'base' }); + }); + } + + private updateQueryParams(): void { + this.router.navigate([], { + relativeTo: this.route, + queryParams: { + filter: this.activeFilter, + sortBy: this.sortMode, + }, + queryParamsHandling: 'merge', + replaceUrl: true, + }); + } + + private isValidFilter(value: string | null): value is SourceFilter { + return value === 'all' || value === 'EPO' || value === 'USPTO'; + } + + private isValidSortMode(value: string | null): value is SortMode { + return value === 'score' || value === 'date' || value === 'title'; + } + + getPagedPatents(): PatentEntry[] { + const start = (this.selectedPage - 1) * this.pageSize; + return this.filteredPatents.slice(start, start + this.pageSize); + } + + getPageCount(): number { + return Math.max(1, Math.ceil(this.filteredPatents.length / this.pageSize)); + } + + hasPagination(): boolean { + return this.getPageCount() > 1; + } + + setPage(page: number): void { + this.selectedPage = Math.min(Math.max(page, 1), this.getPageCount()); + this.updateQueryParams(); + } + + formatDate(date: string | null): string { + if (!date) return '-'; + const d = date.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3'); + return new Intl.DateTimeFormat('de-DE').format(new Date(d)); + } + + getEpoCount(): number { + return this.patents.filter((p) => p.source === 'EPO').length; + } + + getUsptoCount(): number { + return this.patents.filter((p) => p.source === 'USPTO').length; + } +} diff --git a/webapp/src/app/modules/person/person.component.ts b/webapp/src/app/modules/person/person.component.ts index 8c88f580..bbbb9988 100644 --- a/webapp/src/app/modules/person/person.component.ts +++ b/webapp/src/app/modules/person/person.component.ts @@ -195,6 +195,7 @@ export class PersonComponent { { label: 'Netzwerk', path: 'network', disabled: false }, { label: 'Gründungen', path: 'foundings', disabled: true }, { label: 'Förderungen', path: 'funding', disabled: false }, + { label: 'Patente', path: 'patents', disabled: false }, ]; onInterestingTagClick(selection: { id: string; name: string }): void { -- 2.56.1 From 0dd03e0ae0ea25cccebb24aa5c7a22096b4f2f36 Mon Sep 17 00:00:00 2001 From: taguesokoudjou Date: Mon, 15 Jun 2026 20:27:21 +0200 Subject: [PATCH 2/8] feat: improve patent matching with disambiguation pipeline and caching --- service/src/main/inse/config.py | 6 + .../src/main/inse/patents/author_profile.py | 195 ++++++++++ .../src/main/inse/patents/disambiguation.py | 130 +++++++ .../inse/patents/elastic_search_client.py | 315 +++++++++++++--- service/src/main/inse/patents/logic.py | 350 ++++++------------ service/src/main/inse/patents/model.py | 35 +- service/src/main/inse/patents/pipeline.py | 209 +++++++++++ service/src/main/inse/patents/repository.py | 182 +++++++++ service/src/main/inse/patents/service.py | 58 ++- service/src/main/inse/patents/test_logic.py | 228 ++++++++++++ service/src/main/inse/schema.py | 47 ++- webapp/src/app/api/api/patents.service.ts | 47 +++ .../person-patents.component.html | 26 ++ .../person-patents.component.scss | 29 ++ .../person-patents.component.ts | 99 ++++- 15 files changed, 1642 insertions(+), 314 deletions(-) create mode 100644 service/src/main/inse/patents/author_profile.py create mode 100644 service/src/main/inse/patents/disambiguation.py create mode 100644 service/src/main/inse/patents/pipeline.py create mode 100644 service/src/main/inse/patents/repository.py create mode 100644 service/src/main/inse/patents/test_logic.py diff --git a/service/src/main/inse/config.py b/service/src/main/inse/config.py index cdc232d5..cbd9597b 100644 --- a/service/src/main/inse/config.py +++ b/service/src/main/inse/config.py @@ -42,6 +42,12 @@ class Settings(BaseSettings): # Patent elasticsearch config patent_elasticsearch_url: str = "https://inse.nes.uni-due.de/elastic" patent_elasticsearch_api_key: str = "" + patent_es_page_size: int = 500 + patent_es_max_pages: int = 20 + patent_disambiguation_min_score_full_name: int = 6 + patent_disambiguation_min_score_partial: int = 8 + patent_link_cache_ttl_hours: int = 168 + patent_publication_context_max_pages: int = 10 # LLM config diff --git a/service/src/main/inse/patents/author_profile.py b/service/src/main/inse/patents/author_profile.py new file mode 100644 index 00000000..517a2a89 --- /dev/null +++ b/service/src/main/inse/patents/author_profile.py @@ -0,0 +1,195 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" + Build author search profiles and publication context for patent disambiguation. +""" +from __future__ import annotations + +import logging +from dataclasses import dataclass, field + +from .. import config +from ..models.author import Author +from ..works.search_client import OpenAlexWorksSearchClient + +logger = logging.getLogger(__name__) + +_NAME_PREFIXES = frozenset({ + "dr", "prof", "mr", "mrs", "ms", "dipl", "ing", "med", +}) + + +@dataclass +class AuthorProfile: + author_id: str + display_name: str + first_name: str | None + last_name: str | None + name_variants: list[str] = field(default_factory=list) + institutions: list[str] = field(default_factory=list) + topics: list[str] = field(default_factory=list) + orcid: str | None = None + coauthor_last_names: set[str] = field(default_factory=set) + publication_keywords: set[str] = field(default_factory=set) + + +def normalize_author_id(author_id: str) -> str: + short_id = author_id.strip().removeprefix("https://openalex.org/") + return f"https://openalex.org/{short_id}" + + +def build_author_profile(author: Author, author_id: str) -> AuthorProfile: + display_name = author.display_name or "" + first_name, last_name = extract_name_parts(display_name) + institutions = _extract_institutions(author) + topics = [ + topic.display_name + for topic in (author.topics or []) + if topic and topic.display_name + ] + orcid = _extract_orcid(author) + variants = _build_name_variants(first_name, last_name, display_name) + + return AuthorProfile( + author_id=normalize_author_id(author_id), + display_name=display_name, + first_name=first_name, + last_name=last_name, + name_variants=variants, + institutions=institutions, + topics=topics, + orcid=orcid, + ) + + +async def enrich_with_publication_context( + profile: AuthorProfile, + works_client: OpenAlexWorksSearchClient | None = None, +) -> AuthorProfile: + client = works_client or OpenAlexWorksSearchClient() + settings = config.settings + page = 1 + page_size = 100 + max_pages = settings.patent_publication_context_max_pages + normalized_id = profile.author_id + + try: + while page <= max_pages: + data = await client.search_author_works( + normalized_id.removeprefix("https://openalex.org/"), + page, + page_size, + ) + hits = data.get("hits", {}).get("hits", []) + total = data.get("hits", {}).get("total", {}).get("value", 0) + + for hit in hits: + source = hit.get("_source", {}) + _collect_coauthors(source, normalized_id, profile.coauthor_last_names) + _collect_publication_keywords(source, profile.publication_keywords) + + if not hits or page * page_size >= total: + break + page += 1 + except Exception as exc: + logger.warning( + "Publication context unavailable for author %s: %s", + profile.author_id, + exc, + ) + + return profile + + +def extract_name_parts(display_name: str | None) -> tuple[str | None, str | None]: + if not display_name: + return None, None + + parts = [ + part + for part in display_name.strip().split() + if part.lower().rstrip(".") not in _NAME_PREFIXES + ] + if not parts: + return None, None + if len(parts) == 1: + return None, parts[0] + return parts[0], parts[-1] + + +def _build_name_variants( + first_name: str | None, + last_name: str | None, + display_name: str, +) -> list[str]: + variants: list[str] = [] + if display_name.strip(): + variants.append(display_name.strip()) + if first_name and last_name: + variants.append(f"{first_name} {last_name}") + variants.append(f"{last_name}, {first_name}") + variants.append(f"{last_name} {first_name}") + if len(first_name) > 0: + variants.append(f"{first_name[0]}. {last_name}") + if last_name: + variants.append(last_name) + + seen: set[str] = set() + unique: list[str] = [] + for variant in variants: + key = variant.lower() + if key not in seen: + seen.add(key) + unique.append(variant) + return unique + + +def _collect_coauthors( + source: dict, + author_id: str, + coauthor_last_names: set[str], +) -> None: + for authorship in source.get("authorships", []): + author = authorship.get("author", {}) + other_id = author.get("id", "") + if not other_id or other_id == author_id: + continue + other_name = author.get("display_name", "") + _, last_name = extract_name_parts(other_name) + if last_name: + coauthor_last_names.add(last_name.lower()) + + +def _collect_publication_keywords(source: dict, keywords: set[str]) -> None: + for topic in source.get("topics", []) or []: + display_name = topic.get("display_name") + if display_name: + keywords.add(display_name.lower()) + + primary_topic = source.get("primary_topic") or {} + display_name = primary_topic.get("display_name") + if display_name: + keywords.add(display_name.lower()) + + for keyword in source.get("keywords", []) or []: + display_name = keyword.get("display_name") + if display_name: + keywords.add(display_name.lower()) + + +def _extract_orcid(author: Author) -> str | None: + if author.ids and author.ids.orcid: + return str(author.ids.orcid) + return str(author.orcid) if author.orcid else None + + +def _extract_institutions(author: Author) -> list[str]: + institutions: set[str] = set() + for institution in author.last_known_institutions or []: + if institution and institution.display_name: + institutions.add(institution.display_name) + for affiliation in author.affiliations or []: + inst = getattr(affiliation, "institution", None) + if inst and getattr(inst, "display_name", None): + institutions.add(inst.display_name) + return list(institutions) diff --git a/service/src/main/inse/patents/disambiguation.py b/service/src/main/inse/patents/disambiguation.py new file mode 100644 index 00000000..6c278253 --- /dev/null +++ b/service/src/main/inse/patents/disambiguation.py @@ -0,0 +1,130 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" + Rule-based patent-author disambiguation with publication cross-validation. +""" +from __future__ import annotations + +from dataclasses import dataclass + +from .. import config +from . import model +from .author_profile import AuthorProfile + + +@dataclass +class DisambiguationResult: + score: int + signals: list[str] + accepted: bool + + +def disambiguate_patent_group( + versions: list[model.PatentEntry], + profile: AuthorProfile, +) -> model.PatentEntry | None: + best: model.PatentEntry | None = None + best_result: DisambiguationResult | None = None + + for patent in versions: + result = score_patent(patent, profile) + if not result.accepted: + continue + patent.confidence_score = result.score + patent.match_signals = result.signals + if best is None or result.score > best_result.score: # type: ignore[union-attr] + best = patent + best_result = result + + return best + + +def score_patent( + patent: model.PatentEntry, + profile: AuthorProfile, +) -> DisambiguationResult: + settings = config.settings + signals: list[str] = [] + score = 0 + + inventors_lower = [inventor.lower() for inventor in patent.inventors] + title_abstract = ((patent.title or "") + " " + (patent.abstract or "")).lower() + + full_name_match = False + if profile.first_name and profile.last_name: + full_name_match = any( + profile.first_name.lower() in inventor + and profile.last_name.lower() in inventor + for inventor in inventors_lower + ) + if full_name_match: + score += 5 + signals.append("full_name_match") + + if profile.last_name and any(profile.last_name.lower() in inventor for inventor in inventors_lower): + score += 2 + if "last_name_match" not in signals: + signals.append("last_name_match") + + if profile.first_name and any(profile.first_name.lower() in inventor for inventor in inventors_lower): + score += 2 + if "first_name_match" not in signals: + signals.append("first_name_match") + + for institution in profile.institutions: + institution_words = set(institution.lower().split()) + for assignee in patent.assignees: + assignee_words = set(assignee.lower().split()) + meaningful = { + word for word in (institution_words & assignee_words) if len(word) > 3 + } + if len(meaningful) >= 2: + score += 3 + signals.append("institution_match") + break + if "institution_match" in signals: + break + + if profile.orcid and patent.orcid and profile.orcid.lower() in patent.orcid.lower(): + score += 5 + signals.append("orcid_match") + + topic_hits = 0 + for topic in profile.topics: + if topic.lower() in title_abstract: + topic_hits += 1 + score += 1 + if topic_hits == 1: + signals.append("topic_match") + if topic_hits >= 3: + break + + coauthor_hits = 0 + for coauthor_last_name in profile.coauthor_last_names: + if any(coauthor_last_name in inventor for inventor in inventors_lower): + coauthor_hits += 1 + score += 2 + if coauthor_hits == 1: + signals.append("coauthor_match") + if coauthor_hits >= 2: + break + + keyword_hits = 0 + for keyword in profile.publication_keywords: + if len(keyword) > 4 and keyword in title_abstract: + keyword_hits += 1 + score += 1 + if keyword_hits == 1: + signals.append("publication_topic_match") + if keyword_hits >= 2: + break + + threshold = ( + settings.patent_disambiguation_min_score_full_name + if full_name_match + else settings.patent_disambiguation_min_score_partial + ) + has_name_signal = "last_name_match" in signals or "full_name_match" in signals + accepted = score >= threshold and has_name_signal + + return DisambiguationResult(score=score, signals=signals, accepted=accepted) diff --git a/service/src/main/inse/patents/elastic_search_client.py b/service/src/main/inse/patents/elastic_search_client.py index ac20fbb2..5fb58366 100644 --- a/service/src/main/inse/patents/elastic_search_client.py +++ b/service/src/main/inse/patents/elastic_search_client.py @@ -3,15 +3,51 @@ """ HTTP client for patent searches in EPO and USPTO Elasticsearch indices. """ +from __future__ import annotations + +import logging from typing import Any import httpx from .. import config +from . import model +from .author_profile import AuthorProfile + +logger = logging.getLogger(__name__) EPO_INDEX = "epo_index_1.0" USPTO_INDEX = "uspto_patents_2.0" +_EPO_SOURCE_FIELDS = [ + "doc_number", + "country", + "kind", + "date_publication", + "date_publication_year", + "title_en", + "title_de", + "abstract", + "inventors_name", + "applicants_name", + "ipc", + "ipc_text", +] + +_USPTO_SOURCE_FIELDS = [ + "publication_number", + "country", + "publication_date", + "publication_year", + "title", + "abstract", + "inventors_names", + "inventors_names_text", + "assignees_orgs", + "ipcr", + "ipcr_text", +] + class MissingApiKeyError(Exception): pass @@ -38,84 +74,128 @@ class PatentSearchClient: "Content-Type": "application/json", } - def epo_query_by_inventor(self, last_name: str, size: int = 100) -> dict[str, Any]: - """Search EPO index by inventor last name.""" + def epo_query_by_profile( + self, + profile: AuthorProfile, + page: int, + size: int, + ) -> dict[str, Any]: return { + "from": (page - 1) * size, "size": size, "track_total_hits": True, - "_source": [ - "doc_number", - "country", - "kind", - "date_publication", - "date_publication_year", - "title_en", - "title_de", - "abstract", - "inventors_name", - "applicants_name", - "ipc", - "ipc_text", - ], + "_source": _EPO_SOURCE_FIELDS, + "query": self._inventor_bool_query( + profile, + text_field="inventors_name_text", + keyword_field="inventors_name", + ), + } + + def uspto_query_by_profile( + self, + profile: AuthorProfile, + page: int, + size: int, + ) -> dict[str, Any]: + return { + "from": (page - 1) * size, + "size": size, + "track_total_hits": True, + "_source": _USPTO_SOURCE_FIELDS, + "query": self._inventor_bool_query( + profile, + text_field="inventors_names_text", + keyword_field="inventors_names", + ), + } + + def epo_query_by_patent_id(self, patent_id: str) -> dict[str, Any]: + doc_number = patent_id.removeprefix("EP") + return { + "size": 1, + "track_total_hits": True, + "_source": _EPO_SOURCE_FIELDS, "query": { "bool": { "should": [ - { - "match": { - "inventors_name_text": { - "query": last_name, - "operator": "and", - } - } - }, - { - "term": { - "inventors_name": last_name - } - }, + {"term": {"doc_number": doc_number}}, + {"term": {"_id": patent_id}}, ], "minimum_should_match": 1, - } + }, }, } - def uspto_query_by_inventor(self, last_name: str, size: int = 100) -> dict[str, Any]: - """Search USPTO index by inventor last name.""" + def uspto_query_by_patent_id(self, patent_id: str) -> dict[str, Any]: + publication_number = patent_id.removeprefix("US") return { - "size": size, + "size": 1, "track_total_hits": True, - "_source": [ - "publication_number", - "country", - "publication_date", - "publication_year", - "title", - "abstract", - "inventors_names", - "inventors_names_text", - "assignees_orgs", - "ipcr", - "ipcr_text", - ], + "_source": _USPTO_SOURCE_FIELDS, "query": { "bool": { "should": [ - { - "match": { - "inventors_names_text": { - "query": last_name, - "operator": "and", - } - } - }, - { - "term": { - "inventors_names": last_name - } - }, + {"term": {"publication_number": publication_number}}, + {"term": {"_id": patent_id}}, ], "minimum_should_match": 1, - } + }, + }, + } + + @staticmethod + def _inventor_bool_query( + profile: AuthorProfile, + *, + text_field: str, + keyword_field: str, + ) -> dict[str, Any]: + should: list[dict[str, Any]] = [] + + if profile.first_name and profile.last_name: + full_name = f"{profile.first_name} {profile.last_name}" + should.extend([ + { + "match": { + text_field: { + "query": full_name, + "operator": "and", + }, + }, + }, + { + "match_phrase": { + text_field: f"{profile.last_name}, {profile.first_name}", + }, + }, + { + "bool": { + "must": [ + {"term": {keyword_field: profile.last_name}}, + {"match": {text_field: profile.first_name}}, + ], + }, + }, + ]) + + for variant in profile.name_variants: + should.append({ + "match": { + text_field: { + "query": variant, + "operator": "and", + }, + }, + }) + + if profile.last_name: + should.append({"term": {keyword_field: profile.last_name}}) + + return { + "bool": { + "should": should, + "minimum_should_match": 1, }, } @@ -125,6 +205,66 @@ class PatentSearchClient: async def search_uspto(self, payload: dict[str, Any]) -> dict[str, Any]: return await self._search(USPTO_INDEX, payload) + async def fetch_all_epo(self, profile: AuthorProfile) -> tuple[int, list[dict[str, Any]]]: + return await self._fetch_all_pages( + profile, + self.epo_query_by_profile, + self.search_epo, + ) + + async def fetch_all_uspto(self, profile: AuthorProfile) -> tuple[int, list[dict[str, Any]]]: + return await self._fetch_all_pages( + profile, + self.uspto_query_by_profile, + self.search_uspto, + ) + + async def lookup_patent(self, patent_id: str) -> model.PatentEntry | None: + source = patent_id[:2].upper() + if source == "EP": + data = await self.search_epo(self.epo_query_by_patent_id(patent_id)) + patents = parse_epo_hits(data) + elif source == "US": + data = await self.search_uspto(self.uspto_query_by_patent_id(patent_id)) + patents = parse_uspto_hits(data) + else: + return None + return patents[0] if patents else None + + async def _fetch_all_pages( + self, + profile: AuthorProfile, + query_builder, + search_fn, + ) -> tuple[int, list[dict[str, Any]]]: + settings = config.settings + page = 1 + page_size = settings.patent_es_page_size + max_pages = settings.patent_es_max_pages + total_hits = 0 + all_hits: list[dict[str, Any]] = [] + + while page <= max_pages: + payload = query_builder(profile, page, page_size) + data = await search_fn(payload) + total_hits = data.get("hits", {}).get("total", {}).get("value", 0) + hits = data.get("hits", {}).get("hits", []) + all_hits.extend(hits) + + if not hits or page * page_size >= total_hits: + break + page += 1 + + if page > max_pages and page * page_size < total_hits: + logger.warning( + "Patent search truncated for author %s at %s pages (total hits: %s).", + profile.author_id, + max_pages, + total_hits, + ) + + return total_hits, all_hits + async def _search(self, index: str, payload: dict[str, Any]) -> dict[str, Any]: async with httpx.AsyncClient( base_url=self.base_url, @@ -137,4 +277,57 @@ class PatentSearchClient: json=payload, ) response.raise_for_status() - return response.json() \ No newline at end of file + return response.json() + + +def _normalize_str_list(value: Any) -> list[str]: + if value is None: + return [] + if isinstance(value, list): + return [str(item) for item in value if item is not None and str(item).strip()] + return [str(value)] if str(value).strip() else [] + + +def _optional_str(value: Any) -> str | None: + if value is None: + return None + text = str(value).strip() + return text or None + + +def parse_epo_hits(data: dict[str, Any]) -> list[model.PatentEntry]: + patents: list[model.PatentEntry] = [] + for hit in data.get("hits", {}).get("hits", []): + source = hit.get("_source", {}) + patents.append(model.PatentEntry( + patent_id=f"EP{source.get('doc_number', hit.get('_id', ''))}", + source="EPO", + title=source.get("title_en") or source.get("title_de"), + abstract=source.get("abstract"), + publication_date=_optional_str(source.get("date_publication")), + publication_year=_optional_str(source.get("date_publication_year")), + inventors=_normalize_str_list(source.get("inventors_name")), + assignees=_normalize_str_list(source.get("applicants_name")), + ipc=_normalize_str_list(source.get("ipc")), + country=source.get("country", "EP"), + )) + return patents + + +def parse_uspto_hits(data: dict[str, Any]) -> list[model.PatentEntry]: + patents: list[model.PatentEntry] = [] + for hit in data.get("hits", {}).get("hits", []): + source = hit.get("_source", {}) + patents.append(model.PatentEntry( + patent_id=f"US{source.get('publication_number', hit.get('_id', ''))}", + source="USPTO", + title=source.get("title"), + abstract=source.get("abstract"), + publication_date=_optional_str(source.get("publication_date")), + publication_year=_optional_str(source.get("publication_year")), + inventors=_normalize_str_list(source.get("inventors_names")), + assignees=_normalize_str_list(source.get("assignees_orgs")), + ipc=_normalize_str_list(source.get("ipcr")), + country=source.get("country", "US"), + )) + return patents diff --git a/service/src/main/inse/patents/logic.py b/service/src/main/inse/patents/logic.py index e503f042..ecd75b2f 100644 --- a/service/src/main/inse/patents/logic.py +++ b/service/src/main/inse/patents/logic.py @@ -1,269 +1,155 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- """ - Business logic for patent matching by author name. + Business logic for patent matching by author. """ +from __future__ import annotations + import logging -from collections import defaultdict import httpx from fastapi import HTTPException +from sqlalchemy.orm import Session +from starlette.status import HTTP_400_BAD_REQUEST from starlette.status import HTTP_502_BAD_GATEWAY from starlette.status import HTTP_503_SERVICE_UNAVAILABLE -from ..persons import logic as person_logic -from ..models.author import Author from . import model -from .elastic_search_client import MissingApiKeyError -from .elastic_search_client import PatentSearchClient +from . import repository +from .author_profile import normalize_author_id +from .elastic_search_client import MissingApiKeyError, PatentSearchClient +from .pipeline import rebuild_author_patents, load_author_patents logger = logging.getLogger(__name__) -_MIN_CONFIDENCE_SCORE = 4 - async def get_patents_by_author_id( author_id: str, + db: Session, + *, + refresh: bool = False, client: PatentSearchClient | None = None, ) -> model.PatentsByAuthorResponse: - search_client = client or PatentSearchClient() + normalized_id = normalize_author_id(author_id) + build_meta = repository.get_build_meta(db, normalized_id) - author = _get_author(author_id) - if not author: - return model.PatentsByAuthorResponse( - author_id=author_id, - author_name=None, - patent_count=0, - patents=[], - ) + if refresh or build_meta is None or not repository.is_cache_fresh(build_meta.built_at): + try: + return await rebuild_author_patents(author_id, db, client=client) + except MissingApiKeyError as exc: + cached = load_author_patents(db, author_id) + if cached.patent_count > 0: + return cached + raise HTTPException( + status_code=HTTP_503_SERVICE_UNAVAILABLE, + detail="Patent search is not configured.", + ) from exc + except httpx.HTTPError as exc: + cached = load_author_patents(db, author_id) + if cached.patent_count > 0: + return cached + raise HTTPException( + status_code=HTTP_502_BAD_GATEWAY, + detail="Patent search request failed.", + ) from exc - author_name = author.display_name - last_name = _extract_last_name(author_name) - first_name = _extract_first_name(author_name) + return load_author_patents(db, author_id) - if not last_name: - return model.PatentsByAuthorResponse( - author_id=author_id, - author_name=author_name, - patent_count=0, - patents=[], - ) - - institutions = _extract_all_institutions(author) - topics = _extract_topics(author) - orcid = _extract_orcid(author) +async def rebuild_patents_for_author( + author_id: str, + db: Session, + *, + client: PatentSearchClient | None = None, +) -> model.PatentsByAuthorResponse: try: - epo_data, uspto_data = await _search_both_indices(search_client, last_name) + return await rebuild_author_patents(author_id, db, client=client) except MissingApiKeyError as exc: - raise HTTPException(status_code=HTTP_503_SERVICE_UNAVAILABLE, - detail="Patent search is not configured.") from exc + raise HTTPException( + status_code=HTTP_503_SERVICE_UNAVAILABLE, + detail="Patent search is not configured.", + ) from exc except httpx.HTTPError as exc: - raise HTTPException(status_code=HTTP_502_BAD_GATEWAY, - detail="Patent search request failed.") from exc + raise HTTPException( + status_code=HTTP_502_BAD_GATEWAY, + detail="Patent search request failed.", + ) from exc - all_patents = _parse_epo_hits(epo_data) + _parse_uspto_hits(uspto_data) - # Group by patent_id to check all versions together - grouped: dict[str, list[model.PatentEntry]] = defaultdict(list) - for patent in all_patents: - grouped[patent.patent_id].append(patent) +async def set_patent_override( + author_id: str, + patent_id: str, + request: model.PatentOverrideRequest, + db: Session, + *, + client: PatentSearchClient | None = None, +) -> model.PatentOverrideResponse: + action = request.action.strip().lower() + if action not in {"include", "exclude"}: + raise HTTPException( + status_code=HTTP_400_BAD_REQUEST, + detail='action must be "include" or "exclude".', + ) - result_patents = [] - for patent_id, versions in grouped.items(): + normalized_id = normalize_author_id(author_id) + patent: model.PatentEntry | None = None - # Step 1: Check if first+last name appear together in ONE inventor entry - # across any version - if first_name and last_name: - name_ok = any( - first_name.lower() in inv.lower() and last_name.lower() in inv.lower() - for version in versions - for inv in version.inventors - ) - if not name_ok: - continue + if action == "include": + links = repository.get_links(db, author_id) + existing = next( + (entry for entry in repository.links_to_patents(links) if entry.patent_id == patent_id), + None, + ) + if existing is not None: + patent = existing + else: + search_client = client or PatentSearchClient() + try: + patent = await search_client.lookup_patent(patent_id) + except MissingApiKeyError as exc: + raise HTTPException( + status_code=HTTP_503_SERVICE_UNAVAILABLE, + detail="Patent search is not configured.", + ) from exc + except httpx.HTTPError as exc: + raise HTTPException( + status_code=HTTP_502_BAD_GATEWAY, + detail="Patent lookup failed.", + ) from exc - # Step 2: Check institution across ALL versions that have assignees - # If ANY version has assignees that don't match our institutions → reject all - versions_with_assignees = [v for v in versions if v.assignees] - if versions_with_assignees: - institution_ok = False - for version in versions_with_assignees: - for institution in institutions: - inst_words = set(institution.lower().split()) - for asg in version.assignees: - asg_words = set(asg.lower().split()) - meaningful = {w for w in (inst_words & asg_words) if len(w) > 3} - if len(meaningful) >= 2: - institution_ok = True - break - if institution_ok: - break - if institution_ok: - break - if not institution_ok: - continue + if patent is None: + raise HTTPException( + status_code=HTTP_400_BAD_REQUEST, + detail=f"Patent {patent_id} was not found in EPO/USPTO indices.", + ) + patent.confidence_score = max(patent.confidence_score, 10) + patent.match_signals = ["manual_include"] - # Step 3: Score all versions, keep best - best: model.PatentEntry | None = None - for patent in versions: - score = _compute_score(patent, first_name, last_name, - orcid, institutions, topics) - if score >= _MIN_CONFIDENCE_SCORE: - patent.confidence_score = score - if best is None or score > best.confidence_score: - best = patent + repository.upsert_override( + db, + normalized_id, + patent_id, + action, + reason=request.reason, + patent=patent, + ) + db.commit() - if best: - result_patents.append(best) - - result_patents.sort(key=lambda p: p.confidence_score, reverse=True) - - return model.PatentsByAuthorResponse( - author_id=author_id, - author_name=author_name, - patent_count=len(result_patents), - patents=result_patents, + return model.PatentOverrideResponse( + author_id=normalized_id, + patent_id=patent_id, + action=action, + reason=request.reason, + patent=patent, ) -def _compute_score( - patent: model.PatentEntry, - first_name: str | None, - last_name: str | None, - orcid: str | None, - institutions: list[str], - topics: list[str], -) -> int: - score = 0 - inventors_lower = [inv.lower() for inv in patent.inventors] - title_abstract = ((patent.title or "") + " " + (patent.abstract or "")).lower() - - # Last name match (+2) - if last_name and any(last_name.lower() in inv for inv in inventors_lower): - score += 2 - - # First name match (+2) - if first_name and any(first_name.lower() in inv for inv in inventors_lower): - score += 2 - - # Institution match (+3) - for institution in institutions: - inst_words = set(institution.lower().split()) - for asg in patent.assignees: - asg_words = set(asg.lower().split()) - meaningful = {w for w in (inst_words & asg_words) if len(w) > 3} - if len(meaningful) >= 2: - score += 3 - break - - # ORCID match (+5) - if orcid and getattr(patent, "orcid", None): - if orcid.lower() in patent.orcid.lower(): - score += 5 - - # Topics match (+1 each, max +3) - topic_score = 0 - for topic in topics: - if topic.lower() in title_abstract: - topic_score += 1 - if topic_score >= 3: - break - score += topic_score - - return score - - -async def _search_both_indices(client, last_name): - import asyncio - epo_result, uspto_result = await asyncio.gather( - client.search_epo(client.epo_query_by_inventor(last_name)), - client.search_uspto(client.uspto_query_by_inventor(last_name)), - ) - return epo_result, uspto_result - - -def _parse_epo_hits(data: dict) -> list[model.PatentEntry]: - patents = [] - for hit in data.get("hits", {}).get("hits", []): - src = hit.get("_source", {}) - inventors = src.get("inventors_name") or [] - applicants = src.get("applicants_name") or [] - ipc = src.get("ipc") or [] - patents.append(model.PatentEntry( - patent_id=f"EP{src.get('doc_number', hit.get('_id', ''))}", - source="EPO", - title=src.get("title_en") or src.get("title_de"), - abstract=src.get("abstract"), - publication_date=src.get("date_publication"), - publication_year=src.get("date_publication_year"), - inventors=inventors if isinstance(inventors, list) else [inventors], - assignees=applicants if isinstance(applicants, list) else [applicants], - ipc=ipc if isinstance(ipc, list) else [ipc], - country=src.get("country", "EP"), - )) - return patents - - -def _parse_uspto_hits(data: dict) -> list[model.PatentEntry]: - patents = [] - for hit in data.get("hits", {}).get("hits", []): - src = hit.get("_source", {}) - inventors = src.get("inventors_names") or [] - assignees = src.get("assignees_orgs") or [] - ipc = src.get("ipcr") or [] - patents.append(model.PatentEntry( - patent_id=f"US{src.get('publication_number', hit.get('_id', ''))}", - source="USPTO", - title=src.get("title"), - abstract=src.get("abstract"), - publication_date=src.get("publication_date"), - publication_year=src.get("publication_year"), - inventors=inventors if isinstance(inventors, list) else [inventors], - assignees=assignees if isinstance(assignees, list) else [assignees], - ipc=ipc if isinstance(ipc, list) else [ipc], - country=src.get("country", "US"), - )) - return patents - - -def _get_author(author_id: str) -> Author | None: - short_id = author_id.replace("https://openalex.org/", "") - result = person_logic.search_persons(author_id=short_id) - return result.results[0] if result.results else None - - -def _extract_last_name(name: str | None) -> str | None: - if not name: - return None - parts = name.strip().split() - return parts[-1] if parts else None - - -def _extract_first_name(name: str | None) -> str | None: - if not name: - return None - parts = name.strip().split() - return parts[0] if len(parts) > 1 else None - - -def _extract_orcid(author: Author) -> str | None: - if author.ids and author.ids.orcid: - return str(author.ids.orcid) - return str(author.orcid) if author.orcid else None - - -def _extract_all_institutions(author: Author) -> list[str]: - institutions: set[str] = set() - for inst in (author.last_known_institutions or []): - if inst and inst.display_name: - institutions.add(inst.display_name) - for aff in (author.affiliations or []): - inst = getattr(aff, "institution", None) - if inst and getattr(inst, "display_name", None): - institutions.add(inst.display_name) - return list(institutions) - - -def _extract_topics(author: Author) -> list[str]: - return [t.display_name for t in (author.topics or []) if t and t.display_name] \ No newline at end of file +def clear_patent_override( + author_id: str, + patent_id: str, + db: Session, +) -> bool: + deleted = repository.delete_override(db, author_id, patent_id) + if deleted: + db.commit() + return deleted diff --git a/service/src/main/inse/patents/model.py b/service/src/main/inse/patents/model.py index 2bed084c..478e53ff 100644 --- a/service/src/main/inse/patents/model.py +++ b/service/src/main/inse/patents/model.py @@ -1,3 +1,5 @@ +from datetime import datetime + from pydantic import BaseModel, Field @@ -12,11 +14,42 @@ class PatentEntry(BaseModel): assignees: list[str] = Field(default_factory=list) ipc: list[str] = Field(default_factory=list) country: str | None = None + orcid: str | None = None confidence_score: int = 0 + match_signals: list[str] = Field(default_factory=list) + + +class PatentSearchMeta(BaseModel): + epo_total_hits: int = 0 + uspto_total_hits: int = 0 + epo_returned_hits: int = 0 + uspto_returned_hits: int = 0 + matched_count: int = 0 + epo_truncated: bool = False + uspto_truncated: bool = False + coauthor_signals: int = 0 + publication_keywords: int = 0 + rebuild_failed: bool = False class PatentsByAuthorResponse(BaseModel): author_id: str author_name: str | None = None patent_count: int - patents: list[PatentEntry] \ No newline at end of file + patents: list[PatentEntry] + from_cache: bool = False + last_built_at: datetime | None = None + search_meta: PatentSearchMeta | None = None + + +class PatentOverrideRequest(BaseModel): + action: str = Field(description='Either "include" or "exclude".') + reason: str | None = None + + +class PatentOverrideResponse(BaseModel): + author_id: str + patent_id: str + action: str + reason: str | None = None + patent: PatentEntry | None = None diff --git a/service/src/main/inse/patents/pipeline.py b/service/src/main/inse/patents/pipeline.py new file mode 100644 index 00000000..ee1d7492 --- /dev/null +++ b/service/src/main/inse/patents/pipeline.py @@ -0,0 +1,209 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" + Disambiguation pipeline: search patents, score matches, persist links. +""" +from __future__ import annotations + +import logging +from collections import defaultdict +from datetime import datetime, timezone + +import httpx +from sqlalchemy.orm import Session + +from ..persons import logic as person_logic +from ..models.author import Author +from . import model +from .author_profile import ( + AuthorProfile, + build_author_profile, + enrich_with_publication_context, + normalize_author_id, +) +from .disambiguation import disambiguate_patent_group +from .elastic_search_client import ( + MissingApiKeyError, + PatentSearchClient, + parse_epo_hits, + parse_uspto_hits, +) +from . import repository + +logger = logging.getLogger(__name__) + + +async def rebuild_author_patents( + author_id: str, + db: Session, + *, + client: PatentSearchClient | None = None, +) -> model.PatentsByAuthorResponse: + search_client = client or PatentSearchClient() + normalized_id = normalize_author_id(author_id) + + author = _get_author(author_id) + if not author: + return _empty_response(normalized_id) + + profile = build_author_profile(author, author_id) + profile = await enrich_with_publication_context(profile) + + try: + epo_total, epo_hits = await search_client.fetch_all_epo(profile) + uspto_total, uspto_hits = await search_client.fetch_all_uspto(profile) + except MissingApiKeyError: + return _response_from_cache_or_empty( + db, + normalized_id, + author.display_name, + from_cache=True, + rebuild_failed=True, + ) + except httpx.HTTPError as exc: + logger.error("Patent search failed for author %s: %s", normalized_id, exc) + return _response_from_cache_or_empty( + db, + normalized_id, + author.display_name, + from_cache=True, + rebuild_failed=True, + ) + + all_patents = ( + parse_epo_hits({"hits": {"hits": epo_hits}}) + + parse_uspto_hits({"hits": {"hits": uspto_hits}}) + ) + + grouped: dict[str, list[model.PatentEntry]] = defaultdict(list) + for patent in all_patents: + grouped[patent.patent_id].append(patent) + + matched_patents: list[model.PatentEntry] = [] + for versions in grouped.values(): + best = disambiguate_patent_group(versions, profile) + if best is not None: + matched_patents.append(best) + + matched_patents.sort(key=lambda patent: patent.confidence_score, reverse=True) + + search_meta = model.PatentSearchMeta( + epo_total_hits=epo_total, + uspto_total_hits=uspto_total, + epo_returned_hits=len(epo_hits), + uspto_returned_hits=len(uspto_hits), + matched_count=len(matched_patents), + epo_truncated=len(epo_hits) < epo_total, + uspto_truncated=len(uspto_hits) < uspto_total, + coauthor_signals=len(profile.coauthor_last_names), + publication_keywords=len(profile.publication_keywords), + ) + + built_at = datetime.now(timezone.utc) + repository.replace_links( + db, + normalized_id, + matched_patents, + author_name=author.display_name, + search_meta=search_meta, + built_at=built_at, + ) + db.commit() + + return _build_response( + db, + normalized_id, + author.display_name, + from_cache=False, + built_at=built_at, + search_meta=search_meta, + ) + + +def load_author_patents( + db: Session, + author_id: str, +) -> model.PatentsByAuthorResponse: + normalized_id = normalize_author_id(author_id) + build_meta = repository.get_build_meta(db, normalized_id) + search_meta = None + built_at = None + author_name = None + + if build_meta is not None: + author_name = build_meta.author_name + built_at = build_meta.built_at + search_meta = model.PatentSearchMeta.model_validate_json(build_meta.search_meta) + + return _build_response( + db, + normalized_id, + author_name, + from_cache=True, + built_at=built_at, + search_meta=search_meta, + ) + + +def _build_response( + db: Session, + author_id: str, + author_name: str | None, + *, + from_cache: bool, + built_at: datetime | None, + search_meta: model.PatentSearchMeta | None, +) -> model.PatentsByAuthorResponse: + links = repository.get_links(db, author_id) + patents = repository.apply_overrides( + repository.links_to_patents(links), + repository.get_overrides(db, author_id), + ) + return model.PatentsByAuthorResponse( + author_id=author_id, + author_name=author_name, + patent_count=len(patents), + patents=patents, + from_cache=from_cache, + last_built_at=built_at, + search_meta=search_meta, + ) + + +def _response_from_cache_or_empty( + db: Session, + author_id: str, + author_name: str | None, + *, + from_cache: bool, + rebuild_failed: bool, +) -> model.PatentsByAuthorResponse: + links = repository.get_links(db, author_id) + if links: + return load_author_patents(db, author_id) + + search_meta = model.PatentSearchMeta(rebuild_failed=rebuild_failed) if rebuild_failed else None + return model.PatentsByAuthorResponse( + author_id=author_id, + author_name=author_name, + patent_count=0, + patents=[], + from_cache=from_cache, + search_meta=search_meta, + ) + + +def _empty_response(author_id: str) -> model.PatentsByAuthorResponse: + return model.PatentsByAuthorResponse( + author_id=author_id, + author_name=None, + patent_count=0, + patents=[], + from_cache=False, + ) + + +def _get_author(author_id: str) -> Author | None: + short_id = author_id.replace("https://openalex.org/", "") + result = person_logic.search_persons(author_id=short_id) + return result.results[0] if result.results else None diff --git a/service/src/main/inse/patents/repository.py b/service/src/main/inse/patents/repository.py new file mode 100644 index 00000000..5a049f54 --- /dev/null +++ b/service/src/main/inse/patents/repository.py @@ -0,0 +1,182 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" + Persistence layer for author-patent links and manual overrides. +""" +from __future__ import annotations + +import json +from datetime import datetime, timedelta, timezone + +from sqlalchemy import delete, select +from sqlalchemy.orm import Session + +from .. import config +from .. import schema +from . import model +from .author_profile import normalize_author_id + + +def is_cache_fresh(built_at: datetime | None) -> bool: + if built_at is None: + return False + ttl = timedelta(hours=config.settings.patent_link_cache_ttl_hours) + now = datetime.now(timezone.utc) + if built_at.tzinfo is None: + built_at = built_at.replace(tzinfo=timezone.utc) + return now - built_at < ttl + + +def get_build_meta(db: Session, author_id: str) -> schema.AuthorPatentBuildMeta | None: + normalized_id = normalize_author_id(author_id) + return db.get(schema.AuthorPatentBuildMeta, normalized_id) + + +def get_links(db: Session, author_id: str) -> list[schema.AuthorPatentLink]: + normalized_id = normalize_author_id(author_id) + return list( + db.scalars( + select(schema.AuthorPatentLink) + .where(schema.AuthorPatentLink.author_id == normalized_id) + .order_by(schema.AuthorPatentLink.confidence_score.desc()) + ).all() + ) + + +def get_overrides(db: Session, author_id: str) -> list[schema.AuthorPatentOverride]: + normalized_id = normalize_author_id(author_id) + return list( + db.scalars( + select(schema.AuthorPatentOverride) + .where(schema.AuthorPatentOverride.author_id == normalized_id) + ).all() + ) + + +def replace_links( + db: Session, + author_id: str, + patents: list[model.PatentEntry], + *, + author_name: str | None, + search_meta: model.PatentSearchMeta, + built_at: datetime | None = None, +) -> None: + normalized_id = normalize_author_id(author_id) + timestamp = built_at or datetime.now(timezone.utc) + + db.execute( + delete(schema.AuthorPatentLink).where( + schema.AuthorPatentLink.author_id == normalized_id + ) + ) + + for patent in patents: + db.add( + schema.AuthorPatentLink( + author_id=normalized_id, + patent_id=patent.patent_id, + source=patent.source, + confidence_score=patent.confidence_score, + match_signals=json.dumps(patent.match_signals), + patent_data=patent.model_dump_json(), + built_at=timestamp, + ) + ) + + existing_meta = db.get(schema.AuthorPatentBuildMeta, normalized_id) + if existing_meta is None: + existing_meta = schema.AuthorPatentBuildMeta(author_id=normalized_id) + db.add(existing_meta) + + existing_meta.author_name = author_name + existing_meta.built_at = timestamp + existing_meta.search_meta = search_meta.model_dump_json() + + +def upsert_override( + db: Session, + author_id: str, + patent_id: str, + action: str, + *, + reason: str | None = None, + patent: model.PatentEntry | None = None, +) -> schema.AuthorPatentOverride: + normalized_id = normalize_author_id(author_id) + existing = db.scalar( + select(schema.AuthorPatentOverride).where( + schema.AuthorPatentOverride.author_id == normalized_id, + schema.AuthorPatentOverride.patent_id == patent_id, + ) + ) + + patent_data = patent.model_dump_json() if patent is not None else None + if existing is None: + existing = schema.AuthorPatentOverride( + author_id=normalized_id, + patent_id=patent_id, + action=action, + reason=reason, + patent_data=patent_data, + created_at=datetime.now(timezone.utc), + ) + db.add(existing) + return existing + + existing.action = action + existing.reason = reason + if patent_data is not None: + existing.patent_data = patent_data + return existing + + +def delete_override(db: Session, author_id: str, patent_id: str) -> bool: + normalized_id = normalize_author_id(author_id) + override = db.scalar( + select(schema.AuthorPatentOverride).where( + schema.AuthorPatentOverride.author_id == normalized_id, + schema.AuthorPatentOverride.patent_id == patent_id, + ) + ) + if override is None: + return False + db.delete(override) + return True + + +def links_to_patents(links: list[schema.AuthorPatentLink]) -> list[model.PatentEntry]: + patents: list[model.PatentEntry] = [] + for link in links: + patent = model.PatentEntry.model_validate_json(link.patent_data) + patent.confidence_score = link.confidence_score + patent.match_signals = json.loads(link.match_signals or "[]") + patents.append(patent) + return patents + + +def apply_overrides( + patents: list[model.PatentEntry], + overrides: list[schema.AuthorPatentOverride], +) -> list[model.PatentEntry]: + excluded_ids = { + override.patent_id + for override in overrides + if override.action == "exclude" + } + result = [patent for patent in patents if patent.patent_id not in excluded_ids] + existing_ids = {patent.patent_id for patent in result} + + for override in overrides: + if override.action != "include" or override.patent_id in existing_ids: + continue + if not override.patent_data: + continue + patent = model.PatentEntry.model_validate_json(override.patent_data) + if "manual_include" not in patent.match_signals: + patent.match_signals.append("manual_include") + result.append(patent) + existing_ids.add(patent.patent_id) + + result.sort(key=lambda patent: patent.confidence_score, reverse=True) + return result diff --git a/service/src/main/inse/patents/service.py b/service/src/main/inse/patents/service.py index 7bdcbb82..2c41647e 100644 --- a/service/src/main/inse/patents/service.py +++ b/service/src/main/inse/patents/service.py @@ -3,8 +3,11 @@ """ REST API for patent matching by author. """ -from fastapi import APIRouter +from fastapi import APIRouter, Depends, HTTPException, Query +from sqlalchemy.orm import Session +from starlette.status import HTTP_404_NOT_FOUND +from .. import database from . import logic from . import model @@ -15,7 +18,54 @@ router = APIRouter(prefix="/api/inse-service/authors", tags=["Patents"]) "/{author_id}/patents", operation_id="getPatentsByAuthor", response_model=model.PatentsByAuthorResponse, - summary="Get patents matched to an author by name.", + summary="Get patents matched to an author.", ) -async def get_patents_by_author(author_id: str): - return await logic.get_patents_by_author_id(author_id) \ No newline at end of file +async def get_patents_by_author( + author_id: str, + refresh: bool = Query(False, description="Force a rebuild of the patent links."), + db: Session = Depends(database.get), +): + return await logic.get_patents_by_author_id(author_id, db, refresh=refresh) + + +@router.post( + "/{author_id}/patents/rebuild", + operation_id="rebuildPatentsByAuthor", + response_model=model.PatentsByAuthorResponse, + summary="Rebuild patent links for an author via the disambiguation pipeline.", +) +async def rebuild_patents_by_author( + author_id: str, + db: Session = Depends(database.get), +): + return await logic.rebuild_patents_for_author(author_id, db) + + +@router.put( + "/{author_id}/patents/{patent_id}/override", + operation_id="setPatentOverride", + response_model=model.PatentOverrideResponse, + summary="Manually include or exclude a patent for an author.", +) +async def set_patent_override( + author_id: str, + patent_id: str, + body: model.PatentOverrideRequest, + db: Session = Depends(database.get), +): + return await logic.set_patent_override(author_id, patent_id, body, db) + + +@router.delete( + "/{author_id}/patents/{patent_id}/override", + operation_id="clearPatentOverride", + status_code=204, + summary="Remove a manual patent override for an author.", +) +async def clear_patent_override( + author_id: str, + patent_id: str, + db: Session = Depends(database.get), +): + if not logic.clear_patent_override(author_id, patent_id, db): + raise HTTPException(status_code=HTTP_404_NOT_FOUND, detail="Override not found.") diff --git a/service/src/main/inse/patents/test_logic.py b/service/src/main/inse/patents/test_logic.py new file mode 100644 index 00000000..49a15ac1 --- /dev/null +++ b/service/src/main/inse/patents/test_logic.py @@ -0,0 +1,228 @@ +import json + +import httpx +import pytest +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker + +from inse import schema +from inse.patents import model +from inse.patents.author_profile import AuthorProfile, build_author_profile, extract_name_parts +from inse.patents.disambiguation import disambiguate_patent_group, score_patent +from inse.patents.elastic_search_client import PatentSearchClient, parse_epo_hits, parse_uspto_hits +from inse.patents import repository +from inse.models.author import Author +from inse.models.author_ids import AuthorIds +from inse.models.dehydrated_institution import DehydratedInstitution + + +@pytest.fixture +def anyio_backend(): + return "asyncio" + + +@pytest.fixture +def db_session(): + engine = create_engine("sqlite:///:memory:") + schema.Base.metadata.create_all(engine) + session = sessionmaker(bind=engine)() + try: + yield session + finally: + session.close() + + +def _sample_author() -> Author: + return Author( + id="https://openalex.org/A123", + display_name="Max Mustermann", + orcid="https://orcid.org/0000-0001-2345-6789", + ids=AuthorIds(openalex="https://openalex.org/A123", orcid="https://orcid.org/0000-0001-2345-6789"), + last_known_institutions=[ + DehydratedInstitution(display_name="University of Example"), + ], + topics=[], + affiliations=[], + ) + + +def test_extract_name_parts_strips_titles(): + first, last = extract_name_parts("Prof. Dr. Max Mustermann") + assert first == "Max" + assert last == "Mustermann" + + +def test_score_patent_accepts_full_name_and_institution(): + author = _sample_author() + profile = build_author_profile(author, "A123") + profile.coauthor_last_names.add("schmidt") + + patent = model.PatentEntry( + patent_id="EP100", + source="EPO", + title="Machine learning system", + inventors=["Max Mustermann", "Anna Schmidt"], + assignees=["University of Example Research"], + ) + + result = score_patent(patent, profile) + assert result.accepted is True + assert result.score >= 6 + assert "full_name_match" in result.signals + assert "institution_match" in result.signals + assert "coauthor_match" in result.signals + + +def test_disambiguate_patent_group_keeps_best_version(): + author = _sample_author() + profile = build_author_profile(author, "A123") + + weak = model.PatentEntry( + patent_id="EP100", + source="EPO", + inventors=["Mustermann"], + assignees=[], + ) + strong = model.PatentEntry( + patent_id="EP100", + source="EPO", + inventors=["Max Mustermann"], + assignees=["University of Example"], + ) + + best = disambiguate_patent_group([weak, strong], profile) + assert best is not None + assert best.inventors == ["Max Mustermann"] + assert best.confidence_score >= 6 + + +def test_repository_apply_overrides_include_and_exclude(db_session): + patent = model.PatentEntry( + patent_id="EP1", + source="EPO", + inventors=["Max Mustermann"], + confidence_score=8, + match_signals=["full_name_match"], + ) + repository.replace_links( + db_session, + "A123", + [patent], + author_name="Max Mustermann", + search_meta=model.PatentSearchMeta(matched_count=1), + ) + repository.upsert_override(db_session, "A123", "EP1", "exclude") + repository.upsert_override( + db_session, + "A123", + "EP2", + "include", + patent=model.PatentEntry( + patent_id="EP2", + source="EPO", + inventors=["Max Mustermann"], + confidence_score=10, + match_signals=["manual_include"], + ), + ) + db_session.commit() + + patents = repository.apply_overrides( + repository.links_to_patents(repository.get_links(db_session, "A123")), + repository.get_overrides(db_session, "A123"), + ) + patent_ids = {entry.patent_id for entry in patents} + assert "EP1" not in patent_ids + assert "EP2" in patent_ids + + +@pytest.mark.anyio +async def test_rebuild_author_patents_persists_links(db_session, monkeypatch): + from inse.patents.pipeline import rebuild_author_patents + + author = _sample_author() + + monkeypatch.setattr( + "inse.patents.pipeline._get_author", + lambda author_id: author, + ) + async def fake_enrich(profile, works_client=None): + return profile + + monkeypatch.setattr( + "inse.patents.pipeline.enrich_with_publication_context", + fake_enrich, + ) + + class FakeClient: + async def fetch_all_epo(self, profile): + return 1, [{ + "_source": { + "doc_number": "100", + "title_en": "Example patent", + "inventors_name": ["Max Mustermann"], + "applicants_name": ["University of Example"], + }, + }] + + async def fetch_all_uspto(self, profile): + return 0, [] + + response = await rebuild_author_patents("A123", db_session, client=FakeClient()) + assert response.patent_count == 1 + assert response.patents[0].patent_id == "EP100" + assert response.from_cache is False + assert response.search_meta is not None + assert response.search_meta.matched_count == 1 + + cached = repository.get_links(db_session, "A123") + assert len(cached) == 1 + + +def test_patent_search_client_builds_full_name_query(): + profile = AuthorProfile( + author_id="https://openalex.org/A123", + display_name="Max Mustermann", + first_name="Max", + last_name="Mustermann", + name_variants=["Max Mustermann", "Mustermann, Max"], + ) + client = PatentSearchClient(api_key="test-key") + query = client.epo_query_by_profile(profile, page=1, size=100) + assert query["from"] == 0 + assert query["size"] == 100 + should = query["query"]["bool"]["should"] + assert any( + clause.get("match", {}).get("inventors_name_text", {}).get("query") == "Max Mustermann" + for clause in should + ) + + +def test_parse_epo_and_uspto_hits(): + epo = parse_epo_hits({ + "hits": { + "hits": [{ + "_source": { + "doc_number": "123", + "title_en": "EPO title", + "inventors_name": ["Max Mustermann", None], + "date_publication_year": 2015, + }, + }], + }, + }) + uspto = parse_uspto_hits({ + "hits": { + "hits": [{ + "_source": { + "publication_number": "456", + "title": "US title", + "inventors_names": ["Max Mustermann"], + }, + }], + }, + }) + assert epo[0].patent_id == "EP123" + assert epo[0].inventors == ["Max Mustermann"] + assert epo[0].publication_year == "2015" + assert uspto[0].patent_id == "US456" diff --git a/service/src/main/inse/schema.py b/service/src/main/inse/schema.py index d03a1b33..b1b59c1b 100644 --- a/service/src/main/inse/schema.py +++ b/service/src/main/inse/schema.py @@ -4,7 +4,9 @@ This module defines the schema for the database used by the service using sql alchemy. """ -from sqlalchemy import String +from datetime import datetime + +from sqlalchemy import DateTime, String, Text, UniqueConstraint from sqlalchemy.orm import DeclarativeBase from sqlalchemy.orm import Mapped from sqlalchemy.orm import mapped_column @@ -22,3 +24,46 @@ class Item(Base): description: Mapped[str] = mapped_column(String(2000)) def __repr__(self) -> str: return f"Item(id={self.id!r}, name={self.name!r})" + + +class AuthorPatentLink(Base): + """Persisted author-to-patent match produced by the disambiguation pipeline.""" + __tablename__ = "author_patent_link" + __table_args__ = ( + UniqueConstraint("author_id", "patent_id", name="uq_author_patent_link"), + ) + + id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) + author_id: Mapped[str] = mapped_column(String(128), index=True) + patent_id: Mapped[str] = mapped_column(String(64), index=True) + source: Mapped[str] = mapped_column(String(16)) + confidence_score: Mapped[int] = mapped_column() + match_signals: Mapped[str] = mapped_column(Text) + patent_data: Mapped[str] = mapped_column(Text) + built_at: Mapped[datetime] = mapped_column(DateTime) + + +class AuthorPatentOverride(Base): + """Manual include/exclude overrides for author-patent links.""" + __tablename__ = "author_patent_override" + __table_args__ = ( + UniqueConstraint("author_id", "patent_id", name="uq_author_patent_override"), + ) + + id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) + author_id: Mapped[str] = mapped_column(String(128), index=True) + patent_id: Mapped[str] = mapped_column(String(64), index=True) + action: Mapped[str] = mapped_column(String(16)) + reason: Mapped[str | None] = mapped_column(String(500), nullable=True) + patent_data: Mapped[str | None] = mapped_column(Text, nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime) + + +class AuthorPatentBuildMeta(Base): + """Metadata for the last disambiguation run per author.""" + __tablename__ = "author_patent_build_meta" + + author_id: Mapped[str] = mapped_column(String(128), primary_key=True) + author_name: Mapped[str | None] = mapped_column(String(300), nullable=True) + built_at: Mapped[datetime] = mapped_column(DateTime) + search_meta: Mapped[str] = mapped_column(Text) diff --git a/webapp/src/app/api/api/patents.service.ts b/webapp/src/app/api/api/patents.service.ts index 880467cb..ef47c2cd 100644 --- a/webapp/src/app/api/api/patents.service.ts +++ b/webapp/src/app/api/api/patents.service.ts @@ -32,7 +32,22 @@ export interface PatentEntry { assignees: string[]; ipc: string[]; country: string | null; + orcid?: string | null; confidence_score: number; + match_signals?: string[]; +} + +export interface PatentSearchMeta { + epo_total_hits: number; + uspto_total_hits: number; + epo_returned_hits: number; + uspto_returned_hits: number; + matched_count: number; + epo_truncated: boolean; + uspto_truncated: boolean; + coauthor_signals: number; + publication_keywords: number; + rebuild_failed?: boolean; } export interface PatentsByAuthorResponse { @@ -40,6 +55,9 @@ export interface PatentsByAuthorResponse { author_name: string | null; patent_count: number; patents: PatentEntry[]; + from_cache?: boolean; + last_built_at?: string | null; + search_meta?: PatentSearchMeta | null; } @Injectable({ @@ -99,6 +117,7 @@ export class PatentsService extends BaseService { httpHeaderAccept?: 'application/json'; context?: HttpContext; transferCache?: boolean; + refresh?: boolean; }, ): Observable { if (authorId === null || authorId === undefined) { @@ -147,12 +166,18 @@ export class PatentsService extends BaseService { dataFormat: undefined, })}/patents`; + let localVarQueryParameters = new HttpParams({ encoder: new CustomHttpParameterCodec() }); + if (options?.refresh) { + localVarQueryParameters = localVarQueryParameters.set('refresh', 'true'); + } + const { basePath, withCredentials } = this.configuration; return this.httpClient.request( 'get', `${basePath}${localVarPath}`, { context: localVarHttpContext, + params: localVarQueryParameters, responseType: responseType_, ...(withCredentials ? { withCredentials } : {}), headers: localVarHeaders, @@ -164,4 +189,26 @@ export class PatentsService extends BaseService { }, ); } + + public rebuildPatentsByAuthor(authorId: string): Observable { + const localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam({ + name: 'authorId', + value: authorId, + in: 'path', + style: 'simple', + explode: false, + dataType: 'string', + dataFormat: undefined, + })}/patents/rebuild`; + + const { basePath, withCredentials } = this.configuration; + return this.httpClient.post( + `${basePath}${localVarPath}`, + null, + { + ...(withCredentials ? { withCredentials } : {}), + headers: this.defaultHeaders, + }, + ); + } } 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 8d083698..2ca11d99 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.html +++ b/webapp/src/app/modules/person-patents/person-patents.component.html @@ -20,6 +20,21 @@ {{ getUsptoCount() }} USPTO

+ @if (fromCache) { +

+ Aus Cache + @if (lastBuiltAt) { + · {{ formatDate(lastBuiltAt) }} + } +

+ } +
@@ -101,6 +116,17 @@
+ @if (selectedPatent.match_signals?.length) { +
+

Zuordnungs-Signale

+
    + @for (signal of selectedPatent.match_signals; track signal) { +
  • {{ formatSignal(signal) }}
  • + } +
+
+ } + @if (selectedPatent.abstract) {

Abstract

diff --git a/webapp/src/app/modules/person-patents/person-patents.component.scss b/webapp/src/app/modules/person-patents/person-patents.component.scss index 762cf458..f2c2c91b 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.scss +++ b/webapp/src/app/modules/person-patents/person-patents.component.scss @@ -14,6 +14,8 @@ margin-bottom: 8px; display: flex; gap: 24px; + align-items: center; + flex-wrap: wrap; .summary-line { margin: 0; @@ -21,6 +23,27 @@ color: #333; } + .summary-line--meta { + color: #666; + font-size: 13px; + } + + .rebuild-button { + margin-left: auto; + padding: 8px 14px; + border: 1px solid #bdd4ff; + border-radius: 20px; + background: #f0f6ff; + color: #0b63ce; + cursor: pointer; + font-size: 14px; + + &:disabled { + opacity: 0.6; + cursor: default; + } + } + .summary-label { color: #333; } @@ -263,6 +286,12 @@ color: #1e40af; font-size: 0.8rem; line-height: 1.3; + + &--signal { + background: #eef7ee; + border-color: #cfe6cf; + color: #2f6b2f; + } } .pagination { 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 4d73e943..cfe874b6 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.ts +++ b/webapp/src/app/modules/person-patents/person-patents.component.ts @@ -1,11 +1,27 @@ import { Component, OnInit, inject } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ActivatedRoute, Router } from '@angular/router'; -import { PatentsService, PatentEntry } from '../../api/api/patents.service'; +import { + PatentsService, + PatentEntry, + PatentSearchMeta, +} from '../../api/api/patents.service'; type SortMode = 'score' | 'date' | 'title'; type SourceFilter = 'all' | 'EPO' | 'USPTO'; +const SIGNAL_LABELS: Record = { + full_name_match: 'Vollständiger Name', + last_name_match: 'Nachname', + first_name_match: 'Vorname', + institution_match: 'Institution', + orcid_match: 'ORCID', + topic_match: 'Forschungsthema', + coauthor_match: 'Ko-Autor', + publication_topic_match: 'Publikations-Thema', + manual_include: 'Manuell hinzugefügt', +}; + @Component({ selector: 'app-person-patents', imports: [CommonModule], @@ -21,9 +37,14 @@ export class PersonPatentsComponent implements OnInit { filteredPatents: PatentEntry[] = []; authorName: string | null = null; selectedPatent: PatentEntry | null = null; + searchMeta: PatentSearchMeta | null = null; + fromCache = false; + lastBuiltAt: string | null = null; loading = true; + rebuilding = false; error = false; + authorId = ''; activeFilter: SourceFilter = 'all'; sortMode: SortMode = 'score'; @@ -33,7 +54,7 @@ export class PersonPatentsComponent implements OnInit { ngOnInit(): void { this.route.parent?.paramMap.subscribe((params) => { - const authorId = params.get('id') ?? ''; + this.authorId = params.get('id') ?? ''; const filterFromUrl = this.route.snapshot.queryParamMap.get('filter'); const sortFromUrl = this.route.snapshot.queryParamMap.get('sortBy'); @@ -45,23 +66,51 @@ export class PersonPatentsComponent implements OnInit { this.sortMode = sortFromUrl; } - if (authorId) { - this.patentsApi.getPatentsByAuthor(authorId, 'body').subscribe({ - next: (result) => { - this.patents = result.patents ?? []; - this.authorName = result.author_name ?? null; - this.applyFilter(); - this.loading = false; - }, - error: () => { - this.error = true; - this.loading = false; - }, - }); + if (this.authorId) { + this.loadPatents(); } }); } + loadPatents(refresh = false): void { + this.loading = true; + this.error = false; + + this.patentsApi + .getPatentsByAuthor(this.authorId, 'body', false, { + refresh, + transferCache: false, + }) + .subscribe({ + next: (result) => this.applyResult(result), + error: () => { + this.error = true; + this.loading = false; + }, + }); + } + + rebuildPatents(): void { + if (!this.authorId || this.rebuilding) { + return; + } + + this.rebuilding = true; + this.error = false; + + this.patentsApi.rebuildPatentsByAuthor(this.authorId).subscribe({ + next: (result) => { + this.applyResult(result); + this.rebuilding = false; + }, + error: () => { + this.error = true; + this.rebuilding = false; + this.loading = false; + }, + }); + } + setFilter(filter: SourceFilter): void { this.activeFilter = filter; this.selectedPage = 1; @@ -81,6 +130,26 @@ export class PersonPatentsComponent implements OnInit { this.updateQueryParams(); } + formatSignal(signal: string): string { + return SIGNAL_LABELS[signal] ?? signal; + } + + private applyResult(result: { + patents?: PatentEntry[]; + author_name?: string | null; + from_cache?: boolean; + last_built_at?: string | null; + search_meta?: PatentSearchMeta | null; + }): void { + this.patents = result.patents ?? []; + this.authorName = result.author_name ?? null; + this.fromCache = result.from_cache ?? false; + this.lastBuiltAt = result.last_built_at ?? null; + this.searchMeta = result.search_meta ?? null; + this.applyFilter(); + this.loading = false; + } + private applyFilter(): void { let patents = this.patents; -- 2.56.1 From c298a388d0ab64c44f00a13734b047ae3e8cf20e Mon Sep 17 00:00:00 2001 From: taguesokoudjou Date: Mon, 15 Jun 2026 20:41:32 +0200 Subject: [PATCH 3/8] fix: resolve patents build error --- webapp/src/app/api/api/patents.service.ts | 32 +++++++------------ .../person-patents.component.html | 8 ----- .../person-patents.component.scss | 5 --- .../person-patents.component.ts | 6 ---- 4 files changed, 11 insertions(+), 40 deletions(-) diff --git a/webapp/src/app/api/api/patents.service.ts b/webapp/src/app/api/api/patents.service.ts index ef47c2cd..fcf20411 100644 --- a/webapp/src/app/api/api/patents.service.ts +++ b/webapp/src/app/api/api/patents.service.ts @@ -60,6 +60,13 @@ export interface PatentsByAuthorResponse { search_meta?: PatentSearchMeta | null; } +type GetPatentsByAuthorOptions = { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + refresh?: boolean; +}; + @Injectable({ providedIn: 'root', }) @@ -83,42 +90,25 @@ export class PatentsService extends BaseService { authorId: string, observe?: 'body', reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, + options?: GetPatentsByAuthorOptions, ): Observable; public getPatentsByAuthor( authorId: string, observe?: 'response', reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, + options?: GetPatentsByAuthorOptions, ): Observable>; public getPatentsByAuthor( authorId: string, observe?: 'events', reportProgress?: boolean, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - }, + options?: GetPatentsByAuthorOptions, ): Observable>; public getPatentsByAuthor( authorId: string, observe: any = 'body', reportProgress: boolean = false, - options?: { - httpHeaderAccept?: 'application/json'; - context?: HttpContext; - transferCache?: boolean; - refresh?: boolean; - }, + options?: GetPatentsByAuthorOptions, ): Observable { if (authorId === null || authorId === undefined) { throw new Error( 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 2ca11d99..841c1ba1 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.html +++ b/webapp/src/app/modules/person-patents/person-patents.component.html @@ -20,14 +20,6 @@ {{ getUsptoCount() }} USPTO

- @if (fromCache) { -

- Aus Cache - @if (lastBuiltAt) { - · {{ formatDate(lastBuiltAt) }} - } -

- }
-
+
+ +
-
- Relevanz - {{ selectedPatent.confidence_score }} -
- @if (selectedPatent.match_signals?.length) { -
-

Zuordnungs-Signale

-
    - @for (signal of selectedPatent.match_signals; track signal) { -
  • {{ formatSignal(signal) }}
  • - } -
-
- } - @if (selectedPatent.abstract) {

Abstract

diff --git a/webapp/src/app/modules/person-patents/person-patents.component.scss b/webapp/src/app/modules/person-patents/person-patents.component.scss index 079fffd7..9f511648 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.scss +++ b/webapp/src/app/modules/person-patents/person-patents.component.scss @@ -14,8 +14,6 @@ margin-bottom: 8px; display: flex; gap: 24px; - align-items: center; - flex-wrap: wrap; .summary-line { margin: 0; @@ -23,22 +21,6 @@ color: #333; } - .rebuild-button { - margin-left: auto; - padding: 8px 14px; - border: 1px solid #bdd4ff; - border-radius: 20px; - background: #f0f6ff; - color: #0b63ce; - cursor: pointer; - font-size: 14px; - - &:disabled { - opacity: 0.6; - cursor: default; - } - } - .summary-label { color: #333; } @@ -50,33 +32,35 @@ } .filter-bar { - display: flex; + display: inline-flex; align-items: center; - gap: 8px; - flex-wrap: wrap; + gap: 6px; + width: fit-content; + padding: 10px 14px; + border-radius: 20px; + background: #f2f2f2; + color: #333; + font-size: 14px; span { - font-weight: 500; color: #555; } button { - padding: 6px 14px; - border: 1px solid #ccc; - border-radius: 20px; - background: white; + border: 0; + background: transparent; + color: #111827; + font: inherit; cursor: pointer; - font-size: 14px; - - &:hover { - background: #f0f0f0; - } + outline: none; &.active { - background: #f0f6ff; - color: #0b63ce; - border-color: #bdd4ff; font-weight: 600; + color: #0b63ce; + } + + &:hover { + text-decoration: underline; } } } @@ -281,12 +265,6 @@ color: #1e40af; font-size: 0.8rem; line-height: 1.3; - - &--signal { - background: #eef7ee; - border-color: #cfe6cf; - color: #2f6b2f; - } } .pagination { 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 f96dcb14..507f1e88 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.ts +++ b/webapp/src/app/modules/person-patents/person-patents.component.ts @@ -1,26 +1,11 @@ import { Component, OnInit, inject } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ActivatedRoute, Router } from '@angular/router'; -import { - PatentsService, - PatentEntry, - PatentSearchMeta, -} from '../../api/api/patents.service'; +import { PatentsService, PatentEntry } from '../../api/api/patents.service'; -type SortMode = 'score' | 'date' | 'title'; +type SortMode = 'date' | 'title'; type SourceFilter = 'all' | 'EPO' | 'USPTO'; -const SIGNAL_LABELS: Record = { - full_name_match: 'Vollständiger Name', - last_name_match: 'Nachname', - first_name_match: 'Vorname', - institution_match: 'Institution', - topic_match: 'Forschungsthema', - coauthor_match: 'Ko-Autor', - publication_topic_match: 'Publikations-Thema', - manual_include: 'Manuell hinzugefügt', -}; - @Component({ selector: 'app-person-patents', imports: [CommonModule], @@ -36,22 +21,19 @@ export class PersonPatentsComponent implements OnInit { filteredPatents: PatentEntry[] = []; authorName: string | null = null; selectedPatent: PatentEntry | null = null; - searchMeta: PatentSearchMeta | null = null; loading = true; - rebuilding = false; error = false; - authorId = ''; activeFilter: SourceFilter = 'all'; - sortMode: SortMode = 'score'; + sortMode: SortMode = 'date'; selectedPage = 1; readonly pageSize = 10; ngOnInit(): void { this.route.parent?.paramMap.subscribe((params) => { - this.authorId = params.get('id') ?? ''; + const authorId = params.get('id') ?? ''; const filterFromUrl = this.route.snapshot.queryParamMap.get('filter'); const sortFromUrl = this.route.snapshot.queryParamMap.get('sortBy'); @@ -63,51 +45,23 @@ export class PersonPatentsComponent implements OnInit { this.sortMode = sortFromUrl; } - if (this.authorId) { - this.loadPatents(); + if (authorId) { + this.patentsApi.getPatentsByAuthor(authorId, 'body').subscribe({ + next: (result) => { + this.patents = result.patents ?? []; + this.authorName = result.author_name ?? null; + this.applyFilter(); + this.loading = false; + }, + error: () => { + this.error = true; + this.loading = false; + }, + }); } }); } - loadPatents(refresh = false): void { - this.loading = true; - this.error = false; - - this.patentsApi - .getPatentsByAuthor(this.authorId, 'body', false, { - refresh, - transferCache: false, - }) - .subscribe({ - next: (result) => this.applyResult(result), - error: () => { - this.error = true; - this.loading = false; - }, - }); - } - - rebuildPatents(): void { - if (!this.authorId || this.rebuilding) { - return; - } - - this.rebuilding = true; - this.error = false; - - this.patentsApi.rebuildPatentsByAuthor(this.authorId).subscribe({ - next: (result) => { - this.applyResult(result); - this.rebuilding = false; - }, - error: () => { - this.error = true; - this.rebuilding = false; - this.loading = false; - }, - }); - } - setFilter(filter: SourceFilter): void { this.activeFilter = filter; this.selectedPage = 1; @@ -127,22 +81,6 @@ export class PersonPatentsComponent implements OnInit { this.updateQueryParams(); } - formatSignal(signal: string): string { - return SIGNAL_LABELS[signal] ?? signal; - } - - private applyResult(result: { - patents?: PatentEntry[]; - author_name?: string | null; - search_meta?: PatentSearchMeta | null; - }): void { - this.patents = result.patents ?? []; - this.authorName = result.author_name ?? null; - this.searchMeta = result.search_meta ?? null; - this.applyFilter(); - this.loading = false; - } - private applyFilter(): void { let patents = this.patents; @@ -155,13 +93,14 @@ export class PersonPatentsComponent implements OnInit { private sortPatents(patents: PatentEntry[]): PatentEntry[] { return [...patents].sort((a, b) => { - if (this.sortMode === 'score') { - return b.confidence_score - a.confidence_score; - } if (this.sortMode === 'date') { - return (b.publication_date ?? '').localeCompare(a.publication_date ?? ''); + return (b.publication_date ?? '').localeCompare( + a.publication_date ?? '', + ); } - return (a.title ?? '').localeCompare(b.title ?? '', 'de', { sensitivity: 'base' }); + return (a.title ?? '').localeCompare(b.title ?? '', 'de', { + sensitivity: 'base', + }); }); } @@ -182,7 +121,7 @@ export class PersonPatentsComponent implements OnInit { } private isValidSortMode(value: string | null): value is SortMode { - return value === 'score' || value === 'date' || value === 'title'; + return value === 'date' || value === 'title'; } getPagedPatents(): PatentEntry[] { -- 2.56.1 From c211e8d210d7ee209a5071461b52e151250e86ec Mon Sep 17 00:00:00 2001 From: taguesokoudjou Date: Fri, 19 Jun 2026 17:02:31 +0200 Subject: [PATCH 6/8] fix: repair patent ES search and add name matching for inventor lookup --- .../inse/patents/elastic_search_client.py | 126 ++++----- service/src/main/inse/patents/logic.py | 33 ++- .../src/main/inse/patents/name_matching.py | 242 ++++++++++++++++++ .../patents/test_elastic_search_client.py | 49 ++++ .../main/inse/patents/test_name_matching.py | 123 +++++++++ 5 files changed, 503 insertions(+), 70 deletions(-) create mode 100644 service/src/main/inse/patents/name_matching.py create mode 100644 service/src/main/inse/patents/test_elastic_search_client.py create mode 100644 service/src/main/inse/patents/test_name_matching.py diff --git a/service/src/main/inse/patents/elastic_search_client.py b/service/src/main/inse/patents/elastic_search_client.py index ead988af..64d5865e 100644 --- a/service/src/main/inse/patents/elastic_search_client.py +++ b/service/src/main/inse/patents/elastic_search_client.py @@ -8,9 +8,25 @@ from typing import Any import httpx from .. import config +from .name_matching import search_name_variants EPO_INDEX = "epo_index_1.0" -USPTO_INDEX = "uspto_patents_2.0" +USPTO_INDEX = "uspto_patents_3.0" + +DEFAULT_SEARCH_SIZE = 100 + + +def _match_name_field(field: str, name: str) -> dict[str, Any]: + """Match a name field, including transliterated variants (Müller/Mueller).""" + variants = search_name_variants(name) + if len(variants) <= 1: + return {"match": {field: variants[0] if variants else name}} + return { + "bool": { + "should": [{"match": {field: variant}} for variant in variants], + "minimum_should_match": 1, + } + } class MissingApiKeyError(Exception): @@ -38,46 +54,43 @@ class PatentSearchClient: "Content-Type": "application/json", } - def epo_query_by_inventor(self, last_name: str, first_name: str | None = None, size: int = 100) -> dict[str, Any]: - """Search EPO index by inventor first AND last name. - EPO stores full name e.g. 'HANDTE, Marcus' in inventors_name_text. - """ + def epo_query_by_inventor( + self, + last_name: str, + first_name: str | None = None, + size: int = DEFAULT_SEARCH_SIZE, + ) -> dict[str, Any]: + """Search EPO index: first AND last name in the SAME inventor entry.""" if first_name: query = { - "bool": { - "must": [ - { - "match": { - "inventors_name_text": { - "query": last_name, - "operator": "and", - } - } - }, - { - "match": { - "inventors_name_text": { - "query": first_name, - "operator": "and", - } - } - }, - ] + "nested": { + "path": "inventors_name_nested", + "query": { + "bool": { + "must": [ + _match_name_field("inventors_name_nested.inventor", last_name), + _match_name_field("inventors_name_nested.inventor", first_name), + ] + } + }, } } else: query = { - "match": { - "inventors_name_text": { - "query": last_name, - "operator": "and", - } + "nested": { + "path": "inventors_name_nested", + "query": _match_name_field("inventors_name_nested.inventor", last_name), } } return { "size": size, "track_total_hits": True, + "sort": [ + {"_score": {"order": "desc"}}, + {"date_publication": {"order": "desc", "missing": "_last"}}, + "_doc", + ], "_source": [ "doc_number", "country", @@ -95,46 +108,43 @@ class PatentSearchClient: "query": query, } - def uspto_query_by_inventor(self, last_name: str, first_name: str | None = None, size: int = 100) -> dict[str, Any]: - """Search USPTO index by inventor first AND last name. - After Arman's fix, USPTO also stores first name in inventors_names. - """ + def uspto_query_by_inventor( + self, + last_name: str, + first_name: str | None = None, + size: int = DEFAULT_SEARCH_SIZE, + ) -> dict[str, Any]: + """Search USPTO index: first AND last name in the SAME inventor entry.""" if first_name: query = { - "bool": { - "must": [ - { - "match": { - "inventors_names_text": { - "query": last_name, - "operator": "and", - } - } - }, - { - "match": { - "inventors_names_text": { - "query": first_name, - "operator": "and", - } - } - }, - ] + "nested": { + "path": "inventors", + "query": { + "bool": { + "must": [ + _match_name_field("inventors.name", last_name), + _match_name_field("inventors.name", first_name), + ] + } + }, } } else: query = { - "match": { - "inventors_names_text": { - "query": last_name, - "operator": "and", - } + "nested": { + "path": "inventors", + "query": _match_name_field("inventors.name", last_name), } } return { "size": size, "track_total_hits": True, + "sort": [ + {"_score": {"order": "desc"}}, + {"publication_date": {"order": "desc", "missing": "_last"}}, + "_doc", + ], "_source": [ "publication_number", "country", @@ -169,4 +179,4 @@ class PatentSearchClient: json=payload, ) response.raise_for_status() - return response.json() \ No newline at end of file + return response.json() diff --git a/service/src/main/inse/patents/logic.py b/service/src/main/inse/patents/logic.py index ff30648c..a68f6af8 100644 --- a/service/src/main/inse/patents/logic.py +++ b/service/src/main/inse/patents/logic.py @@ -4,7 +4,6 @@ Business logic for patent matching by author name. """ import logging -from collections import defaultdict import httpx from fastapi import HTTPException @@ -16,6 +15,7 @@ from ..models.author import Author from . import model from .elastic_search_client import MissingApiKeyError from .elastic_search_client import PatentSearchClient +from .name_matching import name_matches logger = logging.getLogger(__name__) @@ -60,17 +60,14 @@ async def get_patents_by_author_id( all_patents = _parse_epo_hits(epo_data) + _parse_uspto_hits(uspto_data) - # Group by patent_id and keep one version per patent - grouped: dict[str, model.PatentEntry] = {} - for patent in all_patents: - if patent.patent_id not in grouped: - grouped[patent.patent_id] = patent + if first_name and last_name: + all_patents = _filter_patents_by_name(all_patents, first_name, last_name) return model.PatentsByAuthorResponse( author_id=author_id, author_name=author_name, - patent_count=len(grouped), - patents=list(grouped.values()), + patent_count=len(all_patents), + patents=all_patents, ) @@ -95,8 +92,8 @@ def _parse_epo_hits(data: dict) -> list[model.PatentEntry]: source="EPO", title=src.get("title_en") or src.get("title_de"), abstract=src.get("abstract"), - publication_date=src.get("date_publication"), - publication_year=src.get("date_publication_year"), + publication_date=str(src.get("date_publication")) if src.get("date_publication") else None, + publication_year=str(src.get("date_publication_year")) if src.get("date_publication_year") else None, inventors=inventors if isinstance(inventors, list) else [inventors], assignees=applicants if isinstance(applicants, list) else [applicants], ipc=ipc if isinstance(ipc, list) else [ipc], @@ -117,8 +114,8 @@ def _parse_uspto_hits(data: dict) -> list[model.PatentEntry]: source="USPTO", title=src.get("title"), abstract=src.get("abstract"), - publication_date=src.get("publication_date"), - publication_year=src.get("publication_year"), + publication_date=str(src.get("publication_date")) if src.get("publication_date") else None, + publication_year=str(src.get("publication_year")) if src.get("publication_year") else None, inventors=inventors if isinstance(inventors, list) else [inventors], assignees=assignees if isinstance(assignees, list) else [assignees], ipc=ipc if isinstance(ipc, list) else [ipc], @@ -127,6 +124,18 @@ def _parse_uspto_hits(data: dict) -> list[model.PatentEntry]: return patents +def _filter_patents_by_name( + patents: list[model.PatentEntry], + first_name: str, + last_name: str, +) -> list[model.PatentEntry]: + """Keep patents where at least one inventor matches the author name.""" + return [ + patent for patent in patents + if any(name_matches(inventor, first_name, last_name) for inventor in patent.inventors) + ] + + def _get_author(author_id: str) -> Author | None: short_id = author_id.replace("https://openalex.org/", "") result = person_logic.search_persons(author_id=short_id) diff --git a/service/src/main/inse/patents/name_matching.py b/service/src/main/inse/patents/name_matching.py new file mode 100644 index 00000000..659b295c --- /dev/null +++ b/service/src/main/inse/patents/name_matching.py @@ -0,0 +1,242 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" + Name normalization and matching for patent inventor lookup. + + Handles umlauts, diacritics, and common Latin transliterations so that + e.g. 'Müller' matches 'Mueller' and 'Muller'. +""" +import re +import unicodedata + +# Characters that NFKD does not map to ASCII-friendly forms. +_CHAR_REPLACEMENTS: dict[str, str] = { + "ß": "ss", + "ẞ": "ss", + "æ": "ae", + "Æ": "ae", + "œ": "oe", + "Œ": "oe", + "ø": "o", + "Ø": "o", + "đ": "d", + "Đ": "d", + "ð": "d", + "Ð": "d", + "þ": "th", + "Þ": "th", + "ł": "l", + "Ł": "l", + "ı": "i", + "ſ": "s", +} + +# German patent transliterations: ae/oe/ue often stand in for ä/ö/ü. +_DIGRAPH_COLLAPSES: tuple[tuple[str, str], ...] = ( + ("ae", "a"), + ("oe", "o"), + ("ue", "u"), +) + +# Common ASCII spellings in patent records for umlaut-derived vowels. +_PATENT_VOWEL_EXPANSIONS: tuple[tuple[str, str], ...] = ( + (r"u([lmnrt])", r"ue\1"), + (r"o([lmnrt])", r"oe\1"), + (r"a([lmnrt])", r"ae\1"), +) + + +def normalize_name_part(value: str | None) -> str: + """ + Normalize a single name token for comparison. + + Steps: transliteration map -> NFKD -> strip diacritics -> lowercase + -> remove apostrophes/punctuation -> collapse whitespace. + """ + if not value: + return "" + + text = value.strip() + for src, dst in _CHAR_REPLACEMENTS.items(): + text = text.replace(src, dst) + + text = unicodedata.normalize("NFKD", text) + text = "".join(c for c in text if not unicodedata.combining(c)) + text = text.lower() + text = re.sub(r"[''`´]", "", text) + text = re.sub(r"[^\w\s-]", "", text) + text = re.sub(r"\s+", " ", text).strip() + return text + + +def name_token_variants(value: str | None) -> set[str]: + """ + Return equivalent forms of a name token. + + Includes the normalized base plus German digraph collapses + (Mueller -> muller) and hyphen Relaxed forms (Jean-Pierre -> jean pierre). + """ + base = normalize_name_part(value) + if not base: + return set() + + variants = {base} + + for src, dst in _DIGRAPH_COLLAPSES: + if src in base: + variants.add(base.replace(src, dst)) + + if "-" in base: + variants.add(base.replace("-", "")) + variants.add(base.replace("-", " ")) + + return {v for v in variants if v} + + +def _patent_transliteration_expansions(normalized: str) -> set[str]: + """ + ASCII spellings used in patent records (e.g. Müller indexed as Mueller). + + Used for Elasticsearch recall only; post-filter applies stricter matching. + """ + expanded = {normalized} + for pattern, repl in _PATENT_VOWEL_EXPANSIONS: + if re.search(pattern, normalized): + expanded.add(re.sub(pattern, repl, normalized)) + return expanded + + +def tokens_equal( + left: str | None, + right: str | None, + *, + allow_initial: bool = True, +) -> bool: + """True when two name tokens are equivalent after normalization.""" + left_variants = name_token_variants(left) + right_variants = name_token_variants(right) + if not left_variants or not right_variants: + return False + if left_variants & right_variants: + return True + + if not allow_initial: + return False + + return _initial_tokens_match(left, right) + + +def _initial_letter(token: str | None) -> str | None: + normalized = normalize_name_part(token) + if len(normalized) == 1 and normalized.isalpha(): + return normalized + return None + + +def _initial_tokens_match(left: str | None, right: str | None) -> bool: + """True when one token is a single-letter initial matching the other token.""" + left_initial = _initial_letter(left) + right_initial = _initial_letter(right) + left_full = normalize_name_part(left) + right_full = normalize_name_part(right) + + if left_initial and right_full and len(right_full) > 1: + return right_full.startswith(left_initial) + if right_initial and left_full and len(left_full) > 1: + return left_full.startswith(right_initial) + if left_initial and right_initial: + return left_initial == right_initial + return False + + +def _inventor_first_token(inventor_name: str) -> str: + if "," in inventor_name: + _, first_part = [p.strip() for p in inventor_name.split(",", 1)] + return first_part.split()[0] if first_part else "" + parts = inventor_name.split() + return parts[0] if parts else "" + + +def first_name_match_kind( + inventor_name: str, + first_name: str, + last_name: str, +) -> str: + """ + Match quality for the inventor first name: 'full', 'initial', or 'none'. + """ + if not name_matches(inventor_name, first_name, last_name): + return "none" + + inventor_first = _inventor_first_token(inventor_name) + if tokens_equal(inventor_first, first_name, allow_initial=False): + return "full" + return "initial" + + +def search_name_variants(value: str | None) -> list[str]: + """ + Distinct search strings for Elasticsearch, preserving original casing + where useful but including normalized and transliterated forms. + """ + if not value or not value.strip(): + return [] + + seen: set[str] = set() + ordered: list[str] = [] + + def _add(candidate: str) -> None: + key = candidate.casefold() + if candidate.strip() and key not in seen: + seen.add(key) + ordered.append(candidate.strip()) + + _add(value.strip()) + + normalized = normalize_name_part(value) + if normalized: + _add(normalized.title()) + + for variant in name_token_variants(value): + _add(variant.title()) + + for variant in _patent_transliteration_expansions(normalized): + _add(variant.title()) + + if normalized and len(normalized) > 1: + _add(normalized[0].upper()) + + return ordered + + +def name_matches(inventor_name: str, first_name: str, last_name: str) -> bool: + """ + True when an inventor entry matches first_name + last_name. + + Supports: + - USPTO: 'Christian Weber', 'Christian Hans Weber' + - EPO: 'Weber, Christian', 'Weber, Christian Hans' + """ + if not inventor_name or not last_name: + return False + + name = inventor_name.strip() + + if "," in name: + last_part, first_part = [p.strip() for p in name.split(",", 1)] + first_token = first_part.split()[0] if first_part else "" + return ( + tokens_equal(last_part, last_name, allow_initial=False) + and bool(first_name) + and tokens_equal(first_token, first_name) + ) + + parts = name.split() + if len(parts) < 2: + return False + + return ( + tokens_equal(parts[-1], last_name, allow_initial=False) + and bool(first_name) + and tokens_equal(parts[0], first_name) + ) diff --git a/service/src/main/inse/patents/test_elastic_search_client.py b/service/src/main/inse/patents/test_elastic_search_client.py new file mode 100644 index 00000000..08729ea6 --- /dev/null +++ b/service/src/main/inse/patents/test_elastic_search_client.py @@ -0,0 +1,49 @@ +import httpx +import pytest + +from inse.patents.elastic_search_client import ( + DEFAULT_SEARCH_SIZE, + EPO_INDEX, + PatentSearchClient, + USPTO_INDEX, +) + + +@pytest.fixture +def anyio_backend(): + return "asyncio" + + +def test_epo_query_uses_nested_search_and_name_variants(): + client = PatentSearchClient(api_key="test-key") + payload = client.epo_query_by_inventor("Müller", "Christian") + + assert payload["size"] == DEFAULT_SEARCH_SIZE + assert payload["sort"][0] == {"_score": {"order": "desc"}} + nested = payload["query"]["nested"] + assert nested["path"] == "inventors_name_nested" + must = nested["query"]["bool"]["must"] + assert len(must) == 2 + assert "should" in must[0]["bool"] + + +def test_uspto_index_is_3_0(): + assert USPTO_INDEX == "uspto_patents_3.0" + assert EPO_INDEX == "epo_index_1.0" + + +@pytest.mark.anyio +async def test_search_epo_posts_to_correct_index(): + requests: list[str] = [] + + def handler(request: httpx.Request) -> httpx.Response: + requests.append(request.url.path) + return httpx.Response(200, json={"hits": {"hits": []}}) + + transport = httpx.MockTransport(handler) + client = PatentSearchClient(api_key="test-key", transport=transport) + + await client.search_epo(client.epo_query_by_inventor("Weber", "Christian")) + + assert len(requests) == 1 + assert requests[0].endswith(f"/{EPO_INDEX}/_search") diff --git a/service/src/main/inse/patents/test_name_matching.py b/service/src/main/inse/patents/test_name_matching.py new file mode 100644 index 00000000..cc93465d --- /dev/null +++ b/service/src/main/inse/patents/test_name_matching.py @@ -0,0 +1,123 @@ +import pytest + +from inse.patents.name_matching import ( + first_name_match_kind, + name_matches, + name_token_variants, + normalize_name_part, + search_name_variants, + tokens_equal, +) + + +@pytest.mark.parametrize( + ("left", "right"), + [ + ("Müller", "Mueller"), + ("Müller", "Muller"), + ("Schöning", "Schoening"), + ("François", "Francois"), + ("José", "Jose"), + ("García", "Garcia"), + ("Bräun", "Braun"), + ("Straß", "Strass"), + ("Grøn", "Gron"), + ("Małgorzata", "Malgorzata"), + ("Øystein", "Oystein"), + ], +) +def test_tokens_equal_transliteration(left: str, right: str) -> None: + assert tokens_equal(left, right) + + +@pytest.mark.parametrize( + ("left", "right"), + [ + ("Christian", "Marc"), + ("Weber", "Wagner"), + ("Müller", "Meier"), + ], +) +def test_tokens_equal_rejects_different_names(left: str, right: str) -> None: + assert not tokens_equal(left, right) + + +def test_hyphenated_first_name() -> None: + assert tokens_equal("Jean-Pierre", "Jean Pierre") + assert tokens_equal("Jean-Pierre", "JeanPierre") + + +@pytest.mark.parametrize( + ("inventor", "first", "last", "expected"), + [ + ("Christian Weber", "Christian", "Weber", True), + ("Weber, Christian", "Christian", "Weber", True), + ("Marc Christian Weber", "Christian", "Weber", False), + ("Müller, Hans", "Hans", "Müller", True), + ("Mueller, Hans", "Hans", "Müller", True), + ("Hans Mueller", "Hans", "Müller", True), + ("Weber, Christian Hans", "Christian", "Weber", True), + ("Schoening, Klaus", "Klaus", "Schöning", True), + ], +) +def test_name_matches(inventor: str, first: str, last: str, expected: bool) -> None: + assert name_matches(inventor, first, last) is expected + + +def test_normalize_name_part_strips_diacritics() -> None: + assert normalize_name_part("François") == "francois" + assert normalize_name_part(" O'Brien ") == "obrien" + + +def test_search_name_variants_includes_transliterations() -> None: + variants = search_name_variants("Müller") + folded = {v.casefold() for v in variants} + assert "müller" in folded or "Müller".casefold() in folded + assert "mueller" in folded + assert "muller" in folded + + +def test_name_token_variants_mueller() -> None: + variants = name_token_variants("Mueller") + assert "mueller" in variants + assert "muller" in variants + + +@pytest.mark.parametrize( + ("left", "right"), + [ + ("C", "Christian"), + ("C.", "Christian"), + ("Christian", "C"), + ], +) +def test_tokens_equal_initials(left: str, right: str) -> None: + assert tokens_equal(left, right) + + +def test_tokens_equal_initials_not_for_last_names_by_default() -> None: + assert not tokens_equal("W", "Weber", allow_initial=False) + + +@pytest.mark.parametrize( + ("inventor", "first", "last", "expected"), + [ + ("C. Weber", "Christian", "Weber", True), + ("Weber, C.", "Christian", "Weber", True), + ("Weber, C", "Christian", "Weber", True), + ], +) +def test_name_matches_initials(inventor: str, first: str, last: str, expected: bool) -> None: + assert name_matches(inventor, first, last) is expected + + +def test_first_name_match_kind() -> None: + assert first_name_match_kind("Christian Weber", "Christian", "Weber") == "full" + assert first_name_match_kind("C. Weber", "Christian", "Weber") == "initial" + assert first_name_match_kind("Marc Christian Weber", "Christian", "Weber") == "none" + + +def test_search_name_variants_includes_initial() -> None: + variants = search_name_variants("Christian") + assert "C" in variants + -- 2.56.1 From fc9c18f9655d0610982cc9da9f8832c8aa2ecbbb Mon Sep 17 00:00:00 2001 From: Khuder Khalti Date: Fri, 19 Jun 2026 22:05:47 +0200 Subject: [PATCH 7/8] feat(patents): add interactive detail view with source card navigation --- .../person-patents.component.html | 102 +++++++++-------- .../person-patents.component.scss | 107 ++++++++++-------- .../person-patents.component.ts | 15 ++- 3 files changed, 124 insertions(+), 100 deletions(-) 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 03370197..559aa284 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.html +++ b/webapp/src/app/modules/person-patents/person-patents.component.html @@ -6,7 +6,6 @@

Keine Patente gefunden.

} @else {
-

{{ filteredPatents.length }} @@ -22,9 +21,58 @@

-
+ @if (showDetail && selectedPatent) { + + } -
+
+ @if (showDetail && selectedPatent) { +
+

{{ selectedPatent.title ?? selectedPatent.patent_id }}

+ + @if (selectedPatent.abstract) { +
+

Abstract

+

{{ selectedPatent.abstract }}

+
+ } + +
+

Erfinder

+
    + @for (inventor of selectedPatent.inventors; track inventor) { +
  • {{ inventor }}
  • + } +
+
+ + @if (selectedPatent.assignees.length > 0) { +
+

Anmelder

+
    + @for (assignee of selectedPatent.assignees; track assignee) { +
  • {{ assignee }}
  • + } +
+
+ } + + @if (selectedPatent.ipc.length > 0) { +
+

Klassifikation (IPC)

+
    + @for (ipc of selectedPatent.ipc; track ipc) { +
  • {{ ipc }}
  • + } +
+
+ } +
+ } + +
} diff --git a/webapp/src/app/modules/person-patents/person-patents.component.scss b/webapp/src/app/modules/person-patents/person-patents.component.scss index 9f511648..df70826d 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.scss +++ b/webapp/src/app/modules/person-patents/person-patents.component.scss @@ -31,40 +31,6 @@ } } -.filter-bar { - display: inline-flex; - align-items: center; - gap: 6px; - width: fit-content; - padding: 10px 14px; - border-radius: 20px; - background: #f2f2f2; - color: #333; - font-size: 14px; - - span { - color: #555; - } - - button { - border: 0; - background: transparent; - color: #111827; - font: inherit; - cursor: pointer; - outline: none; - - &.active { - font-weight: 600; - color: #0b63ce; - } - - &:hover { - text-decoration: underline; - } - } -} - .sort-control { display: inline-flex; align-items: center; @@ -99,6 +65,10 @@ .patents-list { flex: 1; + &.hidden { + display: none; + } + .patents-list-toolbar { display: flex; align-items: center; @@ -190,27 +160,12 @@ color: #333; line-height: 1.4; } - - h4 { - margin: 16px 0 8px 0; - font-size: 14px; - color: #555; - font-weight: 600; - } - - p { - font-size: 13px; - color: #444; - line-height: 1.6; - margin: 0; - } } .detail-stats { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; - margin-bottom: 16px; .stat { background: white; @@ -237,6 +192,60 @@ } } +.stat--clickable { + cursor: pointer; + transition: border-color 0.15s, background 0.15s; + + &:hover { + border-color: #0b63ce; + background: #f0f6ff; + } +} + +.patent-full-detail { + flex: 1; + border: 1px solid #e0e0e0; + border-radius: 8px; + padding: 20px; + background: #fafafa; + + h3 { + margin: 0 0 16px 0; + font-size: 16px; + color: #333; + line-height: 1.4; + } + + h4 { + margin: 16px 0 8px 0; + font-size: 14px; + color: #555; + font-weight: 600; + } + + p { + font-size: 13px; + color: #444; + line-height: 1.6; + margin: 0; + } +} + +.back-btn { + border: none; + background: none; + color: #333; + cursor: pointer; + font-size: 14px; + font-weight: 400; + padding: 0; + align-self: flex-start; // NEU + + &:hover { + text-decoration: underline; + } +} + .detail-section { margin-top: 12px; padding-top: 12px; 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 507f1e88..4c71be01 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.ts +++ b/webapp/src/app/modules/person-patents/person-patents.component.ts @@ -21,6 +21,7 @@ export class PersonPatentsComponent implements OnInit { filteredPatents: PatentEntry[] = []; authorName: string | null = null; selectedPatent: PatentEntry | null = null; + showDetail = false; loading = true; error = false; @@ -66,6 +67,7 @@ export class PersonPatentsComponent implements OnInit { this.activeFilter = filter; this.selectedPage = 1; this.selectedPatent = null; + this.showDetail = false; this.applyFilter(); this.updateQueryParams(); } @@ -78,9 +80,14 @@ export class PersonPatentsComponent implements OnInit { selectPatent(patent: PatentEntry): void { this.selectedPatent = patent; + this.showDetail = false; this.updateQueryParams(); } + openDetail(): void { + this.showDetail = true; + } + private applyFilter(): void { let patents = this.patents; @@ -94,13 +101,9 @@ export class PersonPatentsComponent implements OnInit { private sortPatents(patents: PatentEntry[]): PatentEntry[] { return [...patents].sort((a, b) => { if (this.sortMode === 'date') { - return (b.publication_date ?? '').localeCompare( - a.publication_date ?? '', - ); + return (b.publication_date ?? '').localeCompare(a.publication_date ?? ''); } - return (a.title ?? '').localeCompare(b.title ?? '', 'de', { - sensitivity: 'base', - }); + return (a.title ?? '').localeCompare(b.title ?? '', 'de', { sensitivity: 'base' }); }); } -- 2.56.1 From 0cdacf20f75157b531902f37df0cb95d88081fff Mon Sep 17 00:00:00 2001 From: Khuder Khalti Date: Fri, 19 Jun 2026 22:37:51 +0200 Subject: [PATCH 8/8] fix: correct Author import path in patents logic --- service/src/main/inse/patents/logic.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/service/src/main/inse/patents/logic.py b/service/src/main/inse/patents/logic.py index a68f6af8..7e82cc31 100644 --- a/service/src/main/inse/patents/logic.py +++ b/service/src/main/inse/patents/logic.py @@ -11,7 +11,7 @@ from starlette.status import HTTP_502_BAD_GATEWAY from starlette.status import HTTP_503_SERVICE_UNAVAILABLE from ..persons import logic as person_logic -from ..models.author import Author +from ..models.openalex.author import Author from . import model from .elastic_search_client import MissingApiKeyError from .elastic_search_client import PatentSearchClient -- 2.56.1