From bc7b7784ea978c0847f8b96785ae0f022c526b4f Mon Sep 17 00:00:00 2001 From: Khuder Khalti Date: Sun, 14 Jun 2026 11:43:48 +0200 Subject: [PATCH] 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 {