From 9432d01135e3c4396bf2a2d7d76a7913e2c4c513 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Wed, 10 Jun 2026 19:17:20 +0200 Subject: [PATCH 01/24] add news module with business logic and models --- service/src/main/inse/main.py | 2 + service/src/main/inse/news/__init__.py | 0 service/src/main/inse/news/logic.py | 118 +++++++++++++++++++++++++ service/src/main/inse/news/model.py | 25 ++++++ service/src/main/inse/news/service.py | 74 ++++++++++++++++ service/src/main/inse/tags.py | 1 + 6 files changed, 220 insertions(+) create mode 100644 service/src/main/inse/news/__init__.py create mode 100644 service/src/main/inse/news/logic.py create mode 100644 service/src/main/inse/news/model.py create mode 100644 service/src/main/inse/news/service.py diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index a1e4614e..0ec0a2a4 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.news.service import router as news_service_router from . import config from .service import router as service_router @@ -40,6 +41,7 @@ app.include_router(topics_service_router) app.include_router(works_service_router) app.include_router(persons_service_router) app.include_router(funders_service_router) +app.include_router(news_service_router) app.include_router(service_router) app.include_router(account_router) diff --git a/service/src/main/inse/news/__init__.py b/service/src/main/inse/news/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/service/src/main/inse/news/logic.py b/service/src/main/inse/news/logic.py new file mode 100644 index 00000000..4171ab96 --- /dev/null +++ b/service/src/main/inse/news/logic.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +Business logic for the "aktuell" news index on the INSE cluster. +""" + +import logging + +from fastapi import HTTPException +from starlette.status import HTTP_500_INTERNAL_SERVER_ERROR + +from ..integrations import elasticsearch +from .model import NewsArticle, NewsArticleDetail, NewsPage + +logger = logging.getLogger(__name__) + + +def get_news_page(page: int, page_size: int) -> NewsPage: + offset = (page - 1) * page_size + + response = _run_search( + query={"match_all": {}}, + source=["date", "maintitle", "author", "url"], + size=page_size, + offset=offset, + sort=[{"date_full": "desc"}], + ) + + return _build_page(response, page, page_size) + + +def search_news(query_text: str, page: int, page_size: int) -> NewsPage: + offset = (page - 1) * page_size + + response = _run_search( + query={"match": {"full_content": query_text}}, + source=["date", "maintitle", "author", "url"], + size=page_size, + offset=offset, + sort=None, + ) + + return _build_page(response, page, page_size) + + +def get_news_by_id(news_id: str) -> NewsArticleDetail: + try: + response = elasticsearch.get( + index="aktuell", + doc_id=news_id, + source=["date", "maintitle", "author", "url", "full_content"], + cluster="inse", + ) + except Exception as exc: + logger.exception("Abruf des News-Artikels fehlgeschlagen.") + raise HTTPException( + status_code=HTTP_500_INTERNAL_SERVER_ERROR, + detail="Etwas ist schiefgelaufen.", + ) from exc + + source = response.get("_source", {}) + + return NewsArticleDetail( + id=response.get("_id"), + date=source.get("date"), + maintitle=source.get("maintitle"), + author=source.get("author"), + url=source.get("url"), + full_content=source.get("full_content"), + ) + + +def _run_search(query: dict, source: list, size: int, offset: int, sort) -> dict: + try: + return elasticsearch.search( + index="aktuell", + query=query, + source=source, + size=size, + offset=offset, + sort=sort, + track_total_hits=True, + cluster="inse", + ) + except Exception as exc: + logger.exception("Elasticsearch-Anfrage an Index 'aktuell' fehlgeschlagen.") + raise HTTPException( + status_code=HTTP_500_INTERNAL_SERVER_ERROR, + detail="Etwas ist schiefgelaufen.", + ) from exc + + +def _build_page(response: dict, page: int, page_size: int) -> NewsPage: + hits_section = response.get("hits", {}) + total = hits_section.get("total", {}).get("value", 0) + + articles = [] + for hit in hits_section.get("hits", []): + articles.append(_parse_hit(hit)) + + return NewsPage( + total=total, + page=page, + page_size=page_size, + results=articles, + ) + + +def _parse_hit(hit: dict) -> NewsArticle: + source = hit.get("_source", {}) + + return NewsArticle( + id=hit.get("_id"), + date=source.get("date"), + maintitle=source.get("maintitle"), + author=source.get("author"), + url=source.get("url"), + ) diff --git a/service/src/main/inse/news/model.py b/service/src/main/inse/news/model.py new file mode 100644 index 00000000..1fee0b8f --- /dev/null +++ b/service/src/main/inse/news/model.py @@ -0,0 +1,25 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +from typing import List, Optional + +from pydantic import BaseModel + + +class NewsArticle(BaseModel): + id: str + date: Optional[str] = None + maintitle: Optional[str] = None + author: Optional[str] = None + url: Optional[str] = None + + +class NewsArticleDetail(NewsArticle): + full_content: Optional[str] = None + + +class NewsPage(BaseModel): + total: int + page: int + page_size: int + results: List[NewsArticle] diff --git a/service/src/main/inse/news/service.py b/service/src/main/inse/news/service.py new file mode 100644 index 00000000..d93a10a8 --- /dev/null +++ b/service/src/main/inse/news/service.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +REST API for the "aktuell" news index. +""" + +from typing import Annotated + +from fastapi import APIRouter +from fastapi import Path +from fastapi import Query + +from inse.tags import Tags +from . import logic +from .model import NewsArticleDetail, NewsPage + +router = APIRouter(prefix="/api/news", tags=[Tags.NEWS]) + + +@router.get( + "", + operation_id="listNews", + response_model=NewsPage, + response_model_exclude_none=True, + summary="Returns a page of news articles, newest first.", + tags=[Tags.NEWS], +) +def list_news( + page: Annotated[ + int, Query(description="Page number (1-based).", ge=1) + ] = 1, + page_size: Annotated[ + int, Query(alias="pageSize", description="Articles per page.", ge=1, le=100) + ] = 10, +): + return logic.get_news_page(page, page_size) + + +@router.get( + "/search", + operation_id="searchNews", + response_model=NewsPage, + response_model_exclude_none=True, + summary="Searches news articles by full text (full_content).", + tags=[Tags.NEWS], +) +def search_news( + query: Annotated[ + str, Query(description="Search term, matched against the full text (full_content).", min_length=1) + ], + page: Annotated[ + int, Query(description="Page number (1-based).", ge=1) + ] = 1, + page_size: Annotated[ + int, Query(alias="pageSize", description="Articles per page.", ge=1, le=100) + ] = 10, +): + return logic.search_news(query, page, page_size) + + +@router.get( + "/{news_id}", + operation_id="getNewsById", + response_model=NewsArticleDetail, + response_model_exclude_none=True, + summary="Returns a single news article including its full content.", + tags=[Tags.NEWS], +) +def get_news_by_id( + news_id: Annotated[ + str, Path(description="The unique id of the news article (Elasticsearch _id).") + ], +): + return logic.get_news_by_id(news_id) diff --git a/service/src/main/inse/tags.py b/service/src/main/inse/tags.py index 21c6b03c..9142f3eb 100644 --- a/service/src/main/inse/tags.py +++ b/service/src/main/inse/tags.py @@ -7,3 +7,4 @@ class Tags(Enum): INSTITUTIONS = "Institutions" TOPICS = "Topics" WORKS = "Works" + NEWS = "News" From 7442a56b0a9061b6770b547fbffdd6a102eab7df Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Thu, 11 Jun 2026 21:40:26 +0200 Subject: [PATCH 02/24] feat(news-tab): add news tab and details page to person overview --- service/src/main/inse/news/logic.py | 4 +- service/src/main/inse/news/service.py | 5 +- webapp/src/app/app.routes.ts | 15 ++ .../news-detail/news-detail.component.html | 92 +++++++ .../news-detail/news-detail.component.scss | 226 ++++++++++++++++++ .../news-detail/news-detail.component.ts | 107 +++++++++ .../person-news/person-news.component.html | 76 ++++++ .../person-news/person-news.component.scss | 156 ++++++++++++ .../person-news/person-news.component.ts | 145 +++++++++++ .../app/modules/person/person.component.ts | 1 + 10 files changed, 824 insertions(+), 3 deletions(-) create mode 100644 webapp/src/app/modules/news-detail/news-detail.component.html create mode 100644 webapp/src/app/modules/news-detail/news-detail.component.scss create mode 100644 webapp/src/app/modules/news-detail/news-detail.component.ts create mode 100644 webapp/src/app/modules/person-news/person-news.component.html create mode 100644 webapp/src/app/modules/person-news/person-news.component.scss create mode 100644 webapp/src/app/modules/person-news/person-news.component.ts diff --git a/service/src/main/inse/news/logic.py b/service/src/main/inse/news/logic.py index 4171ab96..46866d0b 100644 --- a/service/src/main/inse/news/logic.py +++ b/service/src/main/inse/news/logic.py @@ -15,7 +15,7 @@ from .model import NewsArticle, NewsArticleDetail, NewsPage logger = logging.getLogger(__name__) -def get_news_page(page: int, page_size: int) -> NewsPage: +def get_news_page(page: int, page_size: int, sort_order: str = "desc") -> NewsPage: offset = (page - 1) * page_size response = _run_search( @@ -23,7 +23,7 @@ def get_news_page(page: int, page_size: int) -> NewsPage: source=["date", "maintitle", "author", "url"], size=page_size, offset=offset, - sort=[{"date_full": "desc"}], + sort=[{"date_full": sort_order}], ) return _build_page(response, page, page_size) diff --git a/service/src/main/inse/news/service.py b/service/src/main/inse/news/service.py index d93a10a8..0ed5fe6d 100644 --- a/service/src/main/inse/news/service.py +++ b/service/src/main/inse/news/service.py @@ -32,8 +32,11 @@ def list_news( page_size: Annotated[ int, Query(alias="pageSize", description="Articles per page.", ge=1, le=100) ] = 10, + sort_order: Annotated[ + str, Query(alias="sortOrder", description="Sort order: 'desc' (newest first) or 'asc' (oldest first).", pattern="^(asc|desc)$") + ] = "desc", ): - return logic.get_news_page(page, page_size) + return logic.get_news_page(page, page_size, sort_order) @router.get( diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index c19c5b60..def295c4 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -60,6 +60,14 @@ export const routes: Routes = [ return scalarChanged || topicsChanged; }, }, + { + path: 'news/:id', + canActivate: [userGuard], + loadComponent: () => + import('./modules/news-detail/news-detail.component').then( + (mod) => mod.NewsDetailComponent, + ), + }, { path: 'publication/:publicationId', canActivate: [userGuard], @@ -135,6 +143,13 @@ export const routes: Routes = [ (mod) => mod.PersonFundingComponent, ), }, + { + path: 'news', + loadComponent: () => + import('./modules/person-news/person-news.component').then( + (mod) => mod.PersonNewsComponent, + ), + }, ], }, { diff --git a/webapp/src/app/modules/news-detail/news-detail.component.html b/webapp/src/app/modules/news-detail/news-detail.component.html new file mode 100644 index 00000000..6e930151 --- /dev/null +++ b/webapp/src/app/modules/news-detail/news-detail.component.html @@ -0,0 +1,92 @@ +
+ + + @if (loading) { +
+ +

Nachricht wird geladen...

+
+ } @else if (notFound || !article) { +
+ search_off +

Nachricht nicht gefunden

+

Der Artikel konnte nicht geladen werden.

+ Zur Personensuche +
+ } @else { +
+
+
+
+ @if (article.author) { + {{ article.author }} + } + @if (article.date) { + {{ formatDate(article.date) }} + } +
+

{{ article.maintitle || 'Kein Titel' }}

+
+ +
+ @if (article.full_content) { +

{{ article.full_content }}

+ } @else { +

Kein Inhalt verfügbar.

+ } +
+ + @if (article.url) { +
+ + open_in_new + Originalartikel öffnen + +
+ } +
+ + +
+ } +
diff --git a/webapp/src/app/modules/news-detail/news-detail.component.scss b/webapp/src/app/modules/news-detail/news-detail.component.scss new file mode 100644 index 00000000..71b7519e --- /dev/null +++ b/webapp/src/app/modules/news-detail/news-detail.component.scss @@ -0,0 +1,226 @@ +.detail-page { + max-width: 1200px; + margin: 0 auto; + padding: 28px 32px 64px; +} + +.back-link { + display: inline-flex; + align-items: center; + gap: 6px; + background: none; + border: none; + cursor: pointer; + font-size: 14px; + color: var(--sg-text-muted); + padding: 0; + margin-bottom: 32px; + + &:hover { + color: var(--sg-text); + } + + mat-icon { + font-size: 18px; + width: 18px; + height: 18px; + } +} + +.state { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 16px; + padding: 80px 0; + text-align: center; + color: var(--sg-text-muted); + + mat-icon { + font-size: 48px; + width: 48px; + height: 48px; + } + + p { + margin: 0; + } +} + +.error-state h2 { + margin: 0; +} + +.detail-layout { + display: grid; + grid-template-columns: 1fr 280px; + gap: 40px; + align-items: start; +} + +main { + min-width: 0; +} + +.hero { + margin-bottom: 32px; +} + +.eyebrow { + display: flex; + gap: 12px; + font-size: 13px; + color: var(--sg-text-muted); + margin-bottom: 12px; + + span + span::before { + content: '·'; + margin-right: 12px; + } +} + +.article-heading { + margin: 0; + font-size: 28px; + font-weight: 700; + line-height: 1.3; +} + +.article-body { + font-size: 15px; + line-height: 1.7; + color: var(--sg-text); +} + +.content { + margin: 0; + white-space: pre-wrap; +} + +.placeholder { + margin: 0; + color: var(--sg-text-muted); + font-style: italic; +} + +.article-actions { + margin-top: 32px; +} + +.sidebar { + display: flex; + flex-direction: column; + gap: 16px; + position: sticky; + top: 24px; +} + +.sidebar-card { + padding: 20px; + border: 1px solid #d7e4ff; + border-radius: 16px; + background: #ffffff; + box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04); + + h3 { + display: flex; + align-items: center; + gap: 8px; + margin: 0 0 14px; + font-size: 14px; + font-weight: 600; + color: var(--sg-text); + + mat-icon { + font-size: 18px; + width: 18px; + height: 18px; + color: var(--sg-text-muted); + } + } +} + +.person-list { + display: flex; + flex-direction: column; + gap: 8px; +} + +.person-item { + display: grid; + grid-template-columns: 38px minmax(0, 1fr); + gap: 11px; + align-items: center; + padding: 12px; + border-radius: var(--sg-radius-sm); + background: var(--sg-surface-muted); +} + +.avatar { + display: grid; + place-items: center; + width: 38px; + height: 38px; + border-radius: 50%; + background: #e5ecfb; + color: var(--sg-text); + font-size: 15px; + font-weight: 700; + text-transform: uppercase; +} + +.person-name { + color: var(--sg-text); + font-size: 13px; + font-weight: 700; +} + +.chip-list { + display: flex; + flex-wrap: wrap; + gap: 8px; +} + +.topic-chip { + display: inline-flex; + align-items: center; + padding: 6px 12px; + border: 1px solid var(--topic-border); + border-radius: 8px; + background: var(--topic-bg); + color: var(--topic-color); + font-size: 12px; + font-weight: 500; + line-height: 1.25; +} + +.purple { + --topic-border: #d8cafe; + --topic-bg: #f6f0ff; + --topic-color: #7255d9; +} + +.blue { + --topic-border: #bdd4ff; + --topic-bg: #f0f6ff; + --topic-color: #0b63ce; +} + +.green { + --topic-border: #bdebcf; + --topic-bg: #effaf3; + --topic-color: #24834f; +} + +.orange { + --topic-border: #ffd796; + --topic-bg: #fff7e8; + --topic-color: #c67500; +} + +.pink { + --topic-border: #ffc7d7; + --topic-bg: #fff1f5; + --topic-color: #d12f61; +} diff --git a/webapp/src/app/modules/news-detail/news-detail.component.ts b/webapp/src/app/modules/news-detail/news-detail.component.ts new file mode 100644 index 00000000..3bbca4d1 --- /dev/null +++ b/webapp/src/app/modules/news-detail/news-detail.component.ts @@ -0,0 +1,107 @@ +import { Component, DestroyRef, OnInit, inject } from '@angular/core'; +import { Location, NgClass } from '@angular/common'; +import { HttpClient } from '@angular/common/http'; +import { ActivatedRoute, RouterLink } from '@angular/router'; +import { MatButtonModule } from '@angular/material/button'; +import { MatIconModule } from '@angular/material/icon'; +import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; + +import { WorksService } from '../../api'; + +interface NewsArticleDetail { + id: string; + date?: string | null; + maintitle?: string | null; + author?: string | null; + url?: string | null; + full_content?: string | null; +} + +@Component({ + selector: 'app-news-detail', + imports: [ + MatButtonModule, + MatIconModule, + MatProgressSpinnerModule, + RouterLink, + NgClass, + ], + templateUrl: './news-detail.component.html', + styleUrl: './news-detail.component.scss', +}) +export class NewsDetailComponent implements OnInit { + private readonly destroyRef = inject(DestroyRef); + private readonly route = inject(ActivatedRoute); + private readonly httpClient = inject(HttpClient); + private readonly worksService = inject(WorksService); + private readonly location = inject(Location); + + article: NewsArticleDetail | null = null; + loading = false; + notFound = false; + + readonly mentionedPersons = [ + 'Prof. Dr. Anna Müller', + 'Dr. Hans Schmidt', + 'Dr. Lena Weber', + ]; + + readonly relevantTopics = [ + 'Künstliche Intelligenz', + 'Maschinelles Lernen', + 'Digitalisierung', + 'Datenwissenschaft', + ]; + + private readonly chipColors = ['purple', 'blue', 'green', 'orange', 'pink']; + + chipColor(index: number): string { + return this.chipColors[index % this.chipColors.length]; + } + + ngOnInit(): void { + this.route.paramMap + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe((params) => { + const id = params.get('id'); + if (id) { + this.fetchArticle(id); + } + }); + } + + navigateBack(): void { + this.location.back(); + } + + formatDate(dateStr?: string | null): string { + if (!dateStr) return '-'; + const date = new Date(dateStr); + if (isNaN(date.getTime())) return dateStr; + return new Intl.DateTimeFormat('de-DE', { + day: '2-digit', + month: 'long', + year: 'numeric', + }).format(date); + } + + private fetchArticle(id: string): void { + this.loading = true; + this.notFound = false; + const basePath = this.worksService.configuration.basePath ?? ''; + this.httpClient + .get(`${basePath}/api/news/${encodeURIComponent(id)}`) + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe({ + next: (article) => { + this.article = article; + this.loading = false; + }, + error: () => { + this.notFound = true; + this.loading = false; + }, + }); + } +} diff --git a/webapp/src/app/modules/person-news/person-news.component.html b/webapp/src/app/modules/person-news/person-news.component.html new file mode 100644 index 00000000..d5477d07 --- /dev/null +++ b/webapp/src/app/modules/person-news/person-news.component.html @@ -0,0 +1,76 @@ +
+
+
Nachrichten
+

Aktuelle Nachrichten zu dieser Person.

+
+ +
+ + search + + + + + + Neueste zuerst + Älteste zuerst + + +
+ +
+ @if (loading) { +
+ +
+ } + + + + + + + + + + + + + + + + + + + +
Titel + {{ + article.maintitle || 'Kein Titel' + }} + Autor + {{ article.author || '-' }} + Datum + {{ formatDate(article.date) }} +
+ + @if (!loading && articles.length === 0) { +
Keine Nachrichten gefunden.
+ } +
+ + +
diff --git a/webapp/src/app/modules/person-news/person-news.component.scss b/webapp/src/app/modules/person-news/person-news.component.scss new file mode 100644 index 00000000..68a1899f --- /dev/null +++ b/webapp/src/app/modules/person-news/person-news.component.scss @@ -0,0 +1,156 @@ +.page { + padding: 28px 32px 42px; + max-width: 100%; + margin: 0 auto; +} + +h6 { + margin: 0 0 6px; + font-size: 22px; + line-height: 1.2; + font-weight: 700; +} + +.page > div:first-child p { + margin: 0; + color: var(--sg-text-muted); + font-size: 14px; +} + +.news-toolbar { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 12px; + padding-top: 10px; + padding-bottom: 25px; +} + +.search-field { + max-width: 480px; +} + +::ng-deep .news-toolbar .mat-mdc-form-field-subscript-wrapper { + display: none; +} + +::ng-deep .news-toolbar .mat-mdc-text-field-wrapper { + height: 42px; + background: #fff; + border-radius: var(--sg-radius-sm); +} + +::ng-deep .news-toolbar .mat-mdc-form-field-infix { + min-height: unset; + height: 42px; + padding: 0; + display: flex; + align-items: center; +} + +::ng-deep .news-toolbar .mdc-notched-outline__leading, +::ng-deep .news-toolbar .mdc-notched-outline__notch, +::ng-deep .news-toolbar .mdc-notched-outline__trailing { + border-color: #d9e2f0; +} + +::ng-deep .news-toolbar input.mat-mdc-input-element { + color: var(--sg-text); + font-size: 14px; +} + +::ng-deep .news-toolbar input.mat-mdc-input-element::placeholder { + color: var(--sg-text-muted); + opacity: 1; + font-size: 14px; +} + +.sort-field { + width: 180px; +} + +.table-wrap { + position: relative; + overflow-x: auto; +} + +table { + width: 100%; + min-width: 600px; + border-collapse: separate; + border-spacing: 0 10px; + background: transparent; + box-shadow: none; +} + +.article-title { + display: inline-block; + max-width: 520px; + line-height: 1.35; + color: var(--sg-text); + font-size: 14px; + font-weight: 700; + text-decoration: none; + + &:hover { + color: var(--sg-text); + text-decoration: underline; + } +} + +.loading { + position: absolute; + inset: 0; + z-index: 1; + display: grid; + place-items: center; + background: rgba(255, 255, 255, 0.65); +} + +.empty-state { + padding: 28px; + text-align: center; + color: rgba(0, 0, 0, 0.6); + background: transparent; +} + +::ng-deep .mat-mdc-header-cell { + color: var(--sg-text-muted); + font-size: 12px; + font-weight: 700; +} + +::ng-deep .mat-mdc-row { + height: 72px; +} + +::ng-deep .mat-mdc-cell { + color: var(--sg-text); + border-bottom-color: var(--sg-border); + font-size: 13px; +} + +mat-paginator { + background: transparent; +} + +.table-footer { + display: flex; + align-items: center; + justify-content: space-between; + min-height: 66px; + padding: 0 22px 0 28px; + color: var(--sg-text-muted); + font-size: 13px; +} + +@media (max-width: 600px) { + .page { + padding: 16px; + } + + .table-footer { + align-items: stretch; + flex-direction: column; + } +} diff --git a/webapp/src/app/modules/person-news/person-news.component.ts b/webapp/src/app/modules/person-news/person-news.component.ts new file mode 100644 index 00000000..7c69ef2c --- /dev/null +++ b/webapp/src/app/modules/person-news/person-news.component.ts @@ -0,0 +1,145 @@ +import { + Component, + DestroyRef, + OnInit, + ViewChild, + inject, +} from '@angular/core'; +import { HttpClient, HttpParams } from '@angular/common/http'; +import { FormControl, ReactiveFormsModule } from '@angular/forms'; +import { ActivatedRoute, RouterLink } from '@angular/router'; +import { MatIconModule } from '@angular/material/icon'; +import { MatSelectModule } from '@angular/material/select'; +import { + MatPaginator, + MatPaginatorModule, + PageEvent, +} from '@angular/material/paginator'; +import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; +import { MatTableModule } from '@angular/material/table'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatInputModule } from '@angular/material/input'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; + +import { WorksService } from '../../api'; +import { PaginationService } from '../../shared/services/pagination.service'; + +interface NewsArticle { + id: string; + date?: string | null; + maintitle?: string | null; + author?: string | null; + url?: string | null; +} + +interface NewsPage { + total: number; + page: number; + page_size: number; + results: NewsArticle[]; +} + +const ARTICLE_CAP = 100; + +@Component({ + selector: 'app-person-news', + imports: [ + MatIconModule, + MatSelectModule, + MatFormFieldModule, + MatInputModule, + MatPaginatorModule, + MatProgressSpinnerModule, + MatTableModule, + ReactiveFormsModule, + RouterLink, + ], + templateUrl: './person-news.component.html', + styleUrl: './person-news.component.scss', +}) +export class PersonNewsComponent implements OnInit { + @ViewChild(MatPaginator) paginator?: MatPaginator; + private readonly destroyRef = inject(DestroyRef); + private readonly route = inject(ActivatedRoute); + private readonly httpClient = inject(HttpClient); + private readonly worksService = inject(WorksService); + readonly paginationService = inject(PaginationService); + + readonly searchControl = new FormControl('', { nonNullable: true }); + + displayedColumns = ['maintitle', 'author', 'date']; + private allArticles: NewsArticle[] = []; + articles: NewsArticle[] = []; + total = 0; + loading = false; + currentPageIndex = 0; + sortOrder: 'desc' | 'asc' = 'desc'; + + ngOnInit(): void { + this.route.parent?.paramMap + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe(() => { + this.load(); + }); + } + + load(): void { + this.loading = true; + const params = new HttpParams() + .set('page', 1) + .set('pageSize', ARTICLE_CAP) + .set('sortOrder', this.sortOrder); + + const basePath = this.worksService.configuration.basePath ?? ''; + this.httpClient + .get(`${basePath}/api/news`, { params }) + .subscribe({ + next: (page) => { + this.allArticles = page.results ?? []; + this.total = this.allArticles.length; + this.currentPageIndex = 0; + this.updatePage(); + this.loading = false; + }, + error: () => { + this.loading = false; + }, + }); + } + + onPage(event: PageEvent): void { + this.paginationService.selection = event.pageSize; + this.currentPageIndex = event.pageIndex; + this.updatePage(); + } + + formatDate(dateStr?: string | null): string { + if (!dateStr) return '-'; + const date = new Date(dateStr); + if (isNaN(date.getTime())) return dateStr; + return new Intl.DateTimeFormat('de-DE').format(date); + } + + articleRange(): string { + if (this.total === 0) return 'Keine Nachrichten gefunden'; + const start = this.currentPageIndex * this.paginationService.selection + 1; + const end = Math.min( + start + this.paginationService.selection - 1, + this.total, + ); + return `Zeige ${start} bis ${end} von ${this.total} Nachrichten`; + } + + onSortChange(order: 'desc' | 'asc'): void { + this.sortOrder = order; + this.load(); + } + + private updatePage(): void { + const start = this.currentPageIndex * this.paginationService.selection; + this.articles = this.allArticles.slice( + start, + start + this.paginationService.selection, + ); + } +} diff --git a/webapp/src/app/modules/person/person.component.ts b/webapp/src/app/modules/person/person.component.ts index 2dd189ec..46a8c068 100644 --- a/webapp/src/app/modules/person/person.component.ts +++ b/webapp/src/app/modules/person/person.component.ts @@ -176,6 +176,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: 'Nachrichten', path: 'news', disabled: false }, ]; onInterestingTagClick(selection: { id: string; name: string }): void { From bc7b7784ea978c0847f8b96785ae0f022c526b4f Mon Sep 17 00:00:00 2001 From: Khuder Khalti Date: Sun, 14 Jun 2026 11:43:48 +0200 Subject: [PATCH 03/24] 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 { From 977ac97241d7b57d0e04388b57316ed97695852d Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Mon, 15 Jun 2026 17:46:20 +0200 Subject: [PATCH 04/24] add page news --- webapp/src/app/app.routes.ts | 6 + .../src/app/modules/news/news.component.html | 76 ++++++++ .../src/app/modules/news/news.component.scss | 156 +++++++++++++++++ webapp/src/app/modules/news/news.component.ts | 165 ++++++++++++++++++ .../shared/ui/app-menu/app-menu.component.ts | 6 + 5 files changed, 409 insertions(+) create mode 100644 webapp/src/app/modules/news/news.component.html create mode 100644 webapp/src/app/modules/news/news.component.scss create mode 100644 webapp/src/app/modules/news/news.component.ts diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index c6c2707c..0dd9d706 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -64,6 +64,12 @@ export const routes: Routes = [ return scalarChanged || topicsChanged; }, }, + { + path: 'news', + canActivate: [userGuard], + loadComponent: () => + import('./modules/news/news.component').then((mod) => mod.NewsComponent), + }, { path: 'news/:id', canActivate: [userGuard], diff --git a/webapp/src/app/modules/news/news.component.html b/webapp/src/app/modules/news/news.component.html new file mode 100644 index 00000000..5004b3e5 --- /dev/null +++ b/webapp/src/app/modules/news/news.component.html @@ -0,0 +1,76 @@ +
+
+
Nachrichten
+

Aktuelle Nachrichten aus Campus-Aktuell.

+
+ +
+ + search + + + + + + Neueste zuerst + Älteste zuerst + + +
+ +
+ @if (loading) { +
+ +
+ } + + + + + + + + + + + + + + + + + + + +
Titel + {{ + article.maintitle || 'Kein Titel' + }} + Autor + {{ article.author || '-' }} + Datum + {{ formatDate(article.date) }} +
+ + @if (!loading && articles.length === 0) { +
Keine Nachrichten gefunden.
+ } +
+ + +
diff --git a/webapp/src/app/modules/news/news.component.scss b/webapp/src/app/modules/news/news.component.scss new file mode 100644 index 00000000..68a1899f --- /dev/null +++ b/webapp/src/app/modules/news/news.component.scss @@ -0,0 +1,156 @@ +.page { + padding: 28px 32px 42px; + max-width: 100%; + margin: 0 auto; +} + +h6 { + margin: 0 0 6px; + font-size: 22px; + line-height: 1.2; + font-weight: 700; +} + +.page > div:first-child p { + margin: 0; + color: var(--sg-text-muted); + font-size: 14px; +} + +.news-toolbar { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 12px; + padding-top: 10px; + padding-bottom: 25px; +} + +.search-field { + max-width: 480px; +} + +::ng-deep .news-toolbar .mat-mdc-form-field-subscript-wrapper { + display: none; +} + +::ng-deep .news-toolbar .mat-mdc-text-field-wrapper { + height: 42px; + background: #fff; + border-radius: var(--sg-radius-sm); +} + +::ng-deep .news-toolbar .mat-mdc-form-field-infix { + min-height: unset; + height: 42px; + padding: 0; + display: flex; + align-items: center; +} + +::ng-deep .news-toolbar .mdc-notched-outline__leading, +::ng-deep .news-toolbar .mdc-notched-outline__notch, +::ng-deep .news-toolbar .mdc-notched-outline__trailing { + border-color: #d9e2f0; +} + +::ng-deep .news-toolbar input.mat-mdc-input-element { + color: var(--sg-text); + font-size: 14px; +} + +::ng-deep .news-toolbar input.mat-mdc-input-element::placeholder { + color: var(--sg-text-muted); + opacity: 1; + font-size: 14px; +} + +.sort-field { + width: 180px; +} + +.table-wrap { + position: relative; + overflow-x: auto; +} + +table { + width: 100%; + min-width: 600px; + border-collapse: separate; + border-spacing: 0 10px; + background: transparent; + box-shadow: none; +} + +.article-title { + display: inline-block; + max-width: 520px; + line-height: 1.35; + color: var(--sg-text); + font-size: 14px; + font-weight: 700; + text-decoration: none; + + &:hover { + color: var(--sg-text); + text-decoration: underline; + } +} + +.loading { + position: absolute; + inset: 0; + z-index: 1; + display: grid; + place-items: center; + background: rgba(255, 255, 255, 0.65); +} + +.empty-state { + padding: 28px; + text-align: center; + color: rgba(0, 0, 0, 0.6); + background: transparent; +} + +::ng-deep .mat-mdc-header-cell { + color: var(--sg-text-muted); + font-size: 12px; + font-weight: 700; +} + +::ng-deep .mat-mdc-row { + height: 72px; +} + +::ng-deep .mat-mdc-cell { + color: var(--sg-text); + border-bottom-color: var(--sg-border); + font-size: 13px; +} + +mat-paginator { + background: transparent; +} + +.table-footer { + display: flex; + align-items: center; + justify-content: space-between; + min-height: 66px; + padding: 0 22px 0 28px; + color: var(--sg-text-muted); + font-size: 13px; +} + +@media (max-width: 600px) { + .page { + padding: 16px; + } + + .table-footer { + align-items: stretch; + flex-direction: column; + } +} diff --git a/webapp/src/app/modules/news/news.component.ts b/webapp/src/app/modules/news/news.component.ts new file mode 100644 index 00000000..a6df56f2 --- /dev/null +++ b/webapp/src/app/modules/news/news.component.ts @@ -0,0 +1,165 @@ +import { Component, DestroyRef, OnInit, inject } from '@angular/core'; +import { HttpClient, HttpParams } from '@angular/common/http'; +import { FormControl, ReactiveFormsModule } from '@angular/forms'; +import { ActivatedRoute, Router, RouterLink } from '@angular/router'; +import { MatIconModule } from '@angular/material/icon'; +import { MatSelectModule } from '@angular/material/select'; +import { MatPaginatorModule, PageEvent } from '@angular/material/paginator'; +import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; +import { MatTableModule } from '@angular/material/table'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatInputModule } from '@angular/material/input'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; + +import { WorksService } from '../../api'; +import { PaginationService } from '../../shared/services/pagination.service'; + +interface NewsArticle { + id: string; + date?: string | null; + maintitle?: string | null; + author?: string | null; + url?: string | null; +} + +interface NewsPage { + total: number; + page: number; + page_size: number; + results: NewsArticle[]; +} + +type SortOrder = 'desc' | 'asc'; +const DEFAULT_SORT_ORDER: SortOrder = 'desc'; + +@Component({ + selector: 'app-news', + imports: [ + MatIconModule, + MatSelectModule, + MatFormFieldModule, + MatInputModule, + MatPaginatorModule, + MatProgressSpinnerModule, + MatTableModule, + ReactiveFormsModule, + RouterLink, + ], + templateUrl: './news.component.html', + styleUrl: './news.component.scss', +}) +export class NewsComponent implements OnInit { + private readonly destroyRef = inject(DestroyRef); + private readonly route = inject(ActivatedRoute); + private readonly router = inject(Router); + private readonly httpClient = inject(HttpClient); + private readonly worksService = inject(WorksService); + readonly paginationService = inject(PaginationService); + + readonly searchControl = new FormControl('', { nonNullable: true }); + + displayedColumns = ['maintitle', 'author', 'date']; + articles: NewsArticle[] = []; + total = 0; + loading = false; + + currentPage = 1; + sortOrder: SortOrder = DEFAULT_SORT_ORDER; + + ngOnInit(): void { + this.route.queryParamMap + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe((params) => { + this.currentPage = this.parsePage(params.get('page')); + this.paginationService.selection = this.parsePageSize( + params.get('pageSize'), + ); + this.sortOrder = this.parseSortOrder(params.get('sortOrder')); + this.load(); + }); + } + + load(): void { + this.loading = true; + const params = new HttpParams() + .set('page', this.currentPage) + .set('pageSize', this.paginationService.selection) + .set('sortOrder', this.sortOrder); + + const basePath = this.worksService.configuration.basePath ?? ''; + this.httpClient + .get(`${basePath}/api/news`, { params }) + .subscribe({ + next: (page) => { + this.articles = page.results ?? []; + this.total = page.total ?? 0; + this.loading = false; + }, + error: () => { + this.articles = []; + this.total = 0; + this.loading = false; + }, + }); + } + + onPage(event: PageEvent): void { + this.router.navigate([], { + relativeTo: this.route, + queryParams: { + page: event.pageIndex + 1, + pageSize: event.pageSize, + }, + queryParamsHandling: 'merge', + }); + } + + onSortChange(order: SortOrder): void { + this.router.navigate([], { + relativeTo: this.route, + queryParams: { + sortOrder: order, + page: 1, + }, + queryParamsHandling: 'merge', + }); + } + + formatDate(dateStr?: string | null): string { + if (!dateStr) return '-'; + const date = new Date(dateStr); + if (isNaN(date.getTime())) return dateStr; + return new Intl.DateTimeFormat('de-DE').format(date); + } + + articleRange(): string { + if (this.total === 0) return 'Keine Nachrichten gefunden'; + const pageSize = this.paginationService.selection; + const start = (this.currentPage - 1) * pageSize + 1; + const end = Math.min(start + this.articles.length - 1, this.total); + return `Zeige ${start} bis ${end} von ${this.total} Nachrichten`; + } + + private parsePage(value: string | null): number { + const page = Number.parseInt(value ?? '', 10); + if (Number.isNaN(page) || page < 1) { + return 1; + } + return page; + } + + private parsePageSize(value: string | null): number { + const pageSize = Number.parseInt(value ?? '', 10); + if (this.paginationService.options.includes(pageSize)) { + return pageSize; + } + return 10; + } + + private parseSortOrder(value: string | null): SortOrder { + if (value === 'asc' || value === 'desc') { + return value; + } + return DEFAULT_SORT_ORDER; + } +} diff --git a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts index 371cedb4..7e63b2a3 100644 --- a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts +++ b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts @@ -35,6 +35,12 @@ export class AppMenuComponent { queryParams: { institutionName: 'University of Duisburg-Essen' }, disabled: false, }, + { + label: 'News', + icon: 'newspaper', + route: '/news', + disabled: false, + }, ]; constructor( From 0dd03e0ae0ea25cccebb24aa5c7a22096b4f2f36 Mon Sep 17 00:00:00 2001 From: taguesokoudjou Date: Mon, 15 Jun 2026 20:27:21 +0200 Subject: [PATCH 05/24] 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; From c298a388d0ab64c44f00a13734b047ae3e8cf20e Mon Sep 17 00:00:00 2001 From: taguesokoudjou Date: Mon, 15 Jun 2026 20:41:32 +0200 Subject: [PATCH 06/24] 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) }} - } -

- }
@@ -59,7 +61,13 @@ @if (!loading && articles.length === 0) { -
Keine Nachrichten gefunden.
+
+ @if (isSearching) { + Keine Ergebnisse für „{{ searchControl.value.trim() }}" gefunden. + } @else { + Keine Nachrichten gefunden. + } +
}
diff --git a/webapp/src/app/modules/news/news.component.ts b/webapp/src/app/modules/news/news.component.ts index a6df56f2..e6990dbb 100644 --- a/webapp/src/app/modules/news/news.component.ts +++ b/webapp/src/app/modules/news/news.component.ts @@ -10,6 +10,7 @@ import { MatTableModule } from '@angular/material/table'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatInputModule } from '@angular/material/input'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { debounceTime, distinctUntilChanged } from 'rxjs'; import { WorksService } from '../../api'; import { PaginationService } from '../../shared/services/pagination.service'; @@ -66,6 +67,10 @@ export class NewsComponent implements OnInit { currentPage = 1; sortOrder: SortOrder = DEFAULT_SORT_ORDER; + get isSearching(): boolean { + return this.searchControl.value.trim().length > 0; + } + ngOnInit(): void { this.route.queryParamMap .pipe(takeUntilDestroyed(this.destroyRef)) @@ -75,32 +80,73 @@ export class NewsComponent implements OnInit { params.get('pageSize'), ); this.sortOrder = this.parseSortOrder(params.get('sortOrder')); + this.searchControl.setValue(params.get('q') ?? '', { + emitEvent: false, + }); this.load(); }); + + this.searchControl.valueChanges + .pipe( + debounceTime(300), + distinctUntilChanged(), + takeUntilDestroyed(this.destroyRef), + ) + .subscribe((query) => { + this.router.navigate([], { + relativeTo: this.route, + queryParams: { q: query.trim() || null, page: 1 }, + queryParamsHandling: 'merge', + }); + }); } load(): void { this.loading = true; - const params = new HttpParams() - .set('page', this.currentPage) - .set('pageSize', this.paginationService.selection) - .set('sortOrder', this.sortOrder); - + const query = this.searchControl.value.trim(); const basePath = this.worksService.configuration.basePath ?? ''; - this.httpClient - .get(`${basePath}/api/news`, { params }) - .subscribe({ - next: (page) => { - this.articles = page.results ?? []; - this.total = page.total ?? 0; - this.loading = false; - }, - error: () => { - this.articles = []; - this.total = 0; - this.loading = false; - }, - }); + + if (query) { + const params = new HttpParams() + .set('query', query) + .set('page', this.currentPage) + .set('pageSize', this.paginationService.selection); + + this.httpClient + .get(`${basePath}/api/news/search`, { params }) + .subscribe({ + next: (page) => { + this.articles = page.results ?? []; + this.total = page.total ?? 0; + this.loading = false; + }, + error: () => { + this.articles = []; + this.total = 0; + this.loading = false; + }, + }); + } else { + const params = new HttpParams() + .set('page', this.currentPage) + .set('pageSize', this.paginationService.selection) + .set('sortOrder', this.sortOrder); + + this.httpClient + .get(`${basePath}/api/news`, { params }) + .subscribe({ + next: (page) => { + this.articles = page.results ?? []; + this.total = page.total ?? 0; + this.loading = false; + }, + error: () => { + this.articles = []; + this.total = 0; + this.loading = false; + }, + }); + } } onPage(event: PageEvent): void { diff --git a/webapp/src/app/modules/person-news/person-news.component.html b/webapp/src/app/modules/person-news/person-news.component.html index d5477d07..b4f717db 100644 --- a/webapp/src/app/modules/person-news/person-news.component.html +++ b/webapp/src/app/modules/person-news/person-news.component.html @@ -59,7 +59,13 @@ @if (!loading && articles.length === 0) { -
Keine Nachrichten gefunden.
+
+ @if (isSearching) { + Keine Ergebnisse für „{{ searchControl.value.trim() }}" gefunden. + } @else { + Keine Nachrichten gefunden. + } +
} diff --git a/webapp/src/app/modules/person-news/person-news.component.ts b/webapp/src/app/modules/person-news/person-news.component.ts index 7c69ef2c..230f51a2 100644 --- a/webapp/src/app/modules/person-news/person-news.component.ts +++ b/webapp/src/app/modules/person-news/person-news.component.ts @@ -20,6 +20,7 @@ import { MatTableModule } from '@angular/material/table'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatInputModule } from '@angular/material/input'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { debounceTime, distinctUntilChanged } from 'rxjs'; import { WorksService } from '../../api'; import { PaginationService } from '../../shared/services/pagination.service'; @@ -69,18 +70,33 @@ export class PersonNewsComponent implements OnInit { displayedColumns = ['maintitle', 'author', 'date']; private allArticles: NewsArticle[] = []; + private filteredArticles: NewsArticle[] = []; articles: NewsArticle[] = []; total = 0; loading = false; currentPageIndex = 0; sortOrder: 'desc' | 'asc' = 'desc'; + get isSearching(): boolean { + return this.searchControl.value.trim().length > 0; + } + ngOnInit(): void { this.route.parent?.paramMap .pipe(takeUntilDestroyed(this.destroyRef)) .subscribe(() => { this.load(); }); + + this.searchControl.valueChanges + .pipe( + debounceTime(300), + distinctUntilChanged(), + takeUntilDestroyed(this.destroyRef), + ) + .subscribe(() => { + this.applyFilter(); + }); } load(): void { @@ -96,9 +112,7 @@ export class PersonNewsComponent implements OnInit { .subscribe({ next: (page) => { this.allArticles = page.results ?? []; - this.total = this.allArticles.length; - this.currentPageIndex = 0; - this.updatePage(); + this.applyFilter(); this.loading = false; }, error: () => { @@ -135,9 +149,24 @@ export class PersonNewsComponent implements OnInit { this.load(); } + private applyFilter(): void { + const query = this.searchControl.value.trim().toLowerCase(); + this.filteredArticles = query + ? this.allArticles.filter( + (a) => + a.maintitle?.toLowerCase().includes(query) || + a.author?.toLowerCase().includes(query), + ) + : this.allArticles; + this.total = this.filteredArticles.length; + this.currentPageIndex = 0; + this.paginator?.firstPage(); + this.updatePage(); + } + private updatePage(): void { const start = this.currentPageIndex * this.paginationService.selection; - this.articles = this.allArticles.slice( + this.articles = this.filteredArticles.slice( start, start + this.paginationService.selection, ); From e9935207ea521ffbf4712bbc3dc7f673777b38bf Mon Sep 17 00:00:00 2001 From: Khuder Khalti Date: Wed, 17 Jun 2026 09:55:01 +0200 Subject: [PATCH 09/24] refactor: clean up patents module --- service/src/main/inse/config.py | 8 +- .../src/main/inse/patents/author_profile.py | 186 --------- .../src/main/inse/patents/disambiguation.py | 126 ------ .../inse/patents/elastic_search_client.py | 373 +++++------------- service/src/main/inse/patents/logic.py | 236 ++++++----- service/src/main/inse/patents/model.py | 34 -- service/src/main/inse/patents/pipeline.py | 209 ---------- service/src/main/inse/patents/repository.py | 182 --------- service/src/main/inse/patents/service.py | 59 +-- service/src/main/inse/patents/test_logic.py | 228 ----------- service/src/main/inse/schema.py | 47 +-- webapp/src/app/api/api/patents.service.ts | 45 --- .../person-patents.component.html | 37 +- .../person-patents.component.scss | 58 +-- .../person-patents.component.ts | 109 ++--- 15 files changed, 275 insertions(+), 1662 deletions(-) delete mode 100644 service/src/main/inse/patents/author_profile.py delete mode 100644 service/src/main/inse/patents/disambiguation.py delete mode 100644 service/src/main/inse/patents/pipeline.py delete mode 100644 service/src/main/inse/patents/repository.py delete 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 cbd9597b..32c57cb2 100644 --- a/service/src/main/inse/config.py +++ b/service/src/main/inse/config.py @@ -42,13 +42,7 @@ 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 llm_api_url: Optional[str] = None diff --git a/service/src/main/inse/patents/author_profile.py b/service/src/main/inse/patents/author_profile.py deleted file mode 100644 index 91819a64..00000000 --- a/service/src/main/inse/patents/author_profile.py +++ /dev/null @@ -1,186 +0,0 @@ -#!/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) - 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 - ] - 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, - ) - - -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_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 deleted file mode 100644 index 887f103c..00000000 --- a/service/src/main/inse/patents/disambiguation.py +++ /dev/null @@ -1,126 +0,0 @@ -#!/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 - - 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 5fb58366..ead988af 100644 --- a/service/src/main/inse/patents/elastic_search_client.py +++ b/service/src/main/inse/patents/elastic_search_client.py @@ -3,51 +3,15 @@ """ 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 @@ -74,129 +38,117 @@ class PatentSearchClient: "Content-Type": "application/json", } - 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": _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": { + 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. + """ + if first_name: + query = { "bool": { - "should": [ - {"term": {"doc_number": doc_number}}, - {"term": {"_id": patent_id}}, - ], - "minimum_should_match": 1, - }, - }, - } - - def uspto_query_by_patent_id(self, patent_id: str) -> dict[str, Any]: - publication_number = patent_id.removeprefix("US") - return { - "size": 1, - "track_total_hits": True, - "_source": _USPTO_SOURCE_FIELDS, - "query": { - "bool": { - "should": [ - {"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", + "must": [ + { + "match": { + "inventors_name_text": { + "query": last_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": { + "inventors_name_text": { + "query": first_name, + "operator": "and", + } + } + }, + ] + } + } + else: + query = { "match": { - text_field: { - "query": variant, + "inventors_name_text": { + "query": last_name, "operator": "and", - }, - }, - }) - - if profile.last_name: - should.append({"term": {keyword_field: profile.last_name}}) + } + } + } return { - "bool": { - "should": should, - "minimum_should_match": 1, - }, + "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": 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. + """ + if first_name: + query = { + "bool": { + "must": [ + { + "match": { + "inventors_names_text": { + "query": last_name, + "operator": "and", + } + } + }, + { + "match": { + "inventors_names_text": { + "query": first_name, + "operator": "and", + } + } + }, + ] + } + } + else: + query = { + "match": { + "inventors_names_text": { + "query": last_name, + "operator": "and", + } + } + } + + 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": query, } async def search_epo(self, payload: dict[str, Any]) -> dict[str, Any]: @@ -205,66 +157,6 @@ 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, @@ -277,57 +169,4 @@ class PatentSearchClient: json=payload, ) response.raise_for_status() - 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 + 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 index ecd75b2f..ff30648c 100644 --- a/service/src/main/inse/patents/logic.py +++ b/service/src/main/inse/patents/logic.py @@ -1,155 +1,147 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- """ - Business logic for patent matching by author. + Business logic for patent matching by author name. """ -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 . 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 +from .elastic_search_client import MissingApiKeyError +from .elastic_search_client import PatentSearchClient logger = logging.getLogger(__name__) async def get_patents_by_author_id( author_id: str, - db: Session, - *, - refresh: bool = False, client: PatentSearchClient | None = None, ) -> model.PatentsByAuthorResponse: - normalized_id = normalize_author_id(author_id) - build_meta = repository.get_build_meta(db, normalized_id) + search_client = client or PatentSearchClient() - 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 = _get_author(author_id) + if not author: + return model.PatentsByAuthorResponse( + author_id=author_id, + author_name=None, + patent_count=0, + patents=[], + ) - return load_author_patents(db, author_id) + 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=[], + ) -async def rebuild_patents_for_author( - author_id: str, - db: Session, - *, - client: PatentSearchClient | None = None, -) -> model.PatentsByAuthorResponse: try: - return await rebuild_author_patents(author_id, db, client=client) + epo_data, uspto_data = await _search_both_indices( + search_client, last_name, first_name + ) 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) -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".', - ) + # 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 - normalized_id = normalize_author_id(author_id) - patent: model.PatentEntry | None = None - - 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 - - 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"] - - repository.upsert_override( - db, - normalized_id, - patent_id, - action, - reason=request.reason, - patent=patent, - ) - db.commit() - - return model.PatentOverrideResponse( - author_id=normalized_id, - patent_id=patent_id, - action=action, - reason=request.reason, - patent=patent, + return model.PatentsByAuthorResponse( + author_id=author_id, + author_name=author_name, + patent_count=len(grouped), + patents=list(grouped.values()), ) -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 +async def _search_both_indices(client, last_name, first_name): + import asyncio + epo_result, uspto_result = await asyncio.gather( + client.search_epo(client.epo_query_by_inventor(last_name, first_name)), + client.search_uspto(client.uspto_query_by_inventor(last_name, first_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 \ No newline at end of file diff --git a/service/src/main/inse/patents/model.py b/service/src/main/inse/patents/model.py index 0246b2d4..31ebc18c 100644 --- a/service/src/main/inse/patents/model.py +++ b/service/src/main/inse/patents/model.py @@ -1,5 +1,3 @@ -from datetime import datetime - from pydantic import BaseModel, Field @@ -14,41 +12,9 @@ class PatentEntry(BaseModel): assignees: list[str] = Field(default_factory=list) ipc: list[str] = Field(default_factory=list) country: 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] - 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 deleted file mode 100644 index ee1d7492..00000000 --- a/service/src/main/inse/patents/pipeline.py +++ /dev/null @@ -1,209 +0,0 @@ -#!/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 deleted file mode 100644 index 5a049f54..00000000 --- a/service/src/main/inse/patents/repository.py +++ /dev/null @@ -1,182 +0,0 @@ -#!/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 2c41647e..53a27446 100644 --- a/service/src/main/inse/patents/service.py +++ b/service/src/main/inse/patents/service.py @@ -3,11 +3,7 @@ """ REST API for patent matching by author. """ -from fastapi import APIRouter, Depends, HTTPException, Query -from sqlalchemy.orm import Session -from starlette.status import HTTP_404_NOT_FOUND - -from .. import database +from fastapi import APIRouter from . import logic from . import model @@ -18,54 +14,7 @@ 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.", + summary="Get patents matched to an author by name.", ) -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.") +async def get_patents_by_author(author_id: str): + return await logic.get_patents_by_author_id(author_id) diff --git a/service/src/main/inse/patents/test_logic.py b/service/src/main/inse/patents/test_logic.py deleted file mode 100644 index 49a15ac1..00000000 --- a/service/src/main/inse/patents/test_logic.py +++ /dev/null @@ -1,228 +0,0 @@ -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 b1b59c1b..d03a1b33 100644 --- a/service/src/main/inse/schema.py +++ b/service/src/main/inse/schema.py @@ -4,9 +4,7 @@ This module defines the schema for the database used by the service using sql alchemy. """ -from datetime import datetime - -from sqlalchemy import DateTime, String, Text, UniqueConstraint +from sqlalchemy import String from sqlalchemy.orm import DeclarativeBase from sqlalchemy.orm import Mapped from sqlalchemy.orm import mapped_column @@ -24,46 +22,3 @@ 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 ab42b885..6a0e0b8a 100644 --- a/webapp/src/app/api/api/patents.service.ts +++ b/webapp/src/app/api/api/patents.service.ts @@ -33,20 +33,7 @@ export interface PatentEntry { ipc: string[]; country: 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 { @@ -54,16 +41,12 @@ export interface PatentsByAuthorResponse { author_name: string | null; patent_count: number; patents: PatentEntry[]; - from_cache?: boolean; - last_built_at?: string | null; - search_meta?: PatentSearchMeta | null; } type GetPatentsByAuthorOptions = { httpHeaderAccept?: 'application/json'; context?: HttpContext; transferCache?: boolean; - refresh?: boolean; }; @Injectable({ @@ -155,18 +138,12 @@ 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, @@ -178,26 +155,4 @@ 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 841c1ba1..03370197 100644 --- a/webapp/src/app/modules/person-patents/person-patents.component.html +++ b/webapp/src/app/modules/person-patents/person-patents.component.html @@ -20,29 +20,23 @@ {{ getUsptoCount() }} USPTO

-
-
+
+ +
-
- 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[] { From 379f94ddc7d81b684d9b3920d0d213685b1f5a09 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Wed, 17 Jun 2026 13:06:41 +0200 Subject: [PATCH 10/24] feat(backend/news): combine data from aktuell_postproc with news model --- service/src/main/inse/news/logic.py | 28 ++++++++++++++++++++++++++++ service/src/main/inse/news/model.py | 2 ++ 2 files changed, 30 insertions(+) diff --git a/service/src/main/inse/news/logic.py b/service/src/main/inse/news/logic.py index 46866d0b..aad2e896 100644 --- a/service/src/main/inse/news/logic.py +++ b/service/src/main/inse/news/logic.py @@ -60,6 +60,8 @@ def get_news_by_id(news_id: str) -> NewsArticleDetail: source = response.get("_source", {}) + relevant, authors = _get_postproc_labels(news_id) + return NewsArticleDetail( id=response.get("_id"), date=source.get("date"), @@ -67,9 +69,35 @@ def get_news_by_id(news_id: str) -> NewsArticleDetail: author=source.get("author"), url=source.get("url"), full_content=source.get("full_content"), + relevant=relevant, + authors=authors, ) +def _get_postproc_labels(news_id: str) -> tuple[bool, list]: + try: + response = elasticsearch.search( + index="aktuell_postproc", + query={"term": {"news_id.keyword": news_id}}, + source=["relevant", "authors"], + size=1, + cluster="inse", + ) + except Exception: + logger.exception(f"Postproc-Lookup for {news_id} failed.") + return False, [] + + hits = response.get("hits", {}).get("hits", []) + if not hits: + return False, [] + + postproc_source = hits[0].get("_source", {}) + relevant = bool(postproc_source.get("relevant", 0)) + authors = postproc_source.get("authors") or [] + + return relevant, authors + + def _run_search(query: dict, source: list, size: int, offset: int, sort) -> dict: try: return elasticsearch.search( diff --git a/service/src/main/inse/news/model.py b/service/src/main/inse/news/model.py index 1fee0b8f..74a37542 100644 --- a/service/src/main/inse/news/model.py +++ b/service/src/main/inse/news/model.py @@ -16,6 +16,8 @@ class NewsArticle(BaseModel): class NewsArticleDetail(NewsArticle): full_content: Optional[str] = None + relevant: bool = False + authors: List[str] = [] class NewsPage(BaseModel): From 23da3e44ba8b4b876d8df02682c70ef722b2d4c3 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Wed, 17 Jun 2026 13:08:46 +0200 Subject: [PATCH 11/24] feat(frontend/news_aritcle): show extracted authors --- .../modules/news-detail/news-detail.component.html | 14 +++++++++----- .../modules/news-detail/news-detail.component.ts | 8 ++------ 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/webapp/src/app/modules/news-detail/news-detail.component.html b/webapp/src/app/modules/news-detail/news-detail.component.html index 6e930151..38ece59d 100644 --- a/webapp/src/app/modules/news-detail/news-detail.component.html +++ b/webapp/src/app/modules/news-detail/news-detail.component.html @@ -64,11 +64,15 @@ Erwähnte Personen
- @for (person of mentionedPersons; track person) { -
-
{{ person.charAt(0) }}
- {{ person }} -
+ @if (article.authors && article.authors.length) { + @for (person of article.authors; track person) { +
+
{{ person.charAt(0) }}
+ {{ person }} +
+ } + } @else { +

Keine erwähnten Personen gefunden.

}
diff --git a/webapp/src/app/modules/news-detail/news-detail.component.ts b/webapp/src/app/modules/news-detail/news-detail.component.ts index 3bbca4d1..5c51b52c 100644 --- a/webapp/src/app/modules/news-detail/news-detail.component.ts +++ b/webapp/src/app/modules/news-detail/news-detail.component.ts @@ -16,6 +16,8 @@ interface NewsArticleDetail { author?: string | null; url?: string | null; full_content?: string | null; + relevant?: boolean; + authors?: string[]; } @Component({ @@ -41,12 +43,6 @@ export class NewsDetailComponent implements OnInit { loading = false; notFound = false; - readonly mentionedPersons = [ - 'Prof. Dr. Anna Müller', - 'Dr. Hans Schmidt', - 'Dr. Lena Weber', - ]; - readonly relevantTopics = [ 'Künstliche Intelligenz', 'Maschinelles Lernen', From b6618e030e3e77ab3023def950ddee34ee2bc1b7 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Wed, 17 Jun 2026 13:18:08 +0200 Subject: [PATCH 12/24] feat: add info about article relevance to the news page --- service/src/main/inse/news/logic.py | 6 ++-- service/src/main/inse/news/model.py | 2 +- .../news-detail/news-detail.component.html | 17 +++++++++ .../news-detail/news-detail.component.scss | 35 +++++++++++++++++++ 4 files changed, 56 insertions(+), 4 deletions(-) diff --git a/service/src/main/inse/news/logic.py b/service/src/main/inse/news/logic.py index aad2e896..06334728 100644 --- a/service/src/main/inse/news/logic.py +++ b/service/src/main/inse/news/logic.py @@ -74,7 +74,7 @@ def get_news_by_id(news_id: str) -> NewsArticleDetail: ) -def _get_postproc_labels(news_id: str) -> tuple[bool, list]: +def _get_postproc_labels(news_id: str) -> tuple[bool | None, list]: try: response = elasticsearch.search( index="aktuell_postproc", @@ -85,11 +85,11 @@ def _get_postproc_labels(news_id: str) -> tuple[bool, list]: ) except Exception: logger.exception(f"Postproc-Lookup for {news_id} failed.") - return False, [] + return None, [] hits = response.get("hits", {}).get("hits", []) if not hits: - return False, [] + return None, [] postproc_source = hits[0].get("_source", {}) relevant = bool(postproc_source.get("relevant", 0)) diff --git a/service/src/main/inse/news/model.py b/service/src/main/inse/news/model.py index 74a37542..ad34577f 100644 --- a/service/src/main/inse/news/model.py +++ b/service/src/main/inse/news/model.py @@ -16,7 +16,7 @@ class NewsArticle(BaseModel): class NewsArticleDetail(NewsArticle): full_content: Optional[str] = None - relevant: bool = False + relevant: Optional[bool] = None authors: List[str] = [] diff --git a/webapp/src/app/modules/news-detail/news-detail.component.html b/webapp/src/app/modules/news-detail/news-detail.component.html index 38ece59d..ce499e8d 100644 --- a/webapp/src/app/modules/news-detail/news-detail.component.html +++ b/webapp/src/app/modules/news-detail/news-detail.component.html @@ -33,6 +33,23 @@ }

{{ article.maintitle || 'Kein Titel' }}

+ + @if (article.relevant === true) { + + check_circle + Relevant + + } @else if (article.relevant === false) { + + cancel + Nicht relevant + + } @else { + + help + Relevanz nicht bestimmt + + }
diff --git a/webapp/src/app/modules/news-detail/news-detail.component.scss b/webapp/src/app/modules/news-detail/news-detail.component.scss index 71b7519e..02101fda 100644 --- a/webapp/src/app/modules/news-detail/news-detail.component.scss +++ b/webapp/src/app/modules/news-detail/news-detail.component.scss @@ -87,6 +87,41 @@ main { line-height: 1.3; } +.relevance-badge { + display: inline-flex; + align-items: center; + gap: 6px; + margin-top: 14px; + padding: 5px 12px; + border-radius: 999px; + font-size: 13px; + font-weight: 600; + + mat-icon { + font-size: 16px; + width: 16px; + height: 16px; + } + + &.is-relevant { + background: #effaf3; + border: 1px solid #bdebcf; + color: #24834f; + } + + &.not-relevant { + background: var(--sg-surface-muted); + border: 1px solid #e2e2e2; + color: var(--sg-text-muted); + } + + &.undetermined { + background: #fff7e8; + border: 1px solid #ffd796; + color: #c67500; + } +} + .article-body { font-size: 15px; line-height: 1.7; From 11d20546b1631a506511634926c1df21d922abf2 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Wed, 17 Jun 2026 20:15:16 +0200 Subject: [PATCH 13/24] WIP: show news in author overview --- service/src/main/inse/news/logic.py | 61 ++++++++ service/src/main/inse/news/service.py | 28 ++++ .../person-news/person-news.component.ts | 142 ++++++++++++------ 3 files changed, 189 insertions(+), 42 deletions(-) diff --git a/service/src/main/inse/news/logic.py b/service/src/main/inse/news/logic.py index 06334728..526510de 100644 --- a/service/src/main/inse/news/logic.py +++ b/service/src/main/inse/news/logic.py @@ -10,6 +10,7 @@ from fastapi import HTTPException from starlette.status import HTTP_500_INTERNAL_SERVER_ERROR from ..integrations import elasticsearch +from ..persons.logic import get_author_name_by_id from .model import NewsArticle, NewsArticleDetail, NewsPage logger = logging.getLogger(__name__) @@ -42,6 +43,66 @@ def search_news(query_text: str, page: int, page_size: int) -> NewsPage: return _build_page(response, page, page_size) +def get_news_by_author( + author_id: str, + page: int = 1, + page_size: int = 10, + sort_order: str = "desc", + query_text: str | None = None, +) -> NewsPage: + + author_name = get_author_name_by_id(author_id) + if not author_name: + return _empty_page(page, page_size) + + news_ids = _find_news_ids_for_author(author_name) + if not news_ids: + return _empty_page(page, page_size) + + es_query = {"bool": {"filter": [{"ids": {"values": news_ids}}]}} + if query_text: + es_query["bool"]["must"] = [ + {"multi_match": {"query": query_text, "fields": ["maintitle", "author"]}} + ] + + offset = (page - 1) * page_size + response = _run_search( + query=es_query, + source=["date", "maintitle", "author", "url"], + size=page_size, + offset=offset, + sort=[{"date_full": sort_order}], + ) + + return _build_page(response, page, page_size) + + +def _find_news_ids_for_author(author_name: str) -> list: + + try: + response = elasticsearch.search( + index="aktuell_postproc", + query={"term": {"authors.keyword": author_name}}, + source=["news_id"], + size=1000, + cluster="inse", + ) + except Exception: + logger.exception(f"Postproc-search: Finding news IDs for author '{author_name}' failed.") + return [] + + news_ids = [] + for hit in response.get("hits", {}).get("hits", []): + news_id = hit.get("_source", {}).get("news_id") + if news_id: + news_ids.append(news_id) + + return news_ids + + +def _empty_page(page: int = 1, page_size: int = 0) -> NewsPage: + return NewsPage(total=0, page=page, page_size=page_size, results=[]) + def get_news_by_id(news_id: str) -> NewsArticleDetail: try: diff --git a/service/src/main/inse/news/service.py b/service/src/main/inse/news/service.py index 0ed5fe6d..5bb5dc03 100644 --- a/service/src/main/inse/news/service.py +++ b/service/src/main/inse/news/service.py @@ -61,6 +61,34 @@ def search_news( return logic.search_news(query, page, page_size) +@router.get( + "/by-author", + operation_id="getNewsByAuthor", + response_model=NewsPage, + response_model_exclude_none=True, + summary="Returns news articles in which the given person is mentioned.", + tags=[Tags.NEWS], +) +def get_news_by_author( + author_id: Annotated[ + str, Query(alias="authorId", description="OpenAlex author id, e.g. A5034365278.") + ], + page: Annotated[ + int, Query(description="Page number (1-based).", ge=1) + ] = 1, + page_size: Annotated[ + int, Query(alias="pageSize", description="Articles per page.", ge=1, le=100) + ] = 10, + sort_order: Annotated[ + str, Query(alias="sortOrder", description="Sort order: 'desc' (newest first) or 'asc' (oldest first).", pattern="^(asc|desc)$") + ] = "desc", + query: Annotated[ + str | None, Query(description="Optional search term, matched against title/author.") + ] = None, +): + return logic.get_news_by_author(author_id, page, page_size, sort_order, query) + + @router.get( "/{news_id}", operation_id="getNewsById", diff --git a/webapp/src/app/modules/person-news/person-news.component.ts b/webapp/src/app/modules/person-news/person-news.component.ts index 230f51a2..f33bf1e8 100644 --- a/webapp/src/app/modules/person-news/person-news.component.ts +++ b/webapp/src/app/modules/person-news/person-news.component.ts @@ -7,7 +7,7 @@ import { } from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http'; import { FormControl, ReactiveFormsModule } from '@angular/forms'; -import { ActivatedRoute, RouterLink } from '@angular/router'; +import { ActivatedRoute, ParamMap, Router, RouterLink } from '@angular/router'; import { MatIconModule } from '@angular/material/icon'; import { MatSelectModule } from '@angular/material/select'; import { @@ -20,7 +20,7 @@ import { MatTableModule } from '@angular/material/table'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatInputModule } from '@angular/material/input'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; -import { debounceTime, distinctUntilChanged } from 'rxjs'; +import { combineLatest, debounceTime, distinctUntilChanged } from 'rxjs'; import { WorksService } from '../../api'; import { PaginationService } from '../../shared/services/pagination.service'; @@ -40,7 +40,12 @@ interface NewsPage { results: NewsArticle[]; } -const ARTICLE_CAP = 100; +interface NewsQueryState { + pageIndex: number; + pageSize: number; + sortOrder: 'desc' | 'asc'; + query: string; +} @Component({ selector: 'app-person-news', @@ -62,6 +67,7 @@ export class PersonNewsComponent implements OnInit { @ViewChild(MatPaginator) paginator?: MatPaginator; private readonly destroyRef = inject(DestroyRef); private readonly route = inject(ActivatedRoute); + private readonly router = inject(Router); private readonly httpClient = inject(HttpClient); private readonly worksService = inject(WorksService); readonly paginationService = inject(PaginationService); @@ -69,23 +75,35 @@ export class PersonNewsComponent implements OnInit { readonly searchControl = new FormControl('', { nonNullable: true }); displayedColumns = ['maintitle', 'author', 'date']; - private allArticles: NewsArticle[] = []; - private filteredArticles: NewsArticle[] = []; + private authorId: string | null = null; articles: NewsArticle[] = []; total = 0; loading = false; currentPageIndex = 0; sortOrder: 'desc' | 'asc' = 'desc'; + private readonly queryParamKeys = { + page: 'newsPage', + pageSize: 'newsPageSize', + sort: 'newsSort', + query: 'newsQuery', + } as const; + get isSearching(): boolean { return this.searchControl.value.trim().length > 0; } ngOnInit(): void { - this.route.parent?.paramMap + const parentParamMap = this.route.parent?.paramMap; + if (!parentParamMap) return; + + combineLatest([parentParamMap, this.route.queryParamMap]) .pipe(takeUntilDestroyed(this.destroyRef)) - .subscribe(() => { - this.load(); + .subscribe(([params, queryParams]) => { + this.authorId = params.get('id'); + const state = this.parseQueryParams(queryParams); + this.applyState(state); + this.load(state); }); this.searchControl.valueChanges @@ -94,28 +112,42 @@ export class PersonNewsComponent implements OnInit { distinctUntilChanged(), takeUntilDestroyed(this.destroyRef), ) - .subscribe(() => { - this.applyFilter(); + .subscribe((value) => { + this.updateQueryParams({ + [this.queryParamKeys.query]: value.trim() || null, + [this.queryParamKeys.page]: 1, + }); }); } - load(): void { + load(state: NewsQueryState): void { + if (!this.authorId) { + return; + } + this.loading = true; - const params = new HttpParams() - .set('page', 1) - .set('pageSize', ARTICLE_CAP) - .set('sortOrder', this.sortOrder); + let params = new HttpParams() + .set('authorId', this.authorId) + .set('page', state.pageIndex + 1) + .set('pageSize', state.pageSize) + .set('sortOrder', state.sortOrder); + + if (state.query) { + params = params.set('query', state.query); + } const basePath = this.worksService.configuration.basePath ?? ''; this.httpClient - .get(`${basePath}/api/news`, { params }) + .get(`${basePath}/api/news/by-author`, { params }) .subscribe({ next: (page) => { - this.allArticles = page.results ?? []; - this.applyFilter(); + this.articles = page.results ?? []; + this.total = page.total ?? 0; this.loading = false; }, error: () => { + this.articles = []; + this.total = 0; this.loading = false; }, }); @@ -123,8 +155,17 @@ export class PersonNewsComponent implements OnInit { onPage(event: PageEvent): void { this.paginationService.selection = event.pageSize; - this.currentPageIndex = event.pageIndex; - this.updatePage(); + this.updateQueryParams({ + [this.queryParamKeys.page]: event.pageIndex + 1, + [this.queryParamKeys.pageSize]: event.pageSize, + }); + } + + onSortChange(order: 'desc' | 'asc'): void { + this.updateQueryParams({ + [this.queryParamKeys.sort]: order, + [this.queryParamKeys.page]: 1, + }); } formatDate(dateStr?: string | null): string { @@ -144,31 +185,48 @@ export class PersonNewsComponent implements OnInit { return `Zeige ${start} bis ${end} von ${this.total} Nachrichten`; } - onSortChange(order: 'desc' | 'asc'): void { - this.sortOrder = order; - this.load(); + private updateQueryParams( + overrides: Record, + ): void { + void this.router.navigate([], { + relativeTo: this.route, + queryParams: overrides, + queryParamsHandling: 'merge', + }); } - private applyFilter(): void { - const query = this.searchControl.value.trim().toLowerCase(); - this.filteredArticles = query - ? this.allArticles.filter( - (a) => - a.maintitle?.toLowerCase().includes(query) || - a.author?.toLowerCase().includes(query), - ) - : this.allArticles; - this.total = this.filteredArticles.length; - this.currentPageIndex = 0; - this.paginator?.firstPage(); - this.updatePage(); + private parseQueryParams(queryParams: ParamMap): NewsQueryState { + const sortParam = queryParams.get(this.queryParamKeys.sort); + const sortOrder: 'desc' | 'asc' = sortParam === 'asc' ? 'asc' : 'desc'; + + return { + pageIndex: + this.parsePositiveInteger( + queryParams.get(this.queryParamKeys.page), + 1, + ) - 1, + pageSize: this.parsePositiveInteger( + queryParams.get(this.queryParamKeys.pageSize), + this.paginationService.selection, + ), + sortOrder, + query: (queryParams.get(this.queryParamKeys.query) ?? '').trim(), + }; } - private updatePage(): void { - const start = this.currentPageIndex * this.paginationService.selection; - this.articles = this.filteredArticles.slice( - start, - start + this.paginationService.selection, - ); + private applyState(state: NewsQueryState): void { + this.currentPageIndex = state.pageIndex; + this.paginationService.selection = state.pageSize; + this.sortOrder = state.sortOrder; + this.searchControl.setValue(state.query, { emitEvent: false }); + } + + private parsePositiveInteger(value: string | null, fallback: number): number { + const parsedValue = Number(value); + if (!Number.isInteger(parsedValue) || parsedValue < 1) { + return fallback; + } + + return parsedValue; } } From dc2ef6fd203aff0438cc5a15eff3f76d54c36344 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Wed, 17 Jun 2026 20:26:51 +0200 Subject: [PATCH 14/24] refactor person news to load via resolver --- webapp/src/app/app.routes.ts | 11 ++ .../person-news/person-news.component.ts | 171 ++++-------------- .../src/app/resolvers/person-news.resolver.ts | 57 ++++++ 3 files changed, 107 insertions(+), 132 deletions(-) create mode 100644 webapp/src/app/resolvers/person-news.resolver.ts diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 068e2080..56278534 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -8,6 +8,7 @@ import { institutionResolver } from './resolvers/institution.resolver'; import { bundProjectsResolver } from './resolvers/bund-projects.resolver'; import { euProjectsResolver } from './resolvers/eu-projects.resolver'; import { dfgProjectsResolver } from './resolvers/dfg-projects.resolver'; +import { personNewsResolver } from './resolvers/person-news.resolver'; export const routes: Routes = [ { path: '', @@ -188,6 +189,16 @@ export const routes: Routes = [ import('./modules/person-news/person-news.component').then( (mod) => mod.PersonNewsComponent, ), + resolve: { + newsPage: personNewsResolver, + }, + runGuardsAndResolvers: (from, to) => { + const keys = ['page', 'pageSize', 'sortOrder', 'query']; + + return keys.some( + (key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key), + ); + }, }, ], }, diff --git a/webapp/src/app/modules/person-news/person-news.component.ts b/webapp/src/app/modules/person-news/person-news.component.ts index f33bf1e8..b0e6356b 100644 --- a/webapp/src/app/modules/person-news/person-news.component.ts +++ b/webapp/src/app/modules/person-news/person-news.component.ts @@ -1,51 +1,19 @@ -import { - Component, - DestroyRef, - OnInit, - ViewChild, - inject, -} from '@angular/core'; -import { HttpClient, HttpParams } from '@angular/common/http'; +import { Component, DestroyRef, OnInit, inject } from '@angular/core'; import { FormControl, ReactiveFormsModule } from '@angular/forms'; -import { ActivatedRoute, ParamMap, Router, RouterLink } from '@angular/router'; +import { ActivatedRoute, Router, RouterLink } from '@angular/router'; import { MatIconModule } from '@angular/material/icon'; import { MatSelectModule } from '@angular/material/select'; -import { - MatPaginator, - MatPaginatorModule, - PageEvent, -} from '@angular/material/paginator'; +import { MatPaginatorModule, PageEvent } from '@angular/material/paginator'; import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; import { MatTableModule } from '@angular/material/table'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatInputModule } from '@angular/material/input'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; -import { combineLatest, debounceTime, distinctUntilChanged } from 'rxjs'; +import { debounceTime, distinctUntilChanged } from 'rxjs'; -import { WorksService } from '../../api'; import { PaginationService } from '../../shared/services/pagination.service'; - -interface NewsArticle { - id: string; - date?: string | null; - maintitle?: string | null; - author?: string | null; - url?: string | null; -} - -interface NewsPage { - total: number; - page: number; - page_size: number; - results: NewsArticle[]; -} - -interface NewsQueryState { - pageIndex: number; - pageSize: number; - sortOrder: 'desc' | 'asc'; - query: string; -} +import { ResolverStateService } from '../../shared/services/resolver-state.service'; +import { NewsArticle, NewsPage } from '../../resolvers/person-news.resolver'; @Component({ selector: 'app-person-news', @@ -64,46 +32,53 @@ interface NewsQueryState { styleUrl: './person-news.component.scss', }) export class PersonNewsComponent implements OnInit { - @ViewChild(MatPaginator) paginator?: MatPaginator; private readonly destroyRef = inject(DestroyRef); private readonly route = inject(ActivatedRoute); private readonly router = inject(Router); - private readonly httpClient = inject(HttpClient); - private readonly worksService = inject(WorksService); readonly paginationService = inject(PaginationService); + private readonly resolverStateService = inject(ResolverStateService); readonly searchControl = new FormControl('', { nonNullable: true }); displayedColumns = ['maintitle', 'author', 'date']; - private authorId: string | null = null; articles: NewsArticle[] = []; total = 0; - loading = false; currentPageIndex = 0; sortOrder: 'desc' | 'asc' = 'desc'; - private readonly queryParamKeys = { - page: 'newsPage', - pageSize: 'newsPageSize', - sort: 'newsSort', - query: 'newsQuery', - } as const; + get loading(): boolean { + return this.resolverStateService.isResolving(); + } get isSearching(): boolean { return this.searchControl.value.trim().length > 0; } ngOnInit(): void { - const parentParamMap = this.route.parent?.paramMap; - if (!parentParamMap) return; - - combineLatest([parentParamMap, this.route.queryParamMap]) + this.route.data .pipe(takeUntilDestroyed(this.destroyRef)) - .subscribe(([params, queryParams]) => { - this.authorId = params.get('id'); - const state = this.parseQueryParams(queryParams); - this.applyState(state); - this.load(state); + .subscribe(({ newsPage }) => { + const page = newsPage as NewsPage; + this.articles = page.results ?? []; + this.total = page.total ?? 0; + }); + + this.route.queryParamMap + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe((params) => { + const page = params.get('page') + ? Number.parseInt(params.get('page')!, 10) + : 1; + const pageSize = params.get('pageSize') + ? Number.parseInt(params.get('pageSize')!, 10) + : 10; + const sortOrder = params.get('sortOrder'); + const query = params.get('query') ?? ''; + + this.currentPageIndex = page - 1; + this.paginationService.selection = pageSize; + this.sortOrder = sortOrder === 'asc' ? 'asc' : 'desc'; + this.searchControl.setValue(query, { emitEvent: false }); }); this.searchControl.valueChanges @@ -114,57 +89,24 @@ export class PersonNewsComponent implements OnInit { ) .subscribe((value) => { this.updateQueryParams({ - [this.queryParamKeys.query]: value.trim() || null, - [this.queryParamKeys.page]: 1, + query: value.trim() || null, + page: 1, }); }); } - load(state: NewsQueryState): void { - if (!this.authorId) { - return; - } - - this.loading = true; - let params = new HttpParams() - .set('authorId', this.authorId) - .set('page', state.pageIndex + 1) - .set('pageSize', state.pageSize) - .set('sortOrder', state.sortOrder); - - if (state.query) { - params = params.set('query', state.query); - } - - const basePath = this.worksService.configuration.basePath ?? ''; - this.httpClient - .get(`${basePath}/api/news/by-author`, { params }) - .subscribe({ - next: (page) => { - this.articles = page.results ?? []; - this.total = page.total ?? 0; - this.loading = false; - }, - error: () => { - this.articles = []; - this.total = 0; - this.loading = false; - }, - }); - } - onPage(event: PageEvent): void { this.paginationService.selection = event.pageSize; this.updateQueryParams({ - [this.queryParamKeys.page]: event.pageIndex + 1, - [this.queryParamKeys.pageSize]: event.pageSize, + page: event.pageIndex + 1, + pageSize: event.pageSize, }); } onSortChange(order: 'desc' | 'asc'): void { this.updateQueryParams({ - [this.queryParamKeys.sort]: order, - [this.queryParamKeys.page]: 1, + sortOrder: order, + page: 1, }); } @@ -194,39 +136,4 @@ export class PersonNewsComponent implements OnInit { queryParamsHandling: 'merge', }); } - - private parseQueryParams(queryParams: ParamMap): NewsQueryState { - const sortParam = queryParams.get(this.queryParamKeys.sort); - const sortOrder: 'desc' | 'asc' = sortParam === 'asc' ? 'asc' : 'desc'; - - return { - pageIndex: - this.parsePositiveInteger( - queryParams.get(this.queryParamKeys.page), - 1, - ) - 1, - pageSize: this.parsePositiveInteger( - queryParams.get(this.queryParamKeys.pageSize), - this.paginationService.selection, - ), - sortOrder, - query: (queryParams.get(this.queryParamKeys.query) ?? '').trim(), - }; - } - - private applyState(state: NewsQueryState): void { - this.currentPageIndex = state.pageIndex; - this.paginationService.selection = state.pageSize; - this.sortOrder = state.sortOrder; - this.searchControl.setValue(state.query, { emitEvent: false }); - } - - private parsePositiveInteger(value: string | null, fallback: number): number { - const parsedValue = Number(value); - if (!Number.isInteger(parsedValue) || parsedValue < 1) { - return fallback; - } - - return parsedValue; - } } diff --git a/webapp/src/app/resolvers/person-news.resolver.ts b/webapp/src/app/resolvers/person-news.resolver.ts new file mode 100644 index 00000000..9d361534 --- /dev/null +++ b/webapp/src/app/resolvers/person-news.resolver.ts @@ -0,0 +1,57 @@ +import { ResolveFn } from '@angular/router'; +import { inject } from '@angular/core'; +import { HttpClient, HttpParams } from '@angular/common/http'; +import { of } from 'rxjs'; + +import { WorksService } from '../api'; + +export interface NewsArticle { + id: string; + date?: string | null; + maintitle?: string | null; + author?: string | null; + url?: string | null; +} + +export interface NewsPage { + total: number; + page: number; + page_size: number; + results: NewsArticle[]; +} + +export const personNewsResolver: ResolveFn = (route) => { + const httpClient = inject(HttpClient); + const worksService = inject(WorksService); + + const authorId = route.parent?.paramMap.get('id'); + if (!authorId) { + return of({ total: 0, page: 1, page_size: 0, results: [] }); + } + + const queryParams = route.queryParamMap; + + const page = queryParams.get('page') + ? Number.parseInt(queryParams.get('page')!, 10) + : 1; + + const pageSize = queryParams.get('pageSize') + ? Number.parseInt(queryParams.get('pageSize')!, 10) + : 10; + + const sortOrder = queryParams.get('sortOrder') || 'desc'; + const query = queryParams.get('query') || ''; + + let params = new HttpParams() + .set('authorId', authorId) + .set('page', page) + .set('pageSize', pageSize) + .set('sortOrder', sortOrder); + + if (query) { + params = params.set('query', query); + } + + const basePath = worksService.configuration.basePath ?? ''; + return httpClient.get(`${basePath}/api/news/by-author`, { params }); +}; From c211e8d210d7ee209a5071461b52e151250e86ec Mon Sep 17 00:00:00 2001 From: taguesokoudjou Date: Fri, 19 Jun 2026 17:02:31 +0200 Subject: [PATCH 15/24] 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 + From fc9c18f9655d0610982cc9da9f8832c8aa2ecbbb Mon Sep 17 00:00:00 2001 From: Khuder Khalti Date: Fri, 19 Jun 2026 22:05:47 +0200 Subject: [PATCH 16/24] 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' }); }); } From 0cdacf20f75157b531902f37df0cb95d88081fff Mon Sep 17 00:00:00 2001 From: Khuder Khalti Date: Fri, 19 Jun 2026 22:37:51 +0200 Subject: [PATCH 17/24] 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 From 08cfec6be018da900b1de98ef93e9a3b8d51b0b3 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sat, 20 Jun 2026 15:15:23 +0200 Subject: [PATCH 18/24] Replace author with "Relevant" label in news list --- service/src/main/inse/news/logic.py | 41 ++++++++++++++++++- service/src/main/inse/news/model.py | 1 + .../src/app/modules/news/news.component.html | 21 ++++++++-- .../src/app/modules/news/news.component.scss | 36 ++++++++++++++++ webapp/src/app/modules/news/news.component.ts | 3 +- 5 files changed, 96 insertions(+), 6 deletions(-) diff --git a/service/src/main/inse/news/logic.py b/service/src/main/inse/news/logic.py index 526510de..f5599ddf 100644 --- a/service/src/main/inse/news/logic.py +++ b/service/src/main/inse/news/logic.py @@ -182,10 +182,21 @@ def _run_search(query: dict, source: list, size: int, offset: int, sort) -> dict def _build_page(response: dict, page: int, page_size: int) -> NewsPage: hits_section = response.get("hits", {}) total = hits_section.get("total", {}).get("value", 0) + hits = hits_section.get("hits", []) + + news_ids = [] + for hit in hits: + news_id = hit.get("_id") + if news_id: + news_ids.append(news_id) + + relevance_map = _get_relevance_map(news_ids) articles = [] - for hit in hits_section.get("hits", []): - articles.append(_parse_hit(hit)) + for hit in hits: + article = _parse_hit(hit) + article.relevant = relevance_map.get(article.id) + articles.append(article) return NewsPage( total=total, @@ -195,6 +206,32 @@ def _build_page(response: dict, page: int, page_size: int) -> NewsPage: ) +def _get_relevance_map(news_ids: list) -> dict: + if not news_ids: + return {} + + try: + response = elasticsearch.search( + index="aktuell_postproc", + query={"terms": {"news_id.keyword": news_ids}}, + source=["news_id", "relevant"], + size=len(news_ids), + cluster="inse", + ) + except Exception: + logger.exception("Postproc-Relevanz-Lookup fehlgeschlagen.") + return {} + + relevance_map = {} + for hit in response.get("hits", {}).get("hits", []): + postproc_source = hit.get("_source", {}) + news_id = postproc_source.get("news_id") + if news_id is not None: + relevance_map[news_id] = bool(postproc_source.get("relevant", 0)) + + return relevance_map + + def _parse_hit(hit: dict) -> NewsArticle: source = hit.get("_source", {}) diff --git a/service/src/main/inse/news/model.py b/service/src/main/inse/news/model.py index ad34577f..83b593b3 100644 --- a/service/src/main/inse/news/model.py +++ b/service/src/main/inse/news/model.py @@ -12,6 +12,7 @@ class NewsArticle(BaseModel): maintitle: Optional[str] = None author: Optional[str] = None url: Optional[str] = None + relevant: Optional[bool] = None class NewsArticleDetail(NewsArticle): diff --git a/webapp/src/app/modules/news/news.component.html b/webapp/src/app/modules/news/news.component.html index 05ca40a8..bfd8cba1 100644 --- a/webapp/src/app/modules/news/news.component.html +++ b/webapp/src/app/modules/news/news.component.html @@ -42,10 +42,25 @@ - - Autor + + Relevanz - {{ article.author || '-' }} + @if (article.relevant === true) { + + check_circle + Relevant + + } @else if (article.relevant === false) { + + cancel + Nicht relevant + + } @else { + + help + Nicht bestimmt + + } diff --git a/webapp/src/app/modules/news/news.component.scss b/webapp/src/app/modules/news/news.component.scss index 68a1899f..def9857d 100644 --- a/webapp/src/app/modules/news/news.component.scss +++ b/webapp/src/app/modules/news/news.component.scss @@ -114,6 +114,42 @@ table { background: transparent; } +.relevance-badge { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 5px 12px; + border-radius: 999px; + font-size: 13px; + font-weight: 600; + line-height: 1; + white-space: nowrap; + + mat-icon { + font-size: 16px; + width: 16px; + height: 16px; + } + + &.is-relevant { + background: #effaf3; + border: 1px solid #bdebcf; + color: #24834f; + } + + &.not-relevant { + background: var(--sg-surface-muted); + border: 1px solid #e2e2e2; + color: var(--sg-text-muted); + } + + &.undetermined { + background: #fff7e8; + border: 1px solid #ffd796; + color: #c67500; + } +} + ::ng-deep .mat-mdc-header-cell { color: var(--sg-text-muted); font-size: 12px; diff --git a/webapp/src/app/modules/news/news.component.ts b/webapp/src/app/modules/news/news.component.ts index e6990dbb..89a3d1e4 100644 --- a/webapp/src/app/modules/news/news.component.ts +++ b/webapp/src/app/modules/news/news.component.ts @@ -21,6 +21,7 @@ interface NewsArticle { maintitle?: string | null; author?: string | null; url?: string | null; + relevant?: boolean | null; } interface NewsPage { @@ -59,7 +60,7 @@ export class NewsComponent implements OnInit { readonly searchControl = new FormControl('', { nonNullable: true }); - displayedColumns = ['maintitle', 'author', 'date']; + displayedColumns = ['maintitle', 'relevance', 'date']; articles: NewsArticle[] = []; total = 0; loading = false; From 9dadc1f12f3b923ae103b27890a93f45ea2f3671 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sat, 20 Jun 2026 15:33:16 +0200 Subject: [PATCH 19/24] extends es-client with highlighting --- service/src/main/inse/integrations/elasticsearch.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/service/src/main/inse/integrations/elasticsearch.py b/service/src/main/inse/integrations/elasticsearch.py index 870d833f..f1b405ba 100644 --- a/service/src/main/inse/integrations/elasticsearch.py +++ b/service/src/main/inse/integrations/elasticsearch.py @@ -24,6 +24,7 @@ def search( sort: list = None, body: dict = None, track_total_hits = False, + highlight: dict = None, cluster: str = "nes", ) -> dict[str, Any]: @@ -48,6 +49,8 @@ def search( payload["sort"] = sort if track_total_hits: payload["track_total_hits"] = True + if highlight is not None: + payload["highlight"] = highlight else: payload = { "query": { From db5156a02d91eb3618398063f7c304f42784bb97 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sat, 20 Jun 2026 15:39:06 +0200 Subject: [PATCH 20/24] feat: display search findings directly in news --- service/src/main/inse/news/logic.py | 17 +++++++++++++++-- service/src/main/inse/news/model.py | 1 + webapp/src/app/modules/news/news.component.html | 11 +++++++++++ webapp/src/app/modules/news/news.component.scss | 17 +++++++++++++++++ webapp/src/app/modules/news/news.component.ts | 9 ++++++++- 5 files changed, 52 insertions(+), 3 deletions(-) diff --git a/service/src/main/inse/news/logic.py b/service/src/main/inse/news/logic.py index f5599ddf..82847a96 100644 --- a/service/src/main/inse/news/logic.py +++ b/service/src/main/inse/news/logic.py @@ -33,12 +33,20 @@ def get_news_page(page: int, page_size: int, sort_order: str = "desc") -> NewsPa def search_news(query_text: str, page: int, page_size: int) -> NewsPage: offset = (page - 1) * page_size + highlight = { + "fields": {"full_content": {"fragment_size": 200, "number_of_fragments": 1}}, + "pre_tags": [""], + "post_tags": [""], + "encoder": "html", + } + response = _run_search( query={"match": {"full_content": query_text}}, source=["date", "maintitle", "author", "url"], size=page_size, offset=offset, sort=None, + highlight=highlight, ) return _build_page(response, page, page_size) @@ -159,7 +167,7 @@ def _get_postproc_labels(news_id: str) -> tuple[bool | None, list]: return relevant, authors -def _run_search(query: dict, source: list, size: int, offset: int, sort) -> dict: +def _run_search(query: dict, source: list, size: int, offset: int, sort, highlight: dict = None) -> dict: try: return elasticsearch.search( index="aktuell", @@ -169,6 +177,7 @@ def _run_search(query: dict, source: list, size: int, offset: int, sort) -> dict offset=offset, sort=sort, track_total_hits=True, + highlight=highlight, cluster="inse", ) except Exception as exc: @@ -234,11 +243,15 @@ def _get_relevance_map(news_ids: list) -> dict: def _parse_hit(hit: dict) -> NewsArticle: source = hit.get("_source", {}) - + + fragments = hit.get("highlight", {}).get("full_content") + snippet = fragments[0] if fragments else None + return NewsArticle( id=hit.get("_id"), date=source.get("date"), maintitle=source.get("maintitle"), author=source.get("author"), url=source.get("url"), + snippet=snippet, ) diff --git a/service/src/main/inse/news/model.py b/service/src/main/inse/news/model.py index 83b593b3..be32ee80 100644 --- a/service/src/main/inse/news/model.py +++ b/service/src/main/inse/news/model.py @@ -13,6 +13,7 @@ class NewsArticle(BaseModel): author: Optional[str] = None url: Optional[str] = None relevant: Optional[bool] = None + snippet: Optional[str] = None class NewsArticleDetail(NewsArticle): diff --git a/webapp/src/app/modules/news/news.component.html b/webapp/src/app/modules/news/news.component.html index bfd8cba1..aff9aadc 100644 --- a/webapp/src/app/modules/news/news.component.html +++ b/webapp/src/app/modules/news/news.component.html @@ -42,6 +42,17 @@ + + Fundstelle + + @if (article.snippet) { + + } @else { + — + } + + + Relevanz diff --git a/webapp/src/app/modules/news/news.component.scss b/webapp/src/app/modules/news/news.component.scss index def9857d..100dead9 100644 --- a/webapp/src/app/modules/news/news.component.scss +++ b/webapp/src/app/modules/news/news.component.scss @@ -114,6 +114,23 @@ table { background: transparent; } +.snippet { + color: var(--sg-text-muted); + font-size: 13px; + line-height: 1.4; +} + +::ng-deep .snippet em { + font-style: normal; + background: #fff48d; + padding: 0 3px; + border-radius: 3px; +} + +.snippet-empty { + color: var(--sg-text-muted); +} + .relevance-badge { display: inline-flex; align-items: center; diff --git a/webapp/src/app/modules/news/news.component.ts b/webapp/src/app/modules/news/news.component.ts index 89a3d1e4..3c1ff74c 100644 --- a/webapp/src/app/modules/news/news.component.ts +++ b/webapp/src/app/modules/news/news.component.ts @@ -22,6 +22,7 @@ interface NewsArticle { author?: string | null; url?: string | null; relevant?: boolean | null; + snippet?: string | null; } interface NewsPage { @@ -60,7 +61,13 @@ export class NewsComponent implements OnInit { readonly searchControl = new FormControl('', { nonNullable: true }); - displayedColumns = ['maintitle', 'relevance', 'date']; + get displayedColumns(): string[] { + if (this.isSearching) { + return ['maintitle', 'snippet', 'relevance', 'date']; + } + return ['maintitle', 'relevance', 'date']; + } + articles: NewsArticle[] = []; total = 0; loading = false; From c8b055902fb431e08f6ed7c8e94a7dc1993f1db5 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sat, 20 Jun 2026 17:03:45 +0200 Subject: [PATCH 21/24] Add badge with link to author profile in news --- service/src/main/inse/news/logic.py | 20 +++++-- service/src/main/inse/news/model.py | 8 ++- service/src/main/inse/persons/logic.py | 54 +++++++++++++++++++ .../news-detail/news-detail.component.html | 20 +++++-- .../news-detail/news-detail.component.scss | 25 ++++++++- .../news-detail/news-detail.component.ts | 8 ++- 6 files changed, 124 insertions(+), 11 deletions(-) diff --git a/service/src/main/inse/news/logic.py b/service/src/main/inse/news/logic.py index 82847a96..5f22b9eb 100644 --- a/service/src/main/inse/news/logic.py +++ b/service/src/main/inse/news/logic.py @@ -10,8 +10,8 @@ from fastapi import HTTPException from starlette.status import HTTP_500_INTERNAL_SERVER_ERROR from ..integrations import elasticsearch -from ..persons.logic import get_author_name_by_id -from .model import NewsArticle, NewsArticleDetail, NewsPage +from ..persons.logic import find_ude_author_by_name, get_author_name_by_id +from .model import MentionedPerson, NewsArticle, NewsArticleDetail, NewsPage logger = logging.getLogger(__name__) @@ -139,10 +139,24 @@ def get_news_by_id(news_id: str) -> NewsArticleDetail: url=source.get("url"), full_content=source.get("full_content"), relevant=relevant, - authors=authors, + authors=_build_mentioned_persons(authors), ) +def _build_mentioned_persons(author_names: list) -> list: + + persons = [] + for name in author_names: + match = find_ude_author_by_name(name) + if match: + persons.append( + MentionedPerson(name=name, is_ude=True, person_id=match["id"]) + ) + else: + persons.append(MentionedPerson(name=name)) + return persons + + def _get_postproc_labels(news_id: str) -> tuple[bool | None, list]: try: response = elasticsearch.search( diff --git a/service/src/main/inse/news/model.py b/service/src/main/inse/news/model.py index be32ee80..723e9b49 100644 --- a/service/src/main/inse/news/model.py +++ b/service/src/main/inse/news/model.py @@ -16,10 +16,16 @@ class NewsArticle(BaseModel): snippet: Optional[str] = None +class MentionedPerson(BaseModel): + name: str + is_ude: bool = False + person_id: Optional[str] = None + + class NewsArticleDetail(NewsArticle): full_content: Optional[str] = None relevant: Optional[bool] = None - authors: List[str] = [] + authors: List[MentionedPerson] = [] class NewsPage(BaseModel): diff --git a/service/src/main/inse/persons/logic.py b/service/src/main/inse/persons/logic.py index 76db43c7..458ecc23 100644 --- a/service/src/main/inse/persons/logic.py +++ b/service/src/main/inse/persons/logic.py @@ -30,6 +30,60 @@ from inse.persons.model import ( ) logger = logging.getLogger(__name__) INDEX_NAME = "openalex-authors" +UDE_INSTITUTION_ID = "https://openalex.org/I62318514" # Universität Duisburg-Essen + +def find_ude_author_by_name(display_name: str) -> Optional[dict]: + query = { + "_source": ["display_name"], + "query": { + "bool": { + "must": [ + { + "match_phrase": { + "display_name": display_name + } + }, + { + "nested": { + "path": "affiliations", + "query": { + "term": { + "affiliations.institution.id": UDE_INSTITUTION_ID + } + }, + } + }, + ] + } + }, + "size": 10, + } + + try: + data = elasticsearch.search(index=INDEX_NAME, body=query) + except Exception: + logger.exception(f"UDE-Lookup für '{display_name}' fehlgeschlagen.") + return None + + hits = data.get("hits", {}).get("hits", []) + + display_name = display_name.strip().lower() + exact_matches = [] + + for hit in hits: + hit_display_name = hit.get("_source", {}).get("display_name", "") + if hit_display_name.strip().lower() == display_name: + exact_matches.append(hit) + + if not exact_matches: + return None + + hit = exact_matches[0] + + return { + "id": hit.get("_id"), + "display_name": hit.get("_source", {}).get("display_name"), + } def get_author_name_by_id(author_id: str) -> Optional[str]: diff --git a/webapp/src/app/modules/news-detail/news-detail.component.html b/webapp/src/app/modules/news-detail/news-detail.component.html index ce499e8d..1bc97e7c 100644 --- a/webapp/src/app/modules/news-detail/news-detail.component.html +++ b/webapp/src/app/modules/news-detail/news-detail.component.html @@ -82,11 +82,21 @@
@if (article.authors && article.authors.length) { - @for (person of article.authors; track person) { -
-
{{ person.charAt(0) }}
- {{ person }} -
+ @for (person of article.authors; track person.name) { + @if (person.is_ude && person.person_id) { + +
{{ person.name.charAt(0) }}
+ {{ person.name }} + UDE +
+ } @else { +
+
{{ person.name.charAt(0) }}
+ {{ person.name }} +
+ } } } @else {

Keine erwähnten Personen gefunden.

diff --git a/webapp/src/app/modules/news-detail/news-detail.component.scss b/webapp/src/app/modules/news-detail/news-detail.component.scss index 02101fda..e1669060 100644 --- a/webapp/src/app/modules/news-detail/news-detail.component.scss +++ b/webapp/src/app/modules/news-detail/news-detail.component.scss @@ -184,7 +184,7 @@ main { .person-item { display: grid; - grid-template-columns: 38px minmax(0, 1fr); + grid-template-columns: 38px minmax(0, 1fr) auto; gap: 11px; align-items: center; padding: 12px; @@ -192,6 +192,29 @@ main { background: var(--sg-surface-muted); } +.person-item.is-link { + cursor: pointer; + text-decoration: none; + color: inherit; + transition: background 0.15s ease; +} + +.person-item.is-link:hover { + background: #e5ecfb; +} + +.ude-badge { + justify-self: end; + padding: 3px 9px; + border-radius: 999px; + background: #effaf3; + border: 1px solid #bdebcf; + color: #24834f; + font-size: 11px; + font-weight: 700; + letter-spacing: 0.03em; +} + .avatar { display: grid; place-items: center; diff --git a/webapp/src/app/modules/news-detail/news-detail.component.ts b/webapp/src/app/modules/news-detail/news-detail.component.ts index 5c51b52c..bd75dc3c 100644 --- a/webapp/src/app/modules/news-detail/news-detail.component.ts +++ b/webapp/src/app/modules/news-detail/news-detail.component.ts @@ -9,6 +9,12 @@ import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { WorksService } from '../../api'; +interface MentionedPerson { + name: string; + is_ude?: boolean; + person_id?: string | null; +} + interface NewsArticleDetail { id: string; date?: string | null; @@ -17,7 +23,7 @@ interface NewsArticleDetail { url?: string | null; full_content?: string | null; relevant?: boolean; - authors?: string[]; + authors?: MentionedPerson[]; } @Component({ From be74063a5171b693c74124154313e5c124163f15 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sat, 20 Jun 2026 17:10:30 +0200 Subject: [PATCH 22/24] order person list in news to show ude authors on top --- service/src/main/inse/news/logic.py | 11 +++++++---- .../modules/news-detail/news-detail.component.html | 2 +- .../modules/news-detail/news-detail.component.scss | 11 +++++++++++ 3 files changed, 19 insertions(+), 5 deletions(-) diff --git a/service/src/main/inse/news/logic.py b/service/src/main/inse/news/logic.py index 5f22b9eb..48e7f5ff 100644 --- a/service/src/main/inse/news/logic.py +++ b/service/src/main/inse/news/logic.py @@ -145,16 +145,19 @@ def get_news_by_id(news_id: str) -> NewsArticleDetail: def _build_mentioned_persons(author_names: list) -> list: - persons = [] + ude_persons = [] + other_persons = [] + for name in author_names: match = find_ude_author_by_name(name) if match: - persons.append( + ude_persons.append( MentionedPerson(name=name, is_ude=True, person_id=match["id"]) ) else: - persons.append(MentionedPerson(name=name)) - return persons + other_persons.append(MentionedPerson(name=name)) + + return ude_persons + other_persons def _get_postproc_labels(news_id: str) -> tuple[bool | None, list]: diff --git a/webapp/src/app/modules/news-detail/news-detail.component.html b/webapp/src/app/modules/news-detail/news-detail.component.html index 1bc97e7c..dc1a3fc0 100644 --- a/webapp/src/app/modules/news-detail/news-detail.component.html +++ b/webapp/src/app/modules/news-detail/news-detail.component.html @@ -92,7 +92,7 @@ UDE } @else { -
+
{{ person.name.charAt(0) }}
{{ person.name }}
diff --git a/webapp/src/app/modules/news-detail/news-detail.component.scss b/webapp/src/app/modules/news-detail/news-detail.component.scss index e1669060..82f7b1ac 100644 --- a/webapp/src/app/modules/news-detail/news-detail.component.scss +++ b/webapp/src/app/modules/news-detail/news-detail.component.scss @@ -203,6 +203,17 @@ main { background: #e5ecfb; } +.person-item.is-muted { + .avatar { + background: #ececef; + color: var(--sg-text-muted); + } + + .person-name { + color: var(--sg-text-muted); + } +} + .ude-badge { justify-self: end; padding: 3px 9px; From 3b16f8d8fc36bcd18ee144f57547c921d1b14c96 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sat, 20 Jun 2026 20:31:13 +0200 Subject: [PATCH 23/24] extract latest institution from affiliations if last_known_institutions is null --- .../person-card/person-card.component.ts | 24 +++++++++++++++---- .../app/modules/person/person.component.ts | 21 +++++++++------- 2 files changed, 32 insertions(+), 13 deletions(-) diff --git a/webapp/src/app/modules/person-card/person-card.component.ts b/webapp/src/app/modules/person-card/person-card.component.ts index 89f0440c..6502b9c5 100644 --- a/webapp/src/app/modules/person-card/person-card.component.ts +++ b/webapp/src/app/modules/person-card/person-card.component.ts @@ -36,11 +36,25 @@ export class PersonCardComponent { } institution(person: CustomAuthor): DehydratedInstitution | undefined { - return ( - person.last_known_institutions?.[0] || - person.affiliations?.[person.affiliations.length - 1]?.institution || - undefined - ); + if (person.last_known_institutions?.[0]) { + return person.last_known_institutions[0]; + } + + const affiliations = person.affiliations ?? []; + let newestInstitution: DehydratedInstitution | undefined = + affiliations[0]?.institution ?? undefined; + let newestYear = -1; + + for (const affiliation of affiliations) { + for (const jahr of affiliation.years ?? []) { + if (jahr > newestYear) { + newestYear = jahr; + newestInstitution = affiliation.institution ?? undefined; + } + } + } + + return newestInstitution; } topics(person: CustomAuthor): WorkTopic[] { diff --git a/webapp/src/app/modules/person/person.component.ts b/webapp/src/app/modules/person/person.component.ts index a74be3fe..13b866bd 100644 --- a/webapp/src/app/modules/person/person.component.ts +++ b/webapp/src/app/modules/person/person.component.ts @@ -119,15 +119,20 @@ export class PersonComponent { () => this.person()?.affiliations?.[0] ?? null, ); readonly lastAffiliation = computed(() => { - let lastAffiliation: number | undefined = 0; - if (this.person()?.affiliations?.length != undefined) { - lastAffiliation = this.person()?.affiliations?.length; + const affiliations = this.person()?.affiliations ?? []; + let newestAffiliation = affiliations[0] ?? null; + let newestYear = -1; + + for (const affiliation of affiliations) { + for (const jahr of affiliation.years ?? []) { + if (jahr > newestYear) { + newestYear = jahr; + newestAffiliation = affiliation; + } + } } - return ( - (lastAffiliation - ? this.person()?.affiliations?.[lastAffiliation - 1] - : this.person()?.affiliations?.[0]) ?? null - ); + + return newestAffiliation; }); readonly institution = computed( () => From d1588ac5c1d9c4264a99d84522dd8aaf8c47647a Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sat, 20 Jun 2026 21:14:17 +0200 Subject: [PATCH 24/24] Resolve conflicts in generated OpenAPI client by regenerating from dev --- webapp/src/app/api/model/fundingProjectPage.ts | 18 ------------------ webapp/src/app/api/model/keywords.ts | 3 --- webapp/src/app/api/model/topics.ts | 4 ---- webapp/src/app/api/model/yearlyData.ts | 6 ------ 4 files changed, 31 deletions(-) diff --git a/webapp/src/app/api/model/fundingProjectPage.ts b/webapp/src/app/api/model/fundingProjectPage.ts index 6641656a..e0996525 100644 --- a/webapp/src/app/api/model/fundingProjectPage.ts +++ b/webapp/src/app/api/model/fundingProjectPage.ts @@ -9,24 +9,6 @@ */ import { FundingProject } from './fundingProject'; -export interface EuProjectPage { - /** - * The current page number. - */ - page?: number; - /** - * The requested page size. - */ - size?: number; - /** - * The total number of items. - */ - total?: number; - /** - * The EU projects on this page. - */ - elements?: Array; -} export interface FundingProjectPage { /** * The current page number. diff --git a/webapp/src/app/api/model/keywords.ts b/webapp/src/app/api/model/keywords.ts index 51be69db..d93b5fe0 100644 --- a/webapp/src/app/api/model/keywords.ts +++ b/webapp/src/app/api/model/keywords.ts @@ -8,9 +8,6 @@ * Do not edit the class manually. */ -export interface DisplayCodeSplittedNested { - single_display_code?: string | null; -} /** * Keywords associated with the project */ diff --git a/webapp/src/app/api/model/topics.ts b/webapp/src/app/api/model/topics.ts index ff61fde6..cf40ff1d 100644 --- a/webapp/src/app/api/model/topics.ts +++ b/webapp/src/app/api/model/topics.ts @@ -8,8 +8,4 @@ * Do not edit the class manually. */ -export interface KeywordNested { - keyword?: string | null; -} - export interface Topics {} diff --git a/webapp/src/app/api/model/yearlyData.ts b/webapp/src/app/api/model/yearlyData.ts index c6920fac..d473f13e 100644 --- a/webapp/src/app/api/model/yearlyData.ts +++ b/webapp/src/app/api/model/yearlyData.ts @@ -8,12 +8,6 @@ * Do not edit the class manually. */ -export interface ProgrammeNested { - code?: string | null; - id?: string | null; - programme?: string | null; -} - export interface YearlyData { year: number; publications: number;