diff --git a/service/src/main/inse/auth/router.py b/service/src/main/inse/auth/router.py index 9bf5d85a..4bb2ab31 100644 --- a/service/src/main/inse/auth/router.py +++ b/service/src/main/inse/auth/router.py @@ -2,7 +2,7 @@ import logging import uuid from typing import Annotated -from fastapi import APIRouter, Body, Depends, Response, status +from fastapi import APIRouter, Body, Depends, Query, Response, status from sqlmodel import Session import inse.auth.service as auth_service @@ -204,3 +204,30 @@ async def change_password( current_password=current_password, new_password=new_password, ) + + +@router.get( + "/can-fetch-gdpr-relevant-data", + summary="Check if user can fetch GDPR-relevant data", + description="Check if the authenticated user can fetch GDPR-relevant data for a given author and institution.", + operation_id="canFetchGdprRelevantData", +) +async def can_fetch_gdpr_relevant_data( + access_token: Annotated[ + AccessTokenMetadata, + auth_service.CurrentUserAccessTokenPayloadDep, + ], + raw_oa_author_id: Annotated[ + str | None, + Query(description="OpenAlex author ID to check access for"), + ] = None, + raw_oa_institution_id: Annotated[ + str | None, + Query(description="OpenAlex institution ID to check access for"), + ] = None, +) -> bool: + return await auth_service.can_fetch_gdpr_relevant_data( + access_token=access_token, + raw_oa_author_id=raw_oa_author_id, + raw_oa_institution_id=raw_oa_institution_id, + ) diff --git a/service/src/main/inse/auth/service.py b/service/src/main/inse/auth/service.py index 9ce83f9c..4898ebef 100644 --- a/service/src/main/inse/auth/service.py +++ b/service/src/main/inse/auth/service.py @@ -31,6 +31,7 @@ from inse.auth.model import ( effective_role_for_roles, normalize_roles, ) +from inse.authors.v2 import service as authors_service from inse.config import get_settings from inse.database import get_session @@ -1451,3 +1452,69 @@ def change_password( logger.info("Password changed successfully for account %s", account.id) return {"status": "ok"} + + +async def can_fetch_gdpr_relevant_data( + access_token: AccessTokenMetadata, + raw_oa_author_id: str | None = None, + raw_oa_institution_id: str | None = None, +) -> bool: + """Returns True if the user associated with the provided access token is allowed to fetch GDPR-relevant data for the specified OpenAlex author ID and institution ID, based on their effective institution ID. + + Args: + access_token (AccessTokenMetadata): The access token for the user. + raw_oa_author_id (str | None, optional): The OpenAlex author ID for which to check access. Defaults to None. + raw_oa_institution_id (str | None, optional): The OpenAlex institution ID for which to check access. Defaults to None. + + Returns: + bool: True if the user is allowed to fetch GDPR-relevant data for the specified IDs, False otherwise. + """ + + logger.debug( + "Checking if user with effective institution ID %s can fetch GDPR-relevant data for author ID %s and institution ID %s", + access_token.effective_institution_id, + raw_oa_author_id, + raw_oa_institution_id, + ) + + if not raw_oa_author_id and not raw_oa_institution_id: + logger.debug("No OpenAlex author ID or institution ID provided") + return False + + effective_institution_id = access_token.effective_institution_id + # Current user does not belong to any institution + if not effective_institution_id: + logger.debug( + "Current user does not belong to any institution, cannot fetch GDPR-relevant data" + ) + return False + + # Current user belongs to an institution, but the request is for a different institution + if ( + raw_oa_institution_id + and effective_institution_id + and raw_oa_institution_id != effective_institution_id + ): + logger.debug( + "Current user belongs to institution %s, but request is for institution %s, cannot fetch GDPR-relevant data", + effective_institution_id, + raw_oa_institution_id, + ) + return False + + # Current user belongs to an institution, but request is for author not belonging to that institution + if raw_oa_author_id: + author_belongs_to_institution = ( + await authors_service.author_currently_belongs_to_institution( + raw_oa_author_id or "", effective_institution_id + ) + ) + logger.debug( + "Author %s belongs to institution %s: %s", + raw_oa_author_id, + effective_institution_id, + author_belongs_to_institution, + ) + return author_belongs_to_institution + + return True diff --git a/service/src/main/inse/institutions/institutions_search_client.py b/service/src/main/inse/institutions/institutions_search_client.py index 482194d9..7896a01d 100644 --- a/service/src/main/inse/institutions/institutions_search_client.py +++ b/service/src/main/inse/institutions/institutions_search_client.py @@ -361,6 +361,7 @@ class InstitutionsSearchClient: "government", "facility", "other", + "funder", } cleaned_source = {} diff --git a/service/src/main/inse/institutions/logic.py b/service/src/main/inse/institutions/logic.py index 9e7eeb2e..4437c6c9 100644 --- a/service/src/main/inse/institutions/logic.py +++ b/service/src/main/inse/institutions/logic.py @@ -33,6 +33,7 @@ _VALID_INSTITUTION_TYPES = { "government", "facility", "other", + "funder", } diff --git a/service/src/main/inse/institutions/test_logic.py b/service/src/main/inse/institutions/test_logic.py index cca61dc9..d19b6ba7 100644 --- a/service/src/main/inse/institutions/test_logic.py +++ b/service/src/main/inse/institutions/test_logic.py @@ -174,3 +174,34 @@ async def test_list_institutions_accepts_practical_openalex_type_variants(): assert result.results[0].counts_by_year[0].cited_by_count is None assert result.group_by[0].key == "true" + +@pytest.mark.anyio +async def test_list_institutions_accepts_funder_institution_type(): + def handler(_: httpx.Request) -> httpx.Response: + return httpx.Response( + 200, + json={ + "meta": {"count": 1, "page": 1, "per_page": 25}, + "results": [ + { + "id": "https://openalex.org/I4210119759", + "display_name": "Essen University Hospital", + "country_code": "DE", + "type": "funder", + } + ], + }, + ) + + client = OpenAlexInstitutionsClient( + api_key="test-key", + transport=httpx.MockTransport(handler), + ) + + result = await logic.list_institutions(client=client) + + assert result.results[0].id == "https://openalex.org/I4210119759" + assert result.results[0].display_name == "Essen University Hospital" + assert result.results[0].type == "funder" + + diff --git a/service/src/main/inse/models/openalex/institution.py b/service/src/main/inse/models/openalex/institution.py index deede4f7..089013ba 100644 --- a/service/src/main/inse/models/openalex/institution.py +++ b/service/src/main/inse/models/openalex/institution.py @@ -37,7 +37,7 @@ class Institution(BaseModel): ror: StrictStr | None = Field(default=None, description="The ROR ID for this institution. This is the Canonical External ID for institutions.") display_name: StrictStr | None = Field(default=None, description="The primary name of the institution.") country_code: StrictStr | None = Field(default=None, description="ISO two-letter country code where this institution is located.") - type: StrictStr | None = Field(default=None, description="The institution's primary type (ROR vocabulary): `Education`, `Healthcare`, `Company`, `Archive`, `Nonprofit`, `Government`, `Facility`, `Other`.") + type: StrictStr | None = Field(default=None, description="The institution's primary type (ROR vocabulary): `Education`, `Healthcare`, `Company`, `Archive`, `Nonprofit`, `Government`, `Facility`, `Other`, `Funder`.") homepage_url: StrictStr | None = Field(default=None, description="URL for the institution's primary homepage.") image_url: StrictStr | None = Field(default=None, description="URL for an image representing this institution (usually from Wikimedia).") image_thumbnail_url: StrictStr | None = Field(default=None, description="Smaller version of `image_url`.") @@ -61,8 +61,9 @@ class Institution(BaseModel): if value is None: return value - if value not in set(['education', 'healthcare', 'company', 'archive', 'nonprofit', 'government', 'facility', 'other']): - raise ValueError("must be one of enum values ('education', 'healthcare', 'company', 'archive', 'nonprofit', 'government', 'facility', 'other')") + valid_types = {'education', 'healthcare', 'company', 'archive', 'nonprofit', 'government', 'facility', 'other', 'funder'} + if value not in valid_types: + return 'other' return value model_config = ConfigDict( diff --git a/service/src/main/inse/patents/keywords/logic.py b/service/src/main/inse/patents/keywords/logic.py index 01e06de2..138602cb 100644 --- a/service/src/main/inse/patents/keywords/logic.py +++ b/service/src/main/inse/patents/keywords/logic.py @@ -1,4 +1,4 @@ -"""Find patents for extracted OpenAlex keywords via patents_openalex_keywords index.""" +"""Find patents for extracted OpenAlex keywords via IPC/CPC reverse lookup.""" from __future__ import annotations import asyncio @@ -31,7 +31,6 @@ from inse.patents.ipc_lookup import ( ) from inse.patents.ipc_search_client import IpcSearchClient from inse.patents.keywords.model import ( - KeywordEvidence, KeywordPatentMappingStatus, KeywordPatentMatch, KeywordPatentSearchDiagnostics, @@ -76,13 +75,7 @@ _MIN_LEADER_RELATIVE_MASS = 0.20 _MIN_LEADER_MASS_RATIO = 1.5 _TARGET_CUMULATIVE_CLUSTER_MASS = 0.75 _MIN_PATENT_MATCH_SCORE = 0.50 -_MIN_TEXT_PATENT_MATCH_SCORE = 0.30 _DEFAULT_SCORE_WEIGHTS = {"ipc": 0.60, "topic": 0.25, "text": 0.15} -# When IPC mapping is abstained, score only topic + text evidence. -_TEXT_SCORE_WEIGHTS = {"ipc": 0.0, "topic": 0.45, "text": 0.55} -# Also try title/abstract search when IPC mapping produced terms but scoring -# returned no patents (empty retrieval or over-filtering). -_TEXT_SEARCH_AFTER_EMPTY_IPC = True _TOPIC_SCORE_TOPIC_ID = 1.0 _TOPIC_SCORE_SUBFIELD = 0.7 _TOPIC_SCORE_COMPATIBLE_FIELD = 0.3 @@ -618,12 +611,6 @@ class TopicEvidence: score: float -@dataclass(frozen=True) -class TextGateDecision: - accepted: bool - reason: str - - def _compute_topic_evidence( patent_topics: list[MappedOpenAlexTopic], keyword_topic_ids: frozenset[str], @@ -702,16 +689,6 @@ def _tokenize_words(text: str) -> list[str]: return re.findall(r"[a-z0-9äöüß]+", (text or "").casefold()) -def _contains_token_sequence(haystack: list[str], needle: list[str]) -> bool: - if not needle or len(needle) > len(haystack): - return False - width = len(needle) - for index in range(len(haystack) - width + 1): - if haystack[index : index + width] == needle: - return True - return False - - def _token_set(tokens: list[str]) -> set[str]: return set(tokens) @@ -735,23 +712,6 @@ def _text_search_terms(items: list[KeywordPatentSearchItem]) -> list[str]: return terms -def _text_search_phrases(items: list[KeywordPatentSearchItem]) -> list[str]: - """Full phrases for ES title/abstract retrieval (text path).""" - phrases: list[str] = [] - seen: set[str] = set() - for item in items: - for value in (item.keyword, item.topic_display_name): - cleaned = " ".join((value or "").strip().split()) - if len(cleaned) < 3: - continue - key = cleaned.casefold() - if key in seen: - continue - seen.add(key) - phrases.append(cleaned) - return phrases - - def _text_overlap_score( patent: model.PatentEntry, search_terms: list[str], @@ -772,173 +732,6 @@ def _text_overlap_score( return min(hits / 3, 1.0) -def _text_match_kind( - *, - phrase_in_title: bool, - phrase_in_abstract: bool, - full_token_match: bool, - partial_token_match: bool, -) -> str: - if phrase_in_title: - return "phrase_title" - if phrase_in_abstract: - return "phrase_abstract" - if full_token_match: - return "full_token" - if partial_token_match: - return "partial_token" - return "none" - - -def _collect_keyword_text_evidence( - patent: model.PatentEntry, - phrases: list[str], - search_terms: list[str], -) -> KeywordEvidence: - """Record phrase / full-token / partial-token evidence separately.""" - title_tokens = _tokenize_words(patent.title or "") - abstract_tokens = _tokenize_words(patent.abstract or "") - combined_tokens = _token_set(title_tokens + abstract_tokens) - - phrase_in_title = False - phrase_in_abstract = False - full_token_match = False - partial_token_match = False - matched_phrases: list[str] = [] - - for phrase in phrases: - phrase_tokens = _tokenize_words(phrase) - if not phrase_tokens: - continue - if _contains_token_sequence(title_tokens, phrase_tokens): - phrase_in_title = True - matched_phrases.append(phrase) - elif _contains_token_sequence(abstract_tokens, phrase_tokens): - phrase_in_abstract = True - matched_phrases.append(phrase) - - present = [token for token in phrase_tokens if token in combined_tokens] - if present and len(present) == len(phrase_tokens): - full_token_match = True - elif present: - partial_token_match = True - - matched_words = [term for term in search_terms if term in combined_tokens] - if matched_words and not full_token_match and not partial_token_match: - # Lone search-term hits without a covering phrase count as partial. - partial_token_match = True - - word_match_score = ( - min(len(matched_words) / 3, 1.0) if search_terms and matched_words else 0.0 - ) - kind = _text_match_kind( - phrase_in_title=phrase_in_title, - phrase_in_abstract=phrase_in_abstract, - full_token_match=full_token_match, - partial_token_match=partial_token_match, - ) - - return KeywordEvidence( - phrase_in_title=phrase_in_title, - phrase_in_abstract=phrase_in_abstract, - full_token_match=full_token_match, - partial_token_match=partial_token_match, - word_match_score=round(word_match_score, 4), - matched_phrases=list(dict.fromkeys(matched_phrases)), - matched_words=matched_words, - text_match_kind=kind, - ) - - -def _keyword_text_score(evidence: KeywordEvidence) -> float: - if evidence.phrase_in_title: - return 1.0 - if evidence.phrase_in_abstract: - return 0.85 - if evidence.full_token_match: - return 0.55 - if evidence.partial_token_match: - return 0.25 - return 0.0 - - -def _exact_topic_or_subfield_match( - patent_topics: list[MappedOpenAlexTopic], - keyword_topic_ids: frozenset[str], - keyword_subfield_names: frozenset[str], -) -> bool: - evidence = _compute_topic_evidence( - patent_topics, - keyword_topic_ids, - keyword_subfield_names, - frozenset(), - ) - return evidence.match_kind in {"topic_id", "subfield"} - - -def _keyword_text_passes_relevance_gate( - evidence: KeywordEvidence, - *, - topic_evidence: TopicEvidence, -) -> TextGateDecision: - """Keyword text acceptance policy (no domain hardcoding). - - Accept: - - phrase in title (strong) - - phrase in abstract (medium) - - exact topic/subfield together with full token text evidence - Reject: - - partial/general words alone - - compatible field alone - - exact topic/subfield without text evidence - """ - exact = topic_evidence.match_kind in {"topic_id", "subfield"} - - if evidence.phrase_in_title: - return TextGateDecision(True, "phrase_in_title") - if evidence.phrase_in_abstract: - return TextGateDecision(True, "phrase_in_abstract") - if exact and evidence.full_token_match: - return TextGateDecision( - True, - f"{topic_evidence.match_kind}_with_full_token_match", - ) - if exact and evidence.partial_token_match: - return TextGateDecision(False, "exact_topic_with_partial_tokens_only") - if exact: - return TextGateDecision(False, "exact_topic_without_text") - if topic_evidence.match_kind == "compatible_field": - return TextGateDecision(False, "compatible_field_only") - if evidence.partial_token_match or evidence.matched_words: - return TextGateDecision(False, "partial_or_loose_words_only") - return TextGateDecision(False, "insufficient_evidence") - - -def _matched_keyword_labels_from_evidence( - items: list[KeywordPatentSearchItem], - evidence: KeywordEvidence, -) -> list[str]: - matched: list[str] = [] - seen: set[str] = set() - phrase_keys = {phrase.casefold() for phrase in evidence.matched_phrases} - word_keys = set(evidence.matched_words) - - for item in items: - for value in (item.keyword, item.topic_display_name): - label = (value or "").strip() - if not label: - continue - key = label.casefold() - if key in seen: - continue - label_tokens = _tokenize_words(label) - if key in phrase_keys or any(token in word_keys for token in label_tokens): - seen.add(key) - matched.append(label) - break - return matched - - def _patent_passes_relevance_gate( patent_topics: list[MappedOpenAlexTopic], *, @@ -1261,210 +1054,6 @@ async def _score_patents_with_ipc( } -async def _score_patents_text_search( - *, - raw_patents: list[model.PatentEntry], - search_keywords: list[KeywordPatentSearchItem], - phrases: list[str], - text_search_terms: list[str], - keyword_topic_ids: frozenset[str], - keyword_subfield_names: frozenset[str], - keyword_soft_field_names: frozenset[str], - resolver: PatentOpenAlexMappingResolver, -) -> tuple[list[KeywordPatentMatch], dict[str, int]]: - """Score patents without IPC using graded topic + structured text evidence.""" - patent_topics_by_key = await resolver.resolve_topics_for_patents(raw_patents) - scored: list[KeywordPatentMatch] = [] - filtered_by_relevance_gate = 0 - filtered_by_min_score = 0 - passed_relevance_gate = 0 - - for patent in raw_patents: - patent_topics = patent_topics_by_key.get(patent_map_key(patent), []) - evidence = _collect_keyword_text_evidence(patent, phrases, text_search_terms) - topic_evidence = _compute_topic_evidence( - patent_topics, - keyword_topic_ids, - keyword_subfield_names, - keyword_soft_field_names, - ) - decision = _keyword_text_passes_relevance_gate( - evidence, - topic_evidence=topic_evidence, - ) - if not decision.accepted: - filtered_by_relevance_gate += 1 - logger.info( - "Text reject: id=%s title=%s topic_kind=%s topic_score=%.2f " - "text_kind=%s phrase_title=%s phrase_abstract=%s " - "full_token=%s partial_token=%s reason=%s", - patent.patent_id, - patent.title, - topic_evidence.match_kind, - topic_evidence.score, - evidence.text_match_kind, - evidence.phrase_in_title, - evidence.phrase_in_abstract, - evidence.full_token_match, - evidence.partial_token_match, - decision.reason, - ) - continue - - passed_relevance_gate += 1 - text_score = _keyword_text_score(evidence) - # Field-only remains a weak ranking signal when already accepted via phrase. - score = _compute_final_score( - 0.0, - topic_evidence.score, - text_score, - weights=_TEXT_SCORE_WEIGHTS, - ) - if score < _MIN_TEXT_PATENT_MATCH_SCORE: - filtered_by_min_score += 1 - logger.info( - "Text reject: id=%s reason=below_min_score score=%.4f", - patent.patent_id, - score, - ) - continue - - logger.info( - "Text accept: id=%s title=%s topic_kind=%s topic_score=%.2f " - "text_kind=%s text_score=%.2f final_score=%.4f reason=%s", - patent.patent_id, - patent.title, - topic_evidence.match_kind, - topic_evidence.score, - evidence.text_match_kind, - text_score, - score, - decision.reason, - ) - scored.append( - KeywordPatentMatch( - patent=patent, - match_score=score, - ipc_score=0.0, - topic_score=topic_evidence.score, - text_score=text_score, - matched_keywords=_matched_keyword_labels_from_evidence( - search_keywords, - evidence, - ), - matched_ipc_symbols=[], - text_retrieval=True, - keyword_evidence=evidence, - topic_match_kind=topic_evidence.match_kind, - ) - ) - - logger.info( - "Keyword patent text search: filtered_by_relevance_gate=%d " - "filtered_by_min_score=%d passed_relevance_gate=%d scored=%d", - filtered_by_relevance_gate, - filtered_by_min_score, - passed_relevance_gate, - len(scored), - ) - return scored, { - "filtered_by_relevance_gate": filtered_by_relevance_gate, - "filtered_by_min_score": filtered_by_min_score, - "passed_relevance_gate": passed_relevance_gate, - } - - -async def _search_patents_text_search( - *, - client: BasePatentSearchClient, - queries: IpcPatentSearchQueries, - ipc_search: IpcSearchClient, - resolver: PatentOpenAlexMappingResolver, - search_keywords: list[KeywordPatentSearchItem], - keyword_topic_ids: frozenset[str], - keyword_subfield_names: frozenset[str], - keyword_soft_field_names: frozenset[str], - mapping_status: KeywordPatentMappingStatus, - ipc_cluster_selections: list[dict] | None = None, -) -> PatentsByKeywordsResponse: - cluster_dicts = list(ipc_cluster_selections or []) - phrases = _text_search_phrases(search_keywords) - text_search_terms = _text_search_terms(search_keywords) - if not phrases: - logger.info( - "Keyword patent text search: no phrases for keywords %s", - [item.keyword for item in search_keywords], - ) - return PatentsByKeywordsResponse( - patent_count=0, - patents=[], - mapping_status="no_patents_found", - diagnostics=_empty_diagnostics( - search_path="text", - ipc_cluster_selections=cluster_dicts, - ), - ) - - logger.info( - "Keyword patent text search: mapping_status=%s phrases=%s", - mapping_status, - phrases, - ) - raw_patents = await _fetch_patents_for_queries( - client, - queries.epo_query_by_text_phrases(phrases, size=_MAX_PATENTS), - queries.uspto_query_by_text_phrases(phrases, size=_MAX_PATENTS), - ) - if raw_patents is None: - return PatentsByKeywordsResponse( - patent_count=0, - patents=[], - mapping_status="search_error", - diagnostics=_empty_diagnostics( - search_path="text", - ipc_cluster_selections=cluster_dicts, - ), - ) - - logger.info("Keyword patent text search: raw_patents=%d", len(raw_patents)) - scored, filter_counts = await _score_patents_text_search( - raw_patents=raw_patents, - search_keywords=search_keywords, - phrases=phrases, - text_search_terms=text_search_terms, - keyword_topic_ids=keyword_topic_ids, - keyword_subfield_names=keyword_subfield_names, - keyword_soft_field_names=keyword_soft_field_names, - resolver=resolver, - ) - scored, diagnostics = _finalize_scored_patents( - scored, - raw_count=len(raw_patents), - filtered_by_ipc=0, - filtered_by_relevance_gate=filter_counts["filtered_by_relevance_gate"], - filtered_by_min_score=filter_counts["filtered_by_min_score"], - passed_relevance_gate=filter_counts["passed_relevance_gate"], - search_path="text", - ipc_cluster_selections=cluster_dicts, - ) - await enrich_patents_classifications([item.patent for item in scored], ipc_search) - - if not scored: - return PatentsByKeywordsResponse( - patent_count=0, - patents=[], - mapping_status="no_patents_found", - diagnostics=diagnostics, - ) - - return PatentsByKeywordsResponse( - patent_count=len(scored), - patents=scored, - mapping_status=mapping_status, - diagnostics=diagnostics, - ) - - async def get_patents_by_keywords( request: PatentsByKeywordsRequest, *, @@ -1528,21 +1117,18 @@ async def get_patents_by_keywords( ) logger.info( "Keyword patent search: no IPC search terms for keywords %s " - "(mapping_status=%s) — trying keyword text search", + "(mapping_status=%s)", [item.keyword for item in search_keywords], mapping_status, ) - return await _search_patents_text_search( - client=client, - queries=queries, - ipc_search=ipc_search, - resolver=resolver, - search_keywords=search_keywords, - keyword_topic_ids=keyword_topic_ids, - keyword_subfield_names=keyword_subfield_names, - keyword_soft_field_names=keyword_soft_field_names, + return PatentsByKeywordsResponse( + patent_count=0, + patents=[], mapping_status=mapping_status, - ipc_cluster_selections=cluster_dicts, + diagnostics=_empty_diagnostics( + search_path="none", + ipc_cluster_selections=cluster_dicts, + ), ) text_search_terms = _text_search_terms(search_keywords) @@ -1594,31 +1180,11 @@ async def get_patents_by_keywords( diagnostics=diagnostics, ) - if not _TEXT_SEARCH_AFTER_EMPTY_IPC: - return PatentsByKeywordsResponse( - patent_count=0, - patents=[], - mapping_status="no_patents_found", - diagnostics=diagnostics, - ) - - logger.info( - "Keyword patent search: IPC path yielded no scored patents — " - "trying keyword text search (policy=_TEXT_SEARCH_AFTER_EMPTY_IPC)" - ) - return await _search_patents_text_search( - client=client, - queries=queries, - ipc_search=ipc_search, - resolver=resolver, - search_keywords=search_keywords, - keyword_topic_ids=keyword_topic_ids, - keyword_subfield_names=keyword_subfield_names, - keyword_soft_field_names=keyword_soft_field_names, - # IPC was selected but produced no usable hits; UI treats this like - # uncertain IPC evidence and labels patents via text_retrieval. - mapping_status="uncertain", - ipc_cluster_selections=cluster_dicts, + return PatentsByKeywordsResponse( + patent_count=0, + patents=[], + mapping_status="no_patents_found", + diagnostics=diagnostics, ) diff --git a/service/src/main/inse/patents/keywords/search_queries.py b/service/src/main/inse/patents/keywords/search_queries.py index c24570f6..780e3903 100644 --- a/service/src/main/inse/patents/keywords/search_queries.py +++ b/service/src/main/inse/patents/keywords/search_queries.py @@ -46,19 +46,12 @@ _USPTO_SOURCE_FIELDS = [ ] _MIN_MATCH_TERM_LEN = 4 -_MIN_TEXT_PHRASE_LEN = 3 # Prefer concrete group/subgroup hits over broad subclass prefixes. _BOOST_SUBGROUP = 4.0 _BOOST_MAIN_GROUP = 2.5 _BOOST_SUBCLASS = 1.0 -# Text search: prefer exact phrases in title over abstract / loose match. -_BOOST_TEXT_PHRASE_TITLE = 5.0 -_BOOST_TEXT_PHRASE_ABSTRACT = 3.0 -_BOOST_TEXT_MATCH_TITLE = 1.5 -_BOOST_TEXT_MATCH_ABSTRACT = 1.0 - def _add_term_boost(weights: dict[str, float], term: str, boost: float) -> None: cleaned = term.strip() @@ -157,76 +150,6 @@ def _ipc_match_clauses(field: str, term_boosts: dict[str, float]) -> list[dict[s return clauses -def _normalize_text_phrases(phrases: list[str]) -> list[str]: - cleaned: list[str] = [] - seen: set[str] = set() - for phrase in phrases: - value = " ".join((phrase or "").strip().split()) - if len(value) < _MIN_TEXT_PHRASE_LEN: - continue - key = value.casefold() - if key in seen: - continue - seen.add(key) - cleaned.append(value) - return cleaned - - -def _text_match_clauses( - phrases: list[str], - *, - title_fields: tuple[str, ...], - abstract_field: str, -) -> list[dict[str, Any]]: - """Build title/abstract should-clauses with phrase boosts over loose match.""" - clauses: list[dict[str, Any]] = [] - for phrase in _normalize_text_phrases(phrases): - for field in title_fields: - clauses.append( - { - "match_phrase": { - field: { - "query": phrase, - "boost": _BOOST_TEXT_PHRASE_TITLE, - } - } - } - ) - clauses.append( - { - "match": { - field: { - "query": phrase, - "operator": "and", - "boost": _BOOST_TEXT_MATCH_TITLE, - } - } - } - ) - clauses.append( - { - "match_phrase": { - abstract_field: { - "query": phrase, - "boost": _BOOST_TEXT_PHRASE_ABSTRACT, - } - } - } - ) - clauses.append( - { - "match": { - abstract_field: { - "query": phrase, - "operator": "and", - "boost": _BOOST_TEXT_MATCH_ABSTRACT, - } - } - } - ) - return clauses - - class IpcPatentSearchQueries: def epo_query_by_ipc_terms( self, @@ -299,55 +222,3 @@ class IpcPatentSearchQueries: size: int = DEFAULT_SEARCH_SIZE, ) -> dict[str, Any]: return self.uspto_query_by_ipc_terms(_merge_term_boosts(symbols), size=size) - - def epo_query_by_text_phrases( - self, - phrases: list[str], - size: int = DEFAULT_SEARCH_SIZE, - ) -> dict[str, Any]: - should = _text_match_clauses( - phrases, - title_fields=("title_en", "title_de"), - abstract_field="abstract", - ) - query: dict[str, Any] = ( - {"match_none": {}} - if not should - else {"bool": {"should": should, "minimum_should_match": 1}} - ) - return { - "size": size, - "track_total_hits": True, - "sort": [ - {"_score": {"order": "desc"}}, - {"date_publication": {"order": "desc", "missing": "_last"}}, - ], - "_source": _PATENT_SOURCE_FIELDS, - "query": query, - } - - def uspto_query_by_text_phrases( - self, - phrases: list[str], - size: int = DEFAULT_SEARCH_SIZE, - ) -> dict[str, Any]: - should = _text_match_clauses( - phrases, - title_fields=("title",), - abstract_field="abstract", - ) - query: dict[str, Any] = ( - {"match_none": {}} - if not should - else {"bool": {"should": should, "minimum_should_match": 1}} - ) - return { - "size": size, - "track_total_hits": True, - "sort": [ - {"_score": {"order": "desc"}}, - {"publication_date": {"order": "desc", "missing": "_last"}}, - ], - "_source": _USPTO_SOURCE_FIELDS, - "query": query, - } diff --git a/service/src/main/inse/patents/keywords/test_logic.py b/service/src/main/inse/patents/keywords/test_logic.py index 4b48aaa4..5bcb3ffd 100644 --- a/service/src/main/inse/patents/keywords/test_logic.py +++ b/service/src/main/inse/patents/keywords/test_logic.py @@ -10,21 +10,17 @@ from inse.patents.authors.ipc_openalex_mapping import MappedOpenAlexTopic from inse.patents.common import model from inse.patents.keywords.logic import ( TopicEvidence, - _aggregate_subclass_clusters, - _collect_keyword_text_evidence, _compute_final_score, _compute_topic_evidence, - _exact_topic_or_subfield_match, _filter_keywords_for_patent_search, _ipc_hierarchy_quality, _keyword_is_patent_searchable, - _keyword_text_passes_relevance_gate, - _keyword_text_score, _patent_passes_relevance_gate, _patent_search_terms, _score_ipc_match, _score_patent, _select_dominant_clusters, + _aggregate_subclass_clusters, _term_from_ipc_match, _text_overlap_score, _text_search_terms, @@ -34,10 +30,6 @@ from inse.patents.keywords.logic import ( get_patents_by_keywords, select_ipc_matches_by_cluster_mass, ) -from inse.patents.keywords.model import ( - KeywordPatentSearchItem, - PatentsByKeywordsRequest, -) from inse.patents.keywords.reverse_lookup import ( IpcCodeMatch, _dedupe_ipc_matches, @@ -45,6 +37,7 @@ from inse.patents.keywords.reverse_lookup import ( _weighted_score, clear_reverse_lookup_caches, ) +from inse.patents.keywords.model import KeywordPatentSearchItem, PatentsByKeywordsRequest from inse.patents.keywords.search_queries import ( IpcPatentSearchQueries, _search_terms_for_symbol, @@ -646,132 +639,6 @@ def test_text_overlap_score_uses_word_boundaries_not_substrings() -> None: assert _text_overlap_score(patent, ["chemistry", "organic"]) == 0.0 -def test_fallback_rejects_mechanical_patent_for_organic_chemistry() -> None: - """Soft field / loose words must not accept a mechanical separator patent.""" - patent = model.PatentEntry( - patent_id="EP-MECH", - source="EPO", - title=( - "Rotating machine for separating materials in different " - "states of aggregation" - ), - abstract="Apparatus for mechanical separation of materials.", - ipc=["B01D45/12"], - ) - phrases = ["Organic Chemistry", "organische Chemie"] - terms = ["organic", "chemistry", "organische", "chemie"] - evidence = _collect_keyword_text_evidence(patent, phrases, terms) - - assert evidence.phrase_in_title is False - assert evidence.phrase_in_abstract is False - assert evidence.full_token_match is False - assert evidence.matched_phrases == [] - assert evidence.matched_words == [] - - field_only = TopicEvidence(match_kind="compatible_field", score=0.3) - assert not _keyword_text_passes_relevance_gate( - evidence, - topic_evidence=field_only, - ).accepted - exact = TopicEvidence(match_kind="topic_id", score=1.0) - assert not _keyword_text_passes_relevance_gate( - evidence, - topic_evidence=exact, - ).accepted - - -def test_fallback_accepts_strong_phrase_or_exact_topic_with_full_tokens() -> None: - phrase_patent = model.PatentEntry( - patent_id="EP-PHRASE", - source="EPO", - title="Process for organic chemistry synthesis", - abstract="Catalytic reactions.", - ) - phrases = ["organic chemistry"] - terms = ["organic", "chemistry"] - evidence = _collect_keyword_text_evidence(phrase_patent, phrases, terms) - assert evidence.phrase_in_title is True - assert evidence.text_match_kind == "phrase_title" - assert _keyword_text_score(evidence) == 1.0 - assert _keyword_text_passes_relevance_gate( - evidence, - topic_evidence=TopicEvidence(match_kind="none", score=0.0), - ).accepted - - full_token_patent = model.PatentEntry( - patent_id="EP-WORDS", - source="EPO", - title="Catalytic organic synthesis method", - abstract="Uses chemistry laboratory techniques.", - ) - full_evidence = _collect_keyword_text_evidence( - full_token_patent, - phrases, - terms, - ) - assert full_evidence.phrase_in_title is False - assert full_evidence.phrase_in_abstract is False - assert full_evidence.full_token_match is True - assert not _keyword_text_passes_relevance_gate( - full_evidence, - topic_evidence=TopicEvidence(match_kind="none", score=0.0), - ).accepted - assert _keyword_text_passes_relevance_gate( - full_evidence, - topic_evidence=TopicEvidence(match_kind="topic_id", score=1.0), - ).accepted - - partial_patent = model.PatentEntry( - patent_id="EP-PARTIAL", - source="EPO", - title="Organic polymer blend", - abstract="Industrial materials processing.", - ) - partial_evidence = _collect_keyword_text_evidence( - partial_patent, - phrases, - terms, - ) - assert partial_evidence.partial_token_match is True - assert partial_evidence.full_token_match is False - decision = _keyword_text_passes_relevance_gate( - partial_evidence, - topic_evidence=TopicEvidence(match_kind="topic_id", score=1.0), - ) - assert not decision.accepted - assert decision.reason == "exact_topic_with_partial_tokens_only" - - assert _exact_topic_or_subfield_match( - [ - MappedOpenAlexTopic( - topic_id="https://openalex.org/TORG", - topic_display_name="Organic Chemistry", - subfield_name="Organic Chemistry", - field_name="Chemistry", - ) - ], - frozenset({"TORG"}), - frozenset({"organic chemistry"}), - ) - - -def test_token_match_rejects_machine_inside_micromachined() -> None: - patent = model.PatentEntry( - patent_id="EP-MICRO", - source="EPO", - title="Micromachined sensor device", - abstract="Fabrication of micromachined structures.", - ) - assert _text_overlap_score(patent, ["machine", "learning"]) == 0.0 - evidence = _collect_keyword_text_evidence( - patent, - ["Machine Learning"], - ["machine", "learning"], - ) - assert evidence.matched_words == [] - assert evidence.full_token_match is False - - def test_patent_passes_relevance_gate_with_text_but_no_topics() -> None: patent = model.PatentEntry( patent_id="EP1", @@ -914,8 +781,7 @@ def test_get_patents_by_keywords_uses_symbol_queries() -> None: uspto_symbols.assert_called_once() assert epo_symbols.call_args.args[0][0] == "C07C243/08" assert "C07C" in epo_symbols.call_args.args[0] - # IPC search returns empty → text fallback also queries EPO/USPTO. - assert captured == ["epo", "uspto", "epo", "uspto"] + assert captured == ["epo", "uspto"] def test_text_search_terms_include_topic_metadata() -> None: @@ -993,64 +859,84 @@ def test_epo_and_uspto_queries_boost_specific_symbols_over_subclass() -> None: assert uspto["sort"][0] == {"_score": {"order": "desc"}} -def test_text_queries_prefer_phrase_match_in_title() -> None: - queries = IpcPatentSearchQueries() - epo = queries.epo_query_by_text_phrases(["organic chemistry"]) - uspto = queries.uspto_query_by_text_phrases(["organic chemistry"]) - - epo_should = epo["query"]["bool"]["should"] - uspto_should = uspto["query"]["bool"]["should"] - - def clause_boost(clauses: list[dict], kind: str, field: str) -> float | None: - for clause in clauses: - payload = clause.get(kind, {}).get(field) - if isinstance(payload, dict) and payload.get("query") == "organic chemistry": - return float(payload.get("boost", 1.0)) - return None - - assert clause_boost(epo_should, "match_phrase", "title_en") == 5.0 - assert clause_boost(epo_should, "match_phrase", "abstract") == 3.0 - assert clause_boost(epo_should, "match", "title_en") == 1.5 - assert clause_boost(uspto_should, "match_phrase", "title") == 5.0 - assert epo["sort"][0] == {"_score": {"order": "desc"}} - - -def test_uncertain_mapping_uses_text_fallback_not_empty_list() -> None: - """Fragmented IPC abstention must fall back to title/abstract search.""" - patent = model.PatentEntry( - patent_id="EP123", - source="EPO", - title="Process for organic chemistry synthesis", - abstract="A catalytic method in organic chemistry.", - publication_date="20240101", - ipc=["C07C243/08"], - cpc=[], +def test_technical_search_failure_returns_search_error_not_no_patents_found() -> None: + request = PatentsByKeywordsRequest( + keywords=[ + KeywordPatentSearchItem( + keyword="organische Chemie", + keyword_level="coarse", + topic_id="https://openalex.org/TORG", + topic_display_name="Organic Chemistry", + field_name="Chemistry", + relevance_score=1.0, + ) + ] ) + ipc_matches = [ + IpcCodeMatch( + "subgroup", + "C07C243/08", + 0.90, + "organische Chemie", + "topic", + "TORG", + ) + ] - async def fake_search_epo(query): - assert "match_phrase" in str(query) or "title_en" in str(query) - return { - "hits": { - "hits": [ - { - "_source": { - "doc_number": "123", - "country": "EP", - "kind": "A1", - "date_publication": "20240101", - "title_en": patent.title, - "abstract": patent.abstract, - "ipc": patent.ipc, - "cpc": [], - } - } - ] - } - } + with patch( + "inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes", + new=AsyncMock(return_value=ipc_matches), + ), patch( + "inse.patents.keywords.logic.BasePatentSearchClient.search_epo", + new=AsyncMock(side_effect=httpx.HTTPError("boom")), + ), patch( + "inse.patents.keywords.logic.BasePatentSearchClient.search_uspto", + new=AsyncMock(return_value={"hits": {"hits": []}}), + ): + response = asyncio.run(get_patents_by_keywords(request)) - async def fake_search_uspto(query): - return {"hits": {"hits": []}} + assert response.mapping_status == "search_error" + assert response.patent_count == 0 + +def test_no_ipc_search_terms_returns_without_text_fallback() -> None: + """Without usable IPC symbols the search abstains — no title/abstract path.""" + request = PatentsByKeywordsRequest( + keywords=[ + KeywordPatentSearchItem( + keyword="organische Chemie", + keyword_level="coarse", + topic_id="https://openalex.org/TORG", + topic_display_name="Organic Chemistry", + field_name="Chemistry", + relevance_score=1.0, + ) + ] + ) + search_epo = AsyncMock(return_value={"hits": {"hits": []}}) + search_uspto = AsyncMock(return_value={"hits": {"hits": []}}) + + with patch( + "inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes", + new=AsyncMock(return_value=[]), + ), patch( + "inse.patents.keywords.logic.BasePatentSearchClient.search_epo", + new=search_epo, + ), patch( + "inse.patents.keywords.logic.BasePatentSearchClient.search_uspto", + new=search_uspto, + ): + response = asyncio.run(get_patents_by_keywords(request)) + + assert response.mapping_status == "no_mapping" + assert response.patent_count == 0 + assert response.patents == [] + search_epo.assert_not_called() + search_uspto.assert_not_called() + + +def test_uncertain_ipc_cluster_abstention_returns_without_text_fallback() -> None: + """Fragmented IPC mapping abstains without falling back to text retrieval.""" fragmented = [ IpcCodeMatch( "subgroup", @@ -1074,113 +960,31 @@ def test_uncertain_mapping_uses_text_fallback_not_empty_list() -> None: ) ] ) + search_epo = AsyncMock(return_value={"hits": {"hits": []}}) with patch( "inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes", new=AsyncMock(return_value=fragmented), ), patch( "inse.patents.keywords.logic.BasePatentSearchClient.search_epo", - new=AsyncMock(side_effect=fake_search_epo), - ), patch( - "inse.patents.keywords.logic.BasePatentSearchClient.search_uspto", - new=AsyncMock(side_effect=fake_search_uspto), - ), patch( - "inse.patents.keywords.logic.PatentOpenAlexMappingResolver.resolve_topics_for_patents", - new=AsyncMock(return_value={}), - ), patch( - "inse.patents.keywords.logic.enrich_patents_classifications", - new=AsyncMock(), - ), patch.object( - IpcPatentSearchQueries, - "epo_query_by_text_phrases", - wraps=IpcPatentSearchQueries().epo_query_by_text_phrases, - ) as epo_text: - response = asyncio.run(get_patents_by_keywords(request)) - - epo_text.assert_called_once() - assert response.mapping_status == "uncertain" - assert response.patent_count == 1 - assert response.patents[0].text_retrieval is True - assert response.patents[0].ipc_score == 0.0 - assert response.patents[0].text_score > 0.0 - assert response.patents[0].matched_ipc_symbols == [] - assert response.patents[0].keyword_evidence is not None - assert response.patents[0].keyword_evidence.phrase_in_title is True - assert response.patents[0].keyword_evidence.text_match_kind == "phrase_title" - - -def test_text_fallback_empty_yields_no_patents_found() -> None: - request = PatentsByKeywordsRequest( - keywords=[ - KeywordPatentSearchItem( - keyword="organische Chemie", - keyword_level="coarse", - topic_id="https://openalex.org/TORG", - topic_display_name="Organic Chemistry", - field_name="Chemistry", - relevance_score=1.0, - ) - ] - ) - - with patch( - "inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes", - new=AsyncMock(return_value=[]), - ), patch( - "inse.patents.keywords.logic.BasePatentSearchClient.search_epo", - new=AsyncMock(return_value={"hits": {"hits": []}}), + new=search_epo, ), patch( "inse.patents.keywords.logic.BasePatentSearchClient.search_uspto", new=AsyncMock(return_value={"hits": {"hits": []}}), - ), patch( - "inse.patents.keywords.logic.PatentOpenAlexMappingResolver.resolve_topics_for_patents", - new=AsyncMock(return_value={}), - ), patch( - "inse.patents.keywords.logic.enrich_patents_classifications", - new=AsyncMock(), ): response = asyncio.run(get_patents_by_keywords(request)) - assert response.mapping_status == "no_patents_found" + assert response.mapping_status == "uncertain" assert response.patent_count == 0 assert response.patents == [] - - -def test_technical_search_failure_returns_search_error_not_no_patents_found() -> None: - request = PatentsByKeywordsRequest( - keywords=[ - KeywordPatentSearchItem( - keyword="organische Chemie", - keyword_level="coarse", - topic_id="https://openalex.org/TORG", - topic_display_name="Organic Chemistry", - field_name="Chemistry", - relevance_score=1.0, - ) - ] - ) - - with patch( - "inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes", - new=AsyncMock(return_value=[]), - ), patch( - "inse.patents.keywords.logic.BasePatentSearchClient.search_epo", - new=AsyncMock(side_effect=httpx.HTTPError("boom")), - ), patch( - "inse.patents.keywords.logic.BasePatentSearchClient.search_uspto", - new=AsyncMock(return_value={"hits": {"hits": []}}), - ): - response = asyncio.run(get_patents_by_keywords(request)) - - assert response.mapping_status == "search_error" - assert response.patent_count == 0 + search_epo.assert_not_called() def test_json_lookup_returns_empty_without_mapping(monkeypatch) -> None: clear_reverse_lookup_caches() monkeypatch.setattr( "inse.patents.keywords.reverse_lookup.load_patents_openalex_keywords_json", - dict, + lambda: {}, ) clear_reverse_lookup_caches() diff --git a/service/src/main/inse/projects/logic.py b/service/src/main/inse/projects/logic.py index 7a37ce66..ef96aec4 100644 --- a/service/src/main/inse/projects/logic.py +++ b/service/src/main/inse/projects/logic.py @@ -359,6 +359,53 @@ async def get_person_institutes( } return result +async def get_dfg_institutes_by_ids( + institute_ids: list[int], + ) -> dict[str, dict]: + + if not institute_ids: + return {} + + response = await elasticsearch.search( + index=ESIndex.DFG_INSTITUTES, + cluster=ESCluster.INSE, + body={ + "size": len(institute_ids), + "_source": [ + "institute_id", + "root_id", + "root_name_de", + "root_name_en", + "institute_name_de", + "institute_name_en", + "address_country_de", + "address_country_en", + ], + "query": { + "terms": { + "_id": institute_ids, + } + }, + }, + ) + + result = {} + + for hit in response["hits"]["hits"]: + source = hit["_source"] + + result[source["institute_id"]] = { + "institute_id": source["institute_id"], + "root_id": source.get("root_id"), + "root_name_de": source.get("root_name_de"), + "root_name_en": source.get("root_name_en"), + "institute_name_de": source.get("institute_name_de"), + "institute_name_en": source.get("institute_name_en"), + "address_country_de": source.get("address_country_de"), + "address_country_en": source.get("address_country_en"), + } + return result + #EU Cordis Projects diff --git a/service/src/main/inse/projects/model.py b/service/src/main/inse/projects/model.py index 64dbf6d5..64bfff41 100644 --- a/service/src/main/inse/projects/model.py +++ b/service/src/main/inse/projects/model.py @@ -250,12 +250,41 @@ class DfgProjectSummary(BaseModel): def from_hit(cls, hit: dict) -> "DfgProjectSummary": source = hit.get("_source", {}) fields = hit.get("fields", {}) - + names = [] institutions = {} project_persons = [] - persons = source.get("persons", []) + institutions_raw= source.get("institutions", []) + if isinstance(institutions_raw, list): + for institution in institutions_raw: + if not isinstance(institution, dict): + continue + + institute_id = institution.get("institute_id") + if institute_id is not None: + institutions[f"institute:{institute_id}"] = DfgInstitutionSummary( + id=institute_id, + institute_name_de=institution.get("institute_name_de"), + institute_name_en=institution.get("institute_name_en"), + address_country_de=institution.get("address_country_de"), + address_country_en=institution.get("address_country_en"), + root_id=institution.get("root_id"), + root_name_de=institution.get("root_name_de"), + root_name_en=institution.get("root_name_en"), + ) + root_id = institution.get("root_id") + if root_id is not None: + institutions[f"root:{root_id}"] = DfgInstitutionSummary( + id=root_id, + institute_name_de=institution.get("root_name_de"), + institute_name_en=institution.get("root_name_en"), + address_country_de=institution.get("address_country_de"), + address_country_en=institution.get("address_country_en"), + root_id=None, + root_name_de=None, + root_name_en=None, + ) if isinstance(persons, list): for person in persons: @@ -266,35 +295,35 @@ class DfgProjectSummary(BaseModel): if full_name: names.append(full_name.strip()) + # previously we were creating institution objects for each person, but now we are using the institutions from the institutions_raw list + #institution = None + # if person.get("institute_id") is not None: + # institute = DfgInstitutionSummary( + # id=person["institute_id"], + # institute_name_de=person.get("institute_name_de"), + # institute_name_en=person.get("institute_name_en"), + # address_country_de=person.get("address_country_de"), + # address_country_en=person.get("address_country_en"), + # root_id=None, + # root_name_de=None, + # root_name_en=None, + # ) - institution = None - if person.get("institute_id") is not None: - institute = DfgInstitutionSummary( - id=person["institute_id"], - institute_name_de=person.get("institute_name_de"), - institute_name_en=person.get("institute_name_en"), - address_country_de=person.get("address_country_de"), - address_country_en=person.get("address_country_en"), - root_id=None, - root_name_de=None, - root_name_en=None, - ) + # institutions[f"institute:{person['institute_id']}"] = institute - institutions[f"institute:{person['institute_id']}"] = institute + # if person.get("root_id") is not None: + # root_institution = DfgInstitutionSummary( + # id=person["root_id"], + # institute_name_de=person.get("root_name_de"), + # institute_name_en=person.get("root_name_en"), + # address_country_de=person.get("address_country_de"), + # address_country_en=person.get("address_country_en"), + # root_id=None, + # root_name_de=None, + # root_name_en=None, + # ) - if person.get("root_id") is not None: - root_institution = DfgInstitutionSummary( - id=person["root_id"], - institute_name_de=person.get("root_name_de"), - institute_name_en=person.get("root_name_en"), - address_country_de=person.get("address_country_de"), - address_country_en=person.get("address_country_en"), - root_id=None, - root_name_de=None, - root_name_en=None, - ) - - institutions[f"root:{person['root_id']}"] = root_institution + # institutions[f"root:{person['root_id']}"] = root_institution if person.get("person_id") is not None: project_persons.append( @@ -305,7 +334,7 @@ class DfgProjectSummary(BaseModel): full_name=full_name, role_label_en=person.get("role_label_en"), role_label_de=person.get("role_label_de"), - institution=institution, + institution=None, ) ) topics_raw = source.get("topics") or [] diff --git a/service/src/main/inse/projects/projects_search_client.py b/service/src/main/inse/projects/projects_search_client.py index 66fa8632..3b80b959 100644 --- a/service/src/main/inse/projects/projects_search_client.py +++ b/service/src/main/inse/projects/projects_search_client.py @@ -15,6 +15,7 @@ from inse.projects.logic import ( get_openalex_topics_for_bund_projects, get_openalex_topics_for_dfg_projects, get_person_ids_by_institution_ids, + get_dfg_institutes_by_ids, get_person_institutes, ) from inse.projects.model import ( @@ -412,6 +413,7 @@ async def search_dfg_projects( "subject_area_en", "persons", "subject_classifications", + "institutions", ], "query": {}, } @@ -523,34 +525,54 @@ async def search_dfg_projects( ) if not matching_institution_ids: return DfgProjectPage(elements=[], total=0, page=page, size=size) - matching_person_ids = await get_person_ids_by_institution_ids( - institution_ids=matching_institution_ids - ) + #previously we were filtering by person_ids, but now we are filtering by institution_ids directly + # matching_person_ids = await get_person_ids_by_institution_ids( + # institution_ids=matching_institution_ids + # ) + # must_clauses.append( + # { + # "nested": { + # "path": "persons", + # "query": {"terms": {"persons.person_id": matching_person_ids}}, + # } + # } + # ) must_clauses.append( { "nested": { - "path": "persons", - "query": {"terms": {"persons.person_id": matching_person_ids}}, + "path": "institutions", + "query": {"terms": {"institutions.institute_id": matching_institution_ids}}, } } ) + print("MATCHING_INSTITUTION_IDS", matching_institution_ids) if institution_ids: - matching_person_ids = await get_person_ids_by_institution_ids( - institution_ids=institution_ids - ) + #prevously we were filtering by person_ids, but now we are filtering by institution_ids directly + # matching_person_ids = await get_person_ids_by_institution_ids( + # institution_ids=institution_ids + # ) - if not matching_person_ids: - return DfgProjectPage(elements=[], total=0, page=page, size=size) + # if not matching_person_ids: + # return DfgProjectPage(elements=[], total=0, page=page, size=size) + # must_clauses.append( + # { + # "nested": { + # "path": "persons", + # "query": {"terms": {"persons.person_id": matching_person_ids}}, + # } + # } + # ) must_clauses.append( { "nested": { - "path": "persons", - "query": {"terms": {"persons.person_id": matching_person_ids}}, + "path": "institutions", + "query": {"terms": {"institutions.institute_id": institution_ids}}, } } ) + body["query"] = ( {"bool": {"must": must_clauses}} if must_clauses else {"match_all": {}} @@ -577,6 +599,7 @@ async def search_dfg_projects( body["sort"] = [sort_config] # print(f"Executing DFG project search with body: {json.dumps(body, indent=2)}") # === Execute Search === + print(f"Executing DFG project search with body: {json.dumps(body, indent=2)}") response = await elasticsearch.search( index=ESIndex.DFG_PROJECTS, body=body, @@ -603,21 +626,28 @@ async def search_dfg_projects( source = hit["_source"] project_id = source["id"] source["topics"] = topic_lookup.get(str(project_id), []) + institutions = source.get("institutions", []) + for institution in institutions: + institute_id = institution.get("institute_id") + if institute_id is not None: + institute_info = await get_dfg_institutes_by_ids(institute_ids=[institute_id]) + if institute_info: + institution.update(institute_info[institute_id]) persons = source.get("persons", []) for person in persons: person_id = person.get("person_id") institute = person_lookup.get(person_id) - if institute: - person["root_id"] = institute.get("root_id") - person["institute_id"] = institute.get("institute_id") - person["root_name_de"] = institute.get("root_name_de") - person["root_name_en"] = institute.get("root_name_en") - person["institute_name_de"] = institute.get("institute_name_de") - person["institute_name_en"] = institute.get("institute_name_en") - person["address_country_de"] = institute.get("address_country_de") - person["address_country_en"] = institute.get("address_country_en") - + # if institute: + # person["root_id"] = institute.get("root_id") + # person["institute_id"] = institute.get("institute_id") + # person["root_name_de"] = institute.get("root_name_de") + # person["root_name_en"] = institute.get("root_name_en") + # person["institute_name_de"] = institute.get("institute_name_de") + # person["institute_name_en"] = institute.get("institute_name_en") + # person["address_country_de"] = institute.get("address_country_de") + # person["address_country_en"] = institute.get("address_country_en") + print("ENRIECHED",source.get("institutions", [])) return _complete_response_to_dfg_project_page(response, page, size) def _complete_response_to_dfg_project_page( diff --git a/service/src/main/inse/works/v2/router.py b/service/src/main/inse/works/v2/router.py index 87596cdd..13446ecd 100644 --- a/service/src/main/inse/works/v2/router.py +++ b/service/src/main/inse/works/v2/router.py @@ -24,7 +24,7 @@ router = APIRouter(prefix=RouterPrefixes.WORKS_V2, tags=[Tags.WORKS_V2]) @router.get( - "/{raw_oa_work_id}", + "/single/{raw_oa_work_id}", operation_id="getWorkById", summary="Returns a work based on its ID.", ) diff --git a/webapp/src/app/api/api/auth.service.ts b/webapp/src/app/api/api/auth.service.ts index a906d12f..a53f4427 100644 --- a/webapp/src/app/api/api/auth.service.ts +++ b/webapp/src/app/api/api/auth.service.ts @@ -65,6 +65,71 @@ export class AuthService extends BaseService { super(basePath, configuration); } + /** + * Check if user can fetch GDPR-relevant data + * Check if the authenticated user can fetch GDPR-relevant data for a given author and institution. + * @endpoint get /api/auth/v2/can-fetch-gdpr-relevant-data + * @param rawOaAuthorId OpenAlex author ID to check access for + * @param rawOaInstitutionId OpenAlex institution ID to check access for + * @param secureFgpAcc + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public canFetchGdprRelevantData(rawOaAuthorId?: string, rawOaInstitutionId?: string, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public canFetchGdprRelevantData(rawOaAuthorId?: string, rawOaInstitutionId?: string, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public canFetchGdprRelevantData(rawOaAuthorId?: string, rawOaInstitutionId?: string, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public canFetchGdprRelevantData(rawOaAuthorId?: string, rawOaInstitutionId?: string, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + rawOaAuthorId, 'raw_oa_author_id'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + rawOaInstitutionId, 'raw_oa_institution_id'); + + let localVarHeaders = this.defaultHeaders; + + // authentication (HTTPBearer) required + localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer '); + + 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/auth/v2/can-fetch-gdpr-relevant-data`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + /** * Change Password * Change the user\'s password and invalidate existing tokens. diff --git a/webapp/src/app/api/api/worksV2.service.ts b/webapp/src/app/api/api/worksV2.service.ts index 5e4801f2..9b8dc65d 100644 --- a/webapp/src/app/api/api/worksV2.service.ts +++ b/webapp/src/app/api/api/worksV2.service.ts @@ -511,7 +511,7 @@ export class WorksV2Service extends BaseService { /** * Returns a work based on its ID. - * @endpoint get /api/works/v2/{raw_oa_work_id} + * @endpoint get /api/works/v2/single/{raw_oa_work_id} * @param rawOaWorkId The raw OpenAlex work id. * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. @@ -549,7 +549,7 @@ export class WorksV2Service extends BaseService { } } - let localVarPath = `/api/works/v2/${this.configuration.encodeParam({name: "rawOaWorkId", value: rawOaWorkId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + let localVarPath = `/api/works/v2/single/${this.configuration.encodeParam({name: "rawOaWorkId", value: rawOaWorkId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; const { basePath, withCredentials } = this.configuration; return this.httpClient.request('get', `${basePath}${localVarPath}`, { diff --git a/webapp/src/app/api/model/dfgProjectDetails.ts b/webapp/src/app/api/model/dfgProjectDetails.ts index f3846507..07bcced0 100644 --- a/webapp/src/app/api/model/dfgProjectDetails.ts +++ b/webapp/src/app/api/model/dfgProjectDetails.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -14,69 +14,71 @@ import { DFGProjectFachgebieteInner } from './dFGProjectFachgebieteInner'; import { Topic } from './topic'; import { DfgProjectPublicationSummary } from './dfgProjectPublicationSummary'; + /** * Clean, enriched summary model for a DFG project. */ -export interface DfgProjectDetails { - id?: number | null; - link?: string | null; - page_url?: string | null; - external_link?: string | null; - title_de?: string | null; - title_en?: string | null; - description_de?: string | null; - description_en?: string | null; - final_report_abstract_de?: string | null; - final_report_abstract_en?: string | null; - project_identifier_de?: string | null; - project_identifier_en?: string | null; - funding_start?: number | null; - funding_end?: number | null; - funding_period_de?: string | null; - funding_period_en?: string | null; - funding_type_de?: string | null; - funding_type_en?: string | null; - funding_type_key?: string | null; - dfg_procedure?: string | null; - is_transfer_project?: boolean | null; - website_html_de?: string | null; - website_html_en?: string | null; - equipment_group?: string | null; - equipment_name?: string | null; - subject_area_de?: string | null; - subject_area_en?: string | null; - /** - * Detailed DFG subject-area classification entries (Fachsystematik) - */ - subject_classifications?: Array; - international_relation_de?: string | null; - international_relation_en?: string | null; - /** - * All persons associated with the project, each with their role - */ - persons?: Array; - /** - * All institutions associated with the project, each with their role - */ - institutions?: Array; - /** - * Flat, de-duplicated list of all person full names (convenience view) - */ - associated_persons?: Array; - /** - * Flat, de-duplicated list of all institution names (convenience view) - */ - associated_institutions?: Array; - parent_project_id?: number | null; - parent_title_de?: string | null; - parent_title_en?: string | null; - /** - * Sub-projects of this project, if any - */ - subprojects?: Array; - /** - * Publications resulting from the project - */ - publications?: Array; - topics?: Array | null; +export interface DfgProjectDetails { + id?: number | null; + link?: string | null; + page_url?: string | null; + external_link?: string | null; + title_de?: string | null; + title_en?: string | null; + description_de?: string | null; + description_en?: string | null; + final_report_abstract_de?: string | null; + final_report_abstract_en?: string | null; + project_identifier_de?: string | null; + project_identifier_en?: string | null; + funding_start?: number | null; + funding_end?: number | null; + funding_period_de?: string | null; + funding_period_en?: string | null; + funding_type_de?: string | null; + funding_type_en?: string | null; + funding_type_key?: string | null; + dfg_procedure?: string | null; + is_transfer_project?: boolean | null; + website_html_de?: string | null; + website_html_en?: string | null; + equipment_group?: string | null; + equipment_name?: string | null; + subject_area_de?: string | null; + subject_area_en?: string | null; + /** + * Detailed DFG subject-area classification entries (Fachsystematik) + */ + subject_classifications?: Array; + international_relation_de?: string | null; + international_relation_en?: string | null; + /** + * All persons associated with the project, each with their role + */ + persons?: Array; + /** + * All institutions associated with the project, each with their role + */ + institutions?: Array; + /** + * Flat, de-duplicated list of all person full names (convenience view) + */ + associated_persons?: Array; + /** + * Flat, de-duplicated list of all institution names (convenience view) + */ + associated_institutions?: Array; + parent_project_id?: number | null; + parent_title_de?: string | null; + parent_title_en?: string | null; + /** + * Sub-projects of this project, if any + */ + subprojects?: Array; + /** + * Publications resulting from the project + */ + publications?: Array; + topics?: Array | null; } + diff --git a/webapp/src/app/api/model/dfgProjectKeyword.ts b/webapp/src/app/api/model/dfgProjectKeyword.ts index f81b6ad4..2e898f1c 100644 --- a/webapp/src/app/api/model/dfgProjectKeyword.ts +++ b/webapp/src/app/api/model/dfgProjectKeyword.ts @@ -1,14 +1,16 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ -export interface DfgProjectKeyword { - name: string; - project_count: number; + +export interface DfgProjectKeyword { + name: string; + project_count: number; } + diff --git a/webapp/src/app/api/model/dfgProjectTopic.ts b/webapp/src/app/api/model/dfgProjectTopic.ts index ca22eb28..4b99c034 100644 --- a/webapp/src/app/api/model/dfgProjectTopic.ts +++ b/webapp/src/app/api/model/dfgProjectTopic.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,12 +9,14 @@ */ import { DfgProjectKeyword } from './dfgProjectKeyword'; -export interface DfgProjectTopic { - id: string; - name: string; - subfield?: string | null; - field?: string | null; - domain?: string | null; - project_count: number; - keywords: Array; + +export interface DfgProjectTopic { + id: string; + name: string; + subfield?: string | null; + field?: string | null; + domain?: string | null; + project_count: number; + keywords: Array; } + diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index d193f63e..40deb417 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -6,7 +6,6 @@ import { personPatentsResolver } from './resolvers/person-patents.resolver'; import { personResolver } from './resolvers/person.resolver'; import { personNewsResolver } from './resolvers/person-news.resolver'; import { institutionResolver } from './resolvers/institution.resolver'; -import { bundProjectPageResolver } from './resolvers/bund-project-page.resolver'; import { dfgProjectsResolver, RESOLVING_PROJECT_PAGE_FOR, @@ -65,6 +64,7 @@ import { topicQueryParamKeys, } from './resolvers/topic-page.resolver'; import { topicResolver } from './resolvers/topic.resolver'; +import { canFetchGdprRelevantDataResolver } from './resolvers/can-fetch-gdpr-relevant-data.resolver'; export const routes: Routes = [ { path: '', @@ -493,6 +493,7 @@ export const routes: Routes = [ personData: personResolver, personBio: personBioResolver, personPatents: personPatentsResolver, + canFetchGdprRelevantData: canFetchGdprRelevantDataResolver, }, runGuardsAndResolvers: (from, to) => from.params['id'] !== to.params['id'], children: [ @@ -658,16 +659,12 @@ export const routes: Routes = [ import('./modules/institution/institution.component').then( (mod) => mod.InstitutionComponent, ), - resolve: { institution: institutionResolver }, + resolve: { + institution: institutionResolver, + canFetchGdprRelevantData: canFetchGdprRelevantDataResolver, + }, children: [ - { path: '', pathMatch: 'full', redirectTo: 'overview' }, - { - path: 'overview', - loadComponent: () => - import('./modules/institution-overview/institution-overview.component').then( - (mod) => mod.InstitutionOverviewComponent, - ), - }, + { path: '', pathMatch: 'full', redirectTo: 'publications' }, { path: 'publications', loadComponent: () => diff --git a/webapp/src/app/modules/institution-overview/institution-overview.component.html b/webapp/src/app/modules/institution-overview/institution-overview.component.html deleted file mode 100644 index 486e08e8..00000000 --- a/webapp/src/app/modules/institution-overview/institution-overview.component.html +++ /dev/null @@ -1 +0,0 @@ -

institution-overview works!

diff --git a/webapp/src/app/modules/institution-overview/institution-overview.component.scss b/webapp/src/app/modules/institution-overview/institution-overview.component.scss deleted file mode 100644 index e69de29b..00000000 diff --git a/webapp/src/app/modules/institution-overview/institution-overview.component.spec.ts b/webapp/src/app/modules/institution-overview/institution-overview.component.spec.ts deleted file mode 100644 index 2926265e..00000000 --- a/webapp/src/app/modules/institution-overview/institution-overview.component.spec.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { ComponentFixture, TestBed } from '@angular/core/testing'; - -import { InstitutionOverviewComponent } from './institution-overview.component'; - -describe('InstitutionOverviewComponent', () => { - let component: InstitutionOverviewComponent; - let fixture: ComponentFixture; - - beforeEach(async () => { - await TestBed.configureTestingModule({ - imports: [InstitutionOverviewComponent], - }).compileComponents(); - - fixture = TestBed.createComponent(InstitutionOverviewComponent); - component = fixture.componentInstance; - fixture.detectChanges(); - }); - - it('should create', () => { - expect(component).toBeTruthy(); - }); -}); diff --git a/webapp/src/app/modules/institution-overview/institution-overview.component.ts b/webapp/src/app/modules/institution-overview/institution-overview.component.ts deleted file mode 100644 index 13b18fa4..00000000 --- a/webapp/src/app/modules/institution-overview/institution-overview.component.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { Component } from '@angular/core'; - -@Component({ - selector: 'app-institution-overview', - imports: [], - templateUrl: './institution-overview.component.html', - styleUrl: './institution-overview.component.scss', -}) -export class InstitutionOverviewComponent {} diff --git a/webapp/src/app/modules/institution-patents/institution-patents.component.html b/webapp/src/app/modules/institution-patents/institution-patents.component.html index 6524e69f..290cf522 100644 --- a/webapp/src/app/modules/institution-patents/institution-patents.component.html +++ b/webapp/src/app/modules/institution-patents/institution-patents.component.html @@ -103,24 +103,29 @@ {{ getMatchTypeLabel(patent) }} - - @if ( - patent.matched_authors && patent.matched_authors.length - ) { - @for ( - author of patent.matched_authors.slice(0, 2); - track author.openalex_author_id + +
+ @if ( + patent.matched_authors && patent.matched_authors.length ) { - - {{ author.author_name }} - + @for ( + author of patent.matched_authors.slice(0, 2); + track author.openalex_author_id + ) { + + {{ author.author_name }} + + } + } @else { + - } - } @else { - - - } +
} diff --git a/webapp/src/app/modules/institution-patents/institution-patents.component.scss b/webapp/src/app/modules/institution-patents/institution-patents.component.scss index e52f8265..4b3fdb39 100644 --- a/webapp/src/app/modules/institution-patents/institution-patents.component.scss +++ b/webapp/src/app/modules/institution-patents/institution-patents.component.scss @@ -60,21 +60,14 @@ app-query-param-paginator { table { width: 100%; - border-collapse: separate; - border-spacing: 0; - border: 1px solid var(--sg-border); - border-radius: var(--sg-radius-sm); - overflow: hidden; + border-collapse: collapse; th { text-align: left; padding: 12px 16px; - background: var(--sg-surface-muted); border-bottom: 1px solid var(--sg-border); - font-size: 12px; - font-weight: 700; - text-transform: uppercase; - letter-spacing: 0.02em; + font-size: 13px; + font-weight: 600; color: var(--sg-text-muted); } @@ -90,10 +83,6 @@ app-query-param-paginator { &.selected td { background: var(--sg-primary-soft); } - - &:last-child td { - border-bottom: 0; - } } td { @@ -107,10 +96,9 @@ app-query-param-paginator { .patent-title { color: var(--sg-text); font-weight: 600; - max-width: 280px; - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; + max-width: 320px; + white-space: normal; + word-break: break-word; } .cell-preview { diff --git a/webapp/src/app/modules/institution/institution.component.html b/webapp/src/app/modules/institution/institution.component.html index 2024c855..ef072421 100644 --- a/webapp/src/app/modules/institution/institution.component.html +++ b/webapp/src/app/modules/institution/institution.component.html @@ -1,15 +1,15 @@
-

{{ institution.display_name }}

+

{{ institution().display_name }}

-

{{ institution.homepage_url }}

-

{{ institution.display_name_alternatives }}

+

{{ institution().homepage_url }}

+

{{ institution().display_name_alternatives }}

And many more useful details...