1189 lines
42 KiB
Python
1189 lines
42 KiB
Python
import datetime
|
|
from datetime import date
|
|
from enum import StrEnum
|
|
from typing import Any
|
|
|
|
from inse.authors.v2.model import AuthorPage
|
|
from inse.model import ESIndex
|
|
from inse.models.bund_project import BundProject
|
|
from inse.models.eu_project import EuProject
|
|
from inse.models.openalex.topic import Topic, TopicDomain, TopicField, TopicSubfield
|
|
from inse.models.projects_dfg_v2.project.dfg_project_fachgebiete_inner import (
|
|
DFGProjectFachgebieteInner,
|
|
)
|
|
from inse.models.projects_eu_cordis.fp7.fp7_project_details import Fp7ProjectDetails
|
|
from inse.models.projects_eu_cordis.horizon2020.h2020_project_details import (
|
|
H2020ProjectDetails,
|
|
)
|
|
from inse.models.projects_eu_cordis.horizon_europe.heu_project_details import (
|
|
HEUProjectDetails,
|
|
)
|
|
from inse.projects.bund_institutions.model import BundInstitutionSummary
|
|
from pydantic import BaseModel, Field, field_validator
|
|
|
|
|
|
class ProjectType(StrEnum):
|
|
BUND = "bund"
|
|
EU = "eu"
|
|
DFG = "dfg"
|
|
|
|
def to_es_index(self) -> ESIndex:
|
|
mapping = {
|
|
self.BUND: ESIndex.PROJECTS_BUND_V1,
|
|
self.EU: ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
|
|
self.DFG: ESIndex.DFG_PROJECTS,
|
|
}
|
|
index = mapping.get(self)
|
|
if index is None:
|
|
raise ValueError(f"Unsupported project type: {self}")
|
|
return index
|
|
|
|
|
|
class ProjectsSortBy(StrEnum):
|
|
TITLE = "title"
|
|
FUNDING_START = "funding_start"
|
|
FUNDING_END = "funding_end"
|
|
FUNDING_AMOUNT = "funding_amount"
|
|
|
|
def to_cordis_eu_project_sort_field(self) -> str:
|
|
mapping = {
|
|
self.TITLE: "title.keyword",
|
|
self.FUNDING_START: "startDate",
|
|
self.FUNDING_END: "endDate",
|
|
self.FUNDING_AMOUNT: "ecMaxContribution",
|
|
}
|
|
return mapping.get(self, "title.keyword")
|
|
|
|
def to_bund_project_sort_field(self) -> str:
|
|
mapping = {
|
|
self.TITLE: "Thema.keyword",
|
|
self.FUNDING_START: "funding_start",
|
|
self.FUNDING_END: "funding_end",
|
|
self.FUNDING_AMOUNT: "Fördersumme",
|
|
}
|
|
return mapping.get(self, "Thema.keyword")
|
|
|
|
|
|
class SortDirection(StrEnum):
|
|
ASC = "asc"
|
|
DESC = "desc"
|
|
|
|
|
|
class Page(BaseModel):
|
|
page: int = Field(default=0, description="The current page number.")
|
|
size: int = Field(default=20, description="The requested page size.")
|
|
total: int = Field(default=0, description="The total number of items.")
|
|
class BundProjectHighlight(BaseModel):
|
|
"""Highlighted matching fragments from a BUND project search."""
|
|
|
|
joint_project: list[str] = Field(
|
|
default_factory=list,
|
|
description='Highlights from the Elasticsearch field "Verbundprojekt".',
|
|
)
|
|
topic: list[str] = Field(
|
|
default_factory=list,
|
|
description='Highlights from the Elasticsearch field "Thema".',
|
|
)
|
|
recipient: list[str] = Field(
|
|
default_factory=list,
|
|
description='Highlights from the Elasticsearch field "Zuwendungsempfänger".',
|
|
)
|
|
executing_agency: list[str] = Field(
|
|
default_factory=list,
|
|
description='Highlights from the Elasticsearch field "Ausführende Stelle".',
|
|
)
|
|
class BundProjectSummary(BundProject):
|
|
oa_topics: list[Topic] | None = Field(
|
|
default=None,
|
|
validation_alias="oa_topics",
|
|
description="The OpenAlex topics of the project",
|
|
examples=[["Artificial Intelligence", "Machine Learning"]],
|
|
)
|
|
institution: BundInstitutionSummary | None = Field(
|
|
default=None,
|
|
description="The executing agency / recipient institution for this project, "
|
|
"derived from the project's own agency fields.",
|
|
)
|
|
highlight: BundProjectHighlight | None = Field(
|
|
default=None,
|
|
description="Highlighted matching fragments from the project search.",
|
|
)
|
|
|
|
@classmethod
|
|
def from_hit(cls, hit: dict[str, Any]) -> "BundProjectSummary":
|
|
"""Create a BundProjectSummary from an Elasticsearch hit."""
|
|
|
|
source = hit.get("_source", {})
|
|
|
|
topics_raw = source.get("oa_topics") or []
|
|
oa_topics = None
|
|
|
|
if isinstance(topics_raw, list) and topics_raw:
|
|
sorted_topics_raw = sorted(
|
|
(topic for topic in topics_raw if isinstance(topic, dict)),
|
|
key=lambda topic: (
|
|
topic.get("rank")
|
|
if topic.get("rank") is not None
|
|
else float("inf")
|
|
),
|
|
)
|
|
oa_topics = [
|
|
cls._topic_from_match(topic)
|
|
for topic in sorted_topics_raw
|
|
]
|
|
|
|
return cls(
|
|
funding_code=source.get("Förderkennzeichen"),
|
|
department=source.get("Ressort"),
|
|
department_fullname=source.get("Ressort_fullname"),
|
|
referat=source.get("Referat"),
|
|
project_sponsor=source.get("Projektträger"),
|
|
project_sponsor_fullname=source.get("Projektträger_fullname"),
|
|
work_unit=source.get("Arb.-Einh."),
|
|
recipient=source.get("Zuwendungsempfänger"),
|
|
municipal_code=source.get("Gemeindekennziffer"),
|
|
municipality=source.get("Stadt/Gemeinde"),
|
|
place=source.get("Ort"),
|
|
state=source.get("Bundesland"),
|
|
country=source.get("Staat"),
|
|
executing_agency=source.get("Ausführende Stelle"),
|
|
topic=source.get("Thema"),
|
|
performance_plan_system=source.get("Leistungsplansystematik"),
|
|
performance_plan_system_text=source.get(
|
|
"Klartext Leistungsplansystematik"
|
|
),
|
|
funding_start=source.get("funding_start"),
|
|
funding_end=source.get("funding_end"),
|
|
grant_amount=source.get("Fördersumme"),
|
|
funding_profile=source.get("Förderprofil"),
|
|
joint_project=source.get("Verbundprojekt"),
|
|
funding_type=source.get("Förderart"),
|
|
publication_date=source.get("Publikationsdatum"),
|
|
unix_timestamp=source.get("Unix-Timestamp"),
|
|
date=source.get("datum"),
|
|
new=source.get("neu"),
|
|
duration=source.get("Laufzeit"),
|
|
oa_topics=oa_topics,
|
|
institution=BundInstitutionSummary.from_source(source),
|
|
highlight=cls._highlight_from_hit(hit),
|
|
)
|
|
@staticmethod
|
|
def _highlight_fragments(value: Any) -> list[str]:
|
|
"""Normalize an Elasticsearch highlight value to a list of strings."""
|
|
|
|
if isinstance(value, str):
|
|
return [value]
|
|
|
|
if isinstance(value, list):
|
|
return [
|
|
fragment
|
|
for fragment in value
|
|
if isinstance(fragment, str)
|
|
]
|
|
|
|
return []
|
|
|
|
|
|
@classmethod
|
|
def _highlight_from_hit(
|
|
cls,
|
|
hit: dict[str, Any],
|
|
) -> BundProjectHighlight | None:
|
|
"""Extract BUND project highlights from an Elasticsearch hit."""
|
|
|
|
raw_highlight = hit.get("highlight")
|
|
if not isinstance(raw_highlight, dict):
|
|
return None
|
|
|
|
highlight = BundProjectHighlight(
|
|
joint_project=cls._highlight_fragments(
|
|
raw_highlight.get("Verbundprojekt")
|
|
),
|
|
topic=cls._highlight_fragments(
|
|
raw_highlight.get("Thema")
|
|
),
|
|
recipient=cls._highlight_fragments(
|
|
raw_highlight.get("Zuwendungsempfänger")
|
|
),
|
|
executing_agency=cls._highlight_fragments(
|
|
raw_highlight.get("Ausführende Stelle")
|
|
),
|
|
)
|
|
|
|
has_highlights = any(
|
|
(
|
|
highlight.joint_project,
|
|
highlight.topic,
|
|
highlight.recipient,
|
|
highlight.executing_agency,
|
|
)
|
|
)
|
|
|
|
return highlight if has_highlights else None
|
|
@staticmethod
|
|
def _topic_from_match(match: dict[str, Any]) -> Topic:
|
|
"""Builds a Topic model from a flattened topic_match dict.
|
|
|
|
Same logic as DfgProjectSummary._topic_from_match and EuCordisProjectSummary.topic_from_match
|
|
"""
|
|
domain_name = match.get("domain")
|
|
field_name = match.get("field")
|
|
subfield_name = match.get("subfield")
|
|
|
|
domain = TopicDomain(display_name=domain_name) if domain_name else None
|
|
field = TopicField(display_name=field_name) if field_name else None
|
|
subfield = TopicSubfield(display_name=subfield_name) if subfield_name else None
|
|
|
|
return Topic(
|
|
id=match.get("topic_id"),
|
|
display_name=match.get("topic_display_name"),
|
|
domain=domain,
|
|
field=field,
|
|
subfield=subfield,
|
|
)
|
|
|
|
|
|
class BundProjectPage(Page):
|
|
elements: list[BundProjectSummary] = Field(
|
|
default_factory=list, description="The bund projects on this page."
|
|
)
|
|
|
|
class BundProjectList(BaseModel):
|
|
elements: list[BundProjectSummary] = Field(
|
|
default_factory=list, description="All bund projects."
|
|
)
|
|
total: int = Field(default=0, description="The total number of bund projects.")
|
|
class DfgSubjectClassificationHighlight(BaseModel):
|
|
"""A highlighted nested subject classification."""
|
|
|
|
query: str = Field(
|
|
description="The keyword/inner_hits group which produced this match.",
|
|
)
|
|
|
|
offset: int | None = Field(
|
|
default=None,
|
|
description="Index of the matched item in subject_classifications.",
|
|
)
|
|
|
|
fach: list[str] = Field(default_factory=list)
|
|
fachkollegium: list[str] = Field(default_factory=list)
|
|
fachgebiet: list[str] = Field(default_factory=list)
|
|
fachgebiet_de: list[str] = Field(default_factory=list)
|
|
wissenschaftsbereich: list[str] = Field(default_factory=list)
|
|
|
|
|
|
class DfgProjectHighlight(BaseModel):
|
|
"""Highlighted fragments returned for a DFG project."""
|
|
|
|
title_de: list[str] = Field(default_factory=list)
|
|
title_en: list[str] = Field(default_factory=list)
|
|
|
|
abstract_de: list[str] = Field(default_factory=list)
|
|
abstract_en: list[str] = Field(default_factory=list)
|
|
|
|
subject_classifications: list[DfgSubjectClassificationHighlight] = Field(
|
|
default_factory=list,
|
|
)
|
|
class DfgInstitutionSummary(BaseModel):
|
|
"""A summary of a DFG institution."""
|
|
id: int
|
|
institute_name_de: str | None = None
|
|
institute_name_en: str | None = None
|
|
root_id: int | None = None
|
|
root_name_de: str | None = None
|
|
root_name_en: str | None = None
|
|
address_country_de: str | None = None
|
|
address_country_en: str | None = None
|
|
|
|
class DfgPersonSummary(BaseModel):
|
|
person_id: int
|
|
orcid_id: str | None = None
|
|
project_ref_id: int | None = None
|
|
full_name: str | None = None
|
|
role_label_en: str | None = None,
|
|
role_label_de: str | None = None,
|
|
institution: DfgInstitutionSummary | None = None
|
|
|
|
|
|
|
|
class DfgProjectSummary(BaseModel):
|
|
id: str = Field(
|
|
description="The unique identifier of the DFG project."
|
|
)
|
|
|
|
link: str | None = Field(
|
|
default=None,
|
|
description="The link to the DFG project details."
|
|
)
|
|
|
|
title_de: str | None = Field(
|
|
default=None,
|
|
description="The title of the DFG project in German."
|
|
)
|
|
|
|
title_en: str | None = Field(
|
|
default=None,
|
|
description="The title of the DFG project in English."
|
|
)
|
|
|
|
subject_classifications_raw: str | None = Field(
|
|
default=None,
|
|
description="The subject classifications of the DFG project."
|
|
)
|
|
abstract_de: str | None = Field( default=None, description="The abstract of the DFG project in German.")
|
|
abstract_en: str | None = Field( default=None, description="The abstract of the DFG project in English.")
|
|
|
|
funding_start: str | None = Field(
|
|
default=None,
|
|
description="The funding start date of the DFG project."
|
|
)
|
|
|
|
funding_end: str | None = Field(
|
|
default=None,
|
|
description="The funding end date of the DFG project."
|
|
)
|
|
|
|
institutions: list[DfgInstitutionSummary] = Field(
|
|
default_factory=list,
|
|
description="Institutions associated with the project."
|
|
)
|
|
names: list[str] = Field(
|
|
default_factory=list,
|
|
description="The names of the persons involved in the DFG project.",
|
|
)
|
|
persons: list[DfgPersonSummary] = Field(
|
|
default_factory=list,
|
|
description="The persons involved in the DFG project.",
|
|
)
|
|
subject_classifications: list[DFGProjectFachgebieteInner] | None = Field(
|
|
default=None,
|
|
description="The subject classifications of the DFG project.",
|
|
)
|
|
topics: list[Topic] | None = Field(
|
|
default=None,
|
|
description="The topics associated with the DFG project.",
|
|
)
|
|
highlight: DfgProjectHighlight | None = Field(
|
|
default=None,
|
|
description="Highlighted matching fragments.",
|
|
)
|
|
@classmethod
|
|
def from_hit(cls, hit: dict) -> "DfgProjectSummary":
|
|
source = hit.get("_source", {})
|
|
|
|
source_id = source.get("id")
|
|
project_id = source_id if source_id is not None else hit.get("_id", "")
|
|
|
|
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:
|
|
if not isinstance(person, dict):
|
|
continue
|
|
|
|
full_name = person.get("full_name")
|
|
|
|
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,
|
|
# )
|
|
|
|
# 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,
|
|
# )
|
|
|
|
# institutions[f"root:{person['root_id']}"] = root_institution
|
|
|
|
if person.get("person_id") is not None:
|
|
project_persons.append(
|
|
DfgPersonSummary(
|
|
person_id=person["person_id"],
|
|
project_ref_id=person.get("project_ref_id"),
|
|
orcid_id=person.get("orcid_id"),
|
|
full_name=full_name,
|
|
role_label_en=person.get("role_label_en"),
|
|
role_label_de=person.get("role_label_de"),
|
|
institution=None,
|
|
)
|
|
)
|
|
topics_raw = source.get("topics") or []
|
|
topics = None
|
|
if isinstance(topics_raw, list) and topics_raw:
|
|
# Sort by rank if present, so the most relevant topic comes first
|
|
sorted_topics_raw = sorted(
|
|
(t for t in topics_raw if isinstance(t, dict)),
|
|
key=lambda t: t.get("rank") if t.get("rank") is not None else float("inf"),
|
|
)
|
|
topics = [cls._topic_from_match(t) for t in sorted_topics_raw]
|
|
|
|
|
|
subject_classifications = source.get("subject_classifications")
|
|
if not isinstance(subject_classifications, list):
|
|
subject_classifications = []
|
|
|
|
return cls(
|
|
id=str(project_id),
|
|
|
|
link=source.get("link") or source.get("page_url"),
|
|
page_url=source.get("page_url"),
|
|
|
|
title_de=source.get("title_de"),
|
|
title_en=source.get("title_en"),
|
|
|
|
abstract_de=source.get("abstract_de"),
|
|
abstract_en=source.get("abstract_en"),
|
|
|
|
subject_classifications_raw=(
|
|
source.get("subject_area_de")
|
|
or source.get("subject_area_en")
|
|
),
|
|
|
|
funding_start=(
|
|
str(source["funding_start"])
|
|
if source.get("funding_start") is not None
|
|
else None
|
|
),
|
|
funding_end=(
|
|
str(source["funding_end"])
|
|
if source.get("funding_end") is not None
|
|
else None
|
|
),
|
|
|
|
institutions=list(institutions.values()),
|
|
names=names,
|
|
persons=project_persons,
|
|
|
|
subject_classifications=[
|
|
DFGProjectFachgebieteInner.from_dict(classification)
|
|
for classification in subject_classifications
|
|
if isinstance(classification, dict)
|
|
],
|
|
|
|
topics=topics or [],
|
|
highlight=cls._highlight_from_hit(hit),
|
|
)
|
|
@staticmethod
|
|
def _topic_from_match(match: dict[str, Any]) -> Topic:
|
|
"""Builds a (partial) Topic model from a flattened topic_match dict
|
|
coming from the `projects_dfg_openalex_topics` index.
|
|
|
|
Args:
|
|
match (Dict[str, Any]): A single topic match entry, e.g.:
|
|
{
|
|
"rank": 1,
|
|
"topic_id": "https://openalex.org/T12220",
|
|
"topic_display_name": "Quantum Electrodynamics and Casimir Effect",
|
|
"subfield": "Atomic and Molecular Physics, and Optics",
|
|
"field": "Physics and Astronomy",
|
|
"domain": "Physical Sciences",
|
|
"match_score": None
|
|
}
|
|
|
|
Returns:
|
|
Topic: The constructed Topic instance.
|
|
"""
|
|
domain_name = match.get("domain")
|
|
field_name = match.get("field")
|
|
subfield_name = match.get("subfield")
|
|
|
|
domain = TopicDomain(display_name=domain_name) if domain_name else None
|
|
field = TopicField(display_name=field_name) if field_name else None
|
|
subfield = TopicSubfield(display_name=subfield_name) if subfield_name else None
|
|
|
|
return Topic(
|
|
id=match.get("topic_id"),
|
|
display_name=match.get("topic_display_name"),
|
|
domain=domain,
|
|
field=field,
|
|
subfield=subfield,
|
|
)
|
|
@staticmethod
|
|
def _highlight_fragments(value: Any) -> list[str]:
|
|
"""Normalize an Elasticsearch highlight value."""
|
|
|
|
if isinstance(value, str):
|
|
return [value]
|
|
|
|
if isinstance(value, list):
|
|
return [
|
|
fragment
|
|
for fragment in value
|
|
if isinstance(fragment, str)
|
|
]
|
|
|
|
return []
|
|
|
|
|
|
@classmethod
|
|
def _highlight_from_hit(
|
|
cls,
|
|
hit: dict[str, Any],
|
|
) -> DfgProjectHighlight | None:
|
|
"""Parse top-level and nested highlights from an Elasticsearch hit."""
|
|
|
|
raw_highlight = hit.get("highlight")
|
|
if not isinstance(raw_highlight, dict):
|
|
raw_highlight = {}
|
|
|
|
result = DfgProjectHighlight(
|
|
title_de=cls._highlight_fragments(
|
|
raw_highlight.get("title_de")
|
|
),
|
|
title_en=cls._highlight_fragments(
|
|
raw_highlight.get("title_en")
|
|
),
|
|
abstract_de=cls._highlight_fragments(
|
|
raw_highlight.get("abstract_de")
|
|
),
|
|
abstract_en=cls._highlight_fragments(
|
|
raw_highlight.get("abstract_en")
|
|
),
|
|
)
|
|
|
|
raw_inner_hits = hit.get("inner_hits")
|
|
|
|
if isinstance(raw_inner_hits, dict):
|
|
for query_name, inner_hit_group in raw_inner_hits.items():
|
|
if not isinstance(inner_hit_group, dict):
|
|
continue
|
|
|
|
inner_hits_block = inner_hit_group.get("hits")
|
|
if not isinstance(inner_hits_block, dict):
|
|
continue
|
|
|
|
nested_hits = inner_hits_block.get("hits", [])
|
|
if not isinstance(nested_hits, list):
|
|
continue
|
|
|
|
for nested_hit in nested_hits:
|
|
if not isinstance(nested_hit, dict):
|
|
continue
|
|
|
|
nested_highlight = nested_hit.get("highlight")
|
|
if not isinstance(nested_highlight, dict):
|
|
continue
|
|
|
|
nested_metadata = nested_hit.get("_nested")
|
|
offset = None
|
|
|
|
if isinstance(nested_metadata, dict):
|
|
raw_offset = nested_metadata.get("offset")
|
|
if isinstance(raw_offset, int):
|
|
offset = raw_offset
|
|
|
|
parsed_nested_highlight = (
|
|
DfgSubjectClassificationHighlight(
|
|
query=str(query_name),
|
|
offset=offset,
|
|
fach=cls._highlight_fragments(
|
|
nested_highlight.get(
|
|
"subject_classifications.fach"
|
|
)
|
|
),
|
|
fachkollegium=cls._highlight_fragments(
|
|
nested_highlight.get(
|
|
"subject_classifications.fachkollegium"
|
|
)
|
|
),
|
|
fachgebiet=cls._highlight_fragments(
|
|
nested_highlight.get(
|
|
"subject_classifications.fachgebiet"
|
|
)
|
|
),
|
|
fachgebiet_de=cls._highlight_fragments(
|
|
nested_highlight.get(
|
|
"subject_classifications.fachgebiet_de"
|
|
)
|
|
),
|
|
wissenschaftsbereich=cls._highlight_fragments(
|
|
nested_highlight.get(
|
|
"subject_classifications."
|
|
"wissenschaftsbereich"
|
|
)
|
|
),
|
|
)
|
|
)
|
|
|
|
# Do not expose empty nested highlight objects.
|
|
has_nested_fragments = any(
|
|
(
|
|
parsed_nested_highlight.fach,
|
|
parsed_nested_highlight.fachkollegium,
|
|
parsed_nested_highlight.fachgebiet,
|
|
parsed_nested_highlight.fachgebiet_de,
|
|
parsed_nested_highlight.wissenschaftsbereich,
|
|
)
|
|
)
|
|
|
|
if has_nested_fragments:
|
|
result.subject_classifications.append(
|
|
parsed_nested_highlight
|
|
)
|
|
|
|
has_highlights = any(
|
|
(
|
|
result.title_de,
|
|
result.title_en,
|
|
result.abstract_de,
|
|
result.abstract_en,
|
|
result.subject_classifications,
|
|
)
|
|
)
|
|
|
|
return result if has_highlights else None
|
|
|
|
class DfgProjectPage(Page):
|
|
elements: list[DfgProjectSummary] = Field(
|
|
default_factory=list, description="The DFG projects on this page."
|
|
)
|
|
|
|
class InstitutionFunderSummary(BaseModel):
|
|
type: ProjectType = Field(
|
|
description="The type of funding data (e.g., 'bund', 'eu', 'dfg')."
|
|
)
|
|
funding_per_year: dict = Field(
|
|
default_factory=dict,
|
|
description="A dictionary mapping years to total funding amounts for that year.",
|
|
)
|
|
annual_average_over_period: float = Field(
|
|
default=0.0,
|
|
description="The average annual funding over the continuous period covered by the data.",
|
|
)
|
|
|
|
|
|
class ProjectsFilteringProperties(BaseModel):
|
|
project_type: ProjectType = Field(description="The type of projects to filter by.")
|
|
page: int = Field(description="The page number for pagination.")
|
|
size: int = Field(description="The page size for pagination.")
|
|
raw_oa_institution_id: str | None = Field(
|
|
default=None, description="The raw OA institution ID to filter by."
|
|
)
|
|
query: str | None = Field(
|
|
default=None, description="The query string to filter projects by."
|
|
)
|
|
sort_by: ProjectsSortBy = Field(
|
|
default=ProjectsSortBy.TITLE, description="The field to sort by."
|
|
)
|
|
sort_direction: SortDirection = Field(
|
|
default=SortDirection.ASC, description="The sort direction (asc or desc)."
|
|
)
|
|
|
|
|
|
class EuCordisProjectResponse(BaseModel):
|
|
"""
|
|
Response model for EU Cordis project endpoints.
|
|
"""
|
|
success: bool = Field(description="Indicates if the request was successful")
|
|
project_type: str | None = Field(
|
|
default=None,
|
|
description="The type of project: 'fp7', 'h2020', or 'heu'"
|
|
)
|
|
eu_project_data: Fp7ProjectDetails | H2020ProjectDetails | HEUProjectDetails | None = Field(
|
|
default=None,
|
|
description="The project data"
|
|
)
|
|
error: str | None = Field(
|
|
default=None,
|
|
description="Error message if the request failed"
|
|
)
|
|
|
|
|
|
class FundingProject(BaseModel):
|
|
type: ProjectType = Field(
|
|
description="The type of the project.",
|
|
examples=[ProjectType.BUND, ProjectType.EU, ProjectType.DFG],
|
|
)
|
|
id: str = Field(description="The unique identifier of the project.")
|
|
title: str | None = Field(default=None, description="The title of the project.")
|
|
acronym: str | None = Field(
|
|
default=None, description="The acronym of the project (if available)."
|
|
)
|
|
start_date: date | None = Field(
|
|
default=None, description="The funding start date of the project."
|
|
)
|
|
end_date: date | None = Field(
|
|
default=None, description="The funding end date of the project."
|
|
)
|
|
funding_amount: float | None = Field(
|
|
default=None, description="The total funding amount for the project."
|
|
)
|
|
|
|
@field_validator("start_date", "end_date", mode="before")
|
|
@classmethod
|
|
def parse_all_date_formats(cls, value):
|
|
if isinstance(value, int):
|
|
value = str(value)
|
|
if isinstance(value, str):
|
|
value = value.strip()
|
|
|
|
if len(value) == 4 and value.isdigit():
|
|
return f"{value}-01-01"
|
|
|
|
if "." in value:
|
|
return datetime.datetime.strptime(value, "%d.%m.%Y").date()
|
|
|
|
return value
|
|
|
|
return value
|
|
|
|
@classmethod
|
|
def from_cordis_projects_hit(cls, hit: dict) -> "FundingProject":
|
|
if not hit.get("_index", "").startswith("cordis_eu_") and not hit.get(
|
|
"_index", ""
|
|
).endswith("_projects"):
|
|
raise ValueError(
|
|
"The provided hit does not belong to an index starting with 'cordis_eu_' and ending with '_projects'."
|
|
)
|
|
|
|
source = hit.get("_source", {})
|
|
return cls(
|
|
type=ProjectType.EU,
|
|
id=hit.get("_id", ""),
|
|
title=source.get("title"),
|
|
start_date=source.get("startDate"),
|
|
end_date=source.get("endDate"),
|
|
funding_amount=source.get("ecMaxContribution"),
|
|
)
|
|
|
|
@classmethod
|
|
def from_bund_projects_hit(cls, hit: dict) -> "FundingProject":
|
|
if hit.get("_index") != "projects_bund_v1":
|
|
raise ValueError(
|
|
"The provided hit does not belong to the 'projects_bund_v1' index."
|
|
)
|
|
|
|
source = hit.get("_source", {})
|
|
return cls(
|
|
type=ProjectType.BUND,
|
|
id=source.get("Förderkennzeichen", ""),
|
|
title=source.get("Thema"),
|
|
start_date=source.get("funding_start"),
|
|
end_date=source.get("funding_end"),
|
|
funding_amount=source.get("Fördersumme"),
|
|
)
|
|
|
|
@classmethod
|
|
def from_dfg_projects_hit(cls, hit: dict) -> "FundingProject":
|
|
if hit.get("_index") != ESIndex.DFG_PROJECTS.value:
|
|
raise ValueError(
|
|
f"The provided hit does not belong to the '{ESIndex.DFG_PROJECTS.value}' index."
|
|
)
|
|
|
|
source = hit.get("_source", {})
|
|
return cls(
|
|
type=ProjectType.DFG,
|
|
id=hit.get("_id", ""),
|
|
title=source.get("title_de") or source.get("title_en"),
|
|
start_date=source.get("funding_start"),
|
|
end_date=source.get("funding_end"),
|
|
acronym=source.get("acronym"),
|
|
)
|
|
|
|
|
|
class FundingProjectPage(Page):
|
|
elements: list[FundingProject] = Field(
|
|
default_factory=list, description="The funding projects on this page."
|
|
)
|
|
|
|
|
|
#EU CORDIS PROJECTS
|
|
class EuProjectPage(Page):
|
|
elements: list[EuProject] = Field(
|
|
default_factory=list, description="The EU projects on this page."
|
|
)
|
|
|
|
################
|
|
class EuCordisProjectType(StrEnum):
|
|
FP7 = "fp7"
|
|
H2020 = "h2020"
|
|
HEU = "heu"
|
|
|
|
def to_project_index(self) -> ESIndex:
|
|
mapping = {
|
|
self.FP7: ESIndex.CORDIS_EU_FP7_PROJECTS,
|
|
self.H2020: ESIndex.CORDIS_EU_HORIZON_2020_PROJECTS,
|
|
self.HEU: ESIndex.CORDIS_EU_HORIZON_EUROPE_PROJECTS,
|
|
}
|
|
return mapping[self]
|
|
|
|
def to_organization_index(self) -> ESIndex:
|
|
mapping = {
|
|
self.FP7: ESIndex.CORDIS_EU_FP7_ORGANIZATIONS,
|
|
self.H2020: ESIndex.CORDIS_EU_HORIZON_2020_ORGANIZATIONS,
|
|
self.HEU: ESIndex.CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS,
|
|
}
|
|
return mapping[self]
|
|
|
|
def to_cordis_topic_index(self) -> ESIndex:
|
|
mapping = {
|
|
self.FP7: ESIndex.CORDIS_EU_FP7_TOPICS,
|
|
self.H2020: ESIndex.CORDIS_EU_HORIZON_2020_TOPICS,
|
|
self.HEU: ESIndex.CORDIS_EU_HORIZON_EUROPE_TOPICS,
|
|
}
|
|
return mapping[self]
|
|
def to_cordis_publications_index(self) -> ESIndex:
|
|
mapping = {
|
|
self.FP7: ESIndex.CORDIS_EU_FP7_PUBLICATIONS,
|
|
self.H2020: ESIndex.CORDIS_EU_HORIZON_2020_PUBLICATIONS,
|
|
self.HEU: ESIndex.CORDIS_EU_HORIZON_EUROPE_PUBLICATIONS,
|
|
}
|
|
return mapping[self]
|
|
|
|
def to_euroscivoc_index(self) -> ESIndex:
|
|
mapping = {
|
|
self.FP7: ESIndex.CORDIS_EU_FP7_EUROSCIVOC,
|
|
self.H2020: ESIndex.CORDIS_EU_HORIZON_2020_EUROSCIVOC,
|
|
self.HEU: ESIndex.CORDIS_EU_HORIZON_EUROPE_EUROSCIVOC,
|
|
}
|
|
return mapping[self]
|
|
|
|
def to_openalex_topics_index(self) -> ESIndex:
|
|
mapping = {
|
|
self.FP7: ESIndex.PROJECTS_CORDIS_EU_FP7_TOPICS_MAPPING,
|
|
self.H2020: ESIndex.PROJECTS_CORDIS_EU_H2020_TOPICS,
|
|
self.HEU: ESIndex.PROJECTS_CORDIS_EU_HEUROPE_TOPICS,
|
|
}
|
|
return mapping[self]
|
|
|
|
|
|
@classmethod
|
|
def from_index_name(cls, index_name: str) -> "EuCordisProjectType":
|
|
if index_name == ESIndex.CORDIS_EU_FP7_PROJECTS.value:
|
|
return cls.FP7
|
|
if index_name == ESIndex.CORDIS_EU_HORIZON_2020_PROJECTS.value:
|
|
return cls.H2020
|
|
if index_name == ESIndex.CORDIS_EU_HORIZON_EUROPE_PROJECTS.value:
|
|
return cls.HEU
|
|
|
|
raise ValueError(f"Unsupported EU CORDIS project index: {index_name}")
|
|
|
|
|
|
class EuCordisOrganizationSummary(BaseModel):
|
|
id: str | None = None
|
|
organisation_id: str | None = None
|
|
name: str | None = None
|
|
short_name: str | None = None
|
|
country: str | None = None
|
|
city: str | None = None
|
|
role: str | None = None
|
|
activity_type: str | None = None
|
|
project_id: str | None = None
|
|
ec_contribution: float | None = None
|
|
total_cost: float | None = None
|
|
|
|
@classmethod
|
|
def from_es_source(cls, source: dict[str, Any]) -> "EuCordisOrganizationSummary":
|
|
return cls(
|
|
id=source.get("id"),
|
|
organisation_id=source.get("organisationID"),
|
|
name=source.get("name"),
|
|
short_name=source.get("shortName"),
|
|
country=source.get("country"),
|
|
city=source.get("city"),
|
|
role=source.get("role"),
|
|
activity_type=source.get("activityType"),
|
|
project_id=source.get("projectID"),
|
|
ec_contribution=source.get("ecContribution"),
|
|
total_cost=source.get("totalCost"),
|
|
)
|
|
|
|
|
|
|
|
class EuCordisTopicSummary(BaseModel):
|
|
id: str | None = None
|
|
project_id: str | None = None
|
|
title: str | None = None
|
|
topic: str | None = None
|
|
|
|
@classmethod
|
|
def from_es_source(cls, source: dict[str, Any]) -> "EuCordisTopicSummary":
|
|
return cls(
|
|
id=source.get("id"),
|
|
project_id=source.get("projectID"),
|
|
title=source.get("title"),
|
|
topic=source.get("topic"),
|
|
)
|
|
|
|
|
|
|
|
class EuCordisEurosciVocSummary(BaseModel):
|
|
id: str | None = None
|
|
project_id: str | None = None
|
|
code: str | None = None
|
|
title: str | None = None
|
|
description: str | None = None
|
|
path: str | None = None
|
|
|
|
@classmethod
|
|
def from_es_source(cls, source: dict[str, Any]) -> "EuCordisEurosciVocSummary":
|
|
return cls(
|
|
id=source.get("id"),
|
|
project_id=source.get("projectID"),
|
|
code=source.get("code"),
|
|
title=source.get("title"),
|
|
description=source.get("description"),
|
|
path=source.get("path"),
|
|
)
|
|
class EuCordisProjectHighlight(BaseModel):
|
|
"""Highlighted fragments returned by Elasticsearch."""
|
|
|
|
title: list[str] = Field(default_factory=list)
|
|
acronym: list[str] = Field(default_factory=list)
|
|
objective: list[str] = Field(default_factory=list)
|
|
keywords: list[str] = Field(default_factory=list)
|
|
|
|
# Elasticsearch source/highlight field is "topics", but "topics" is already
|
|
# used by the API model for mapped OpenAlex Topic objects.
|
|
cordis_topic_text: list[str] = Field(
|
|
default_factory=list,
|
|
description="Highlighted fragments from the CORDIS topics text field.",
|
|
)
|
|
|
|
class EuCordisProjectSummary(BaseModel):
|
|
id: str
|
|
project_type: EuCordisProjectType
|
|
|
|
title: str | None = None
|
|
acronym: str | None = None
|
|
objective: str | None = None
|
|
keywords: str | None = None
|
|
|
|
framework_programme: str | None = None
|
|
funding_scheme: str | None = None
|
|
status: str | None = None
|
|
|
|
start_date: date | None = None
|
|
end_date: date | None = None
|
|
|
|
ec_max_contribution: float | None = None
|
|
total_cost: float | None = None
|
|
authors: AuthorPage | None = None
|
|
organizations: list[EuCordisOrganizationSummary] = Field(default_factory=list)
|
|
cordis_topics: list[EuCordisTopicSummary] = Field(default_factory=list)
|
|
eurosci_voc: list[EuCordisEurosciVocSummary] = Field(default_factory=list)
|
|
topics: list[Topic] = Field(default_factory=list, description="Mapped OpenAlex topics.")
|
|
cordis_topic_text: str | None = Field(
|
|
default=None,
|
|
description=(
|
|
"Original CORDIS topics text from the Elasticsearch project "
|
|
"document, for example 'MSCA-IF-2018'."
|
|
),
|
|
)
|
|
highlight: EuCordisProjectHighlight | None = Field(
|
|
default=None,
|
|
description="Highlighted matching fragments from the project search.",
|
|
)
|
|
@classmethod
|
|
@classmethod
|
|
def from_hit(
|
|
cls,
|
|
hit: dict[str, Any],
|
|
authors: AuthorPage | None = None,
|
|
organizations: list[EuCordisOrganizationSummary] | None = None,
|
|
cordis_topics: list[EuCordisTopicSummary] | None = None,
|
|
eurosci_voc: list[EuCordisEurosciVocSummary] | None = None,
|
|
topics: list[Topic] | None = None,
|
|
) -> "EuCordisProjectSummary":
|
|
source = hit.get("_source", {})
|
|
project_type = EuCordisProjectType.from_index_name(
|
|
hit.get("_index", "")
|
|
)
|
|
|
|
project_id = source.get("id")
|
|
if project_id is None:
|
|
project_id = hit.get("_id", "")
|
|
|
|
return cls(
|
|
id=str(project_id),
|
|
project_type=project_type,
|
|
|
|
title=source.get("title"),
|
|
acronym=source.get("acronym"),
|
|
objective=source.get("objective"),
|
|
keywords=source.get("keywords"),
|
|
cordis_topic_text=source.get("topics"),
|
|
|
|
framework_programme=source.get("frameworkProgramme"),
|
|
funding_scheme=source.get("fundingScheme"),
|
|
status=source.get("status"),
|
|
|
|
start_date=source.get("startDate"),
|
|
end_date=source.get("endDate"),
|
|
|
|
ec_max_contribution=source.get("ecMaxContribution"),
|
|
total_cost=source.get("totalCost"),
|
|
|
|
authors=authors,
|
|
organizations=organizations or [],
|
|
cordis_topics=cordis_topics or [],
|
|
eurosci_voc=eurosci_voc or [],
|
|
topics=topics or [],
|
|
|
|
highlight=cls._highlight_from_hit(hit),
|
|
)
|
|
@staticmethod
|
|
def _highlight_fragments(value: Any) -> list[str]:
|
|
"""Normalize an Elasticsearch highlight value to a list of strings."""
|
|
|
|
if isinstance(value, str):
|
|
return [value]
|
|
|
|
if isinstance(value, list):
|
|
return [
|
|
fragment
|
|
for fragment in value
|
|
if isinstance(fragment, str)
|
|
]
|
|
|
|
return []
|
|
|
|
|
|
@classmethod
|
|
def _highlight_from_hit(
|
|
cls,
|
|
hit: dict[str, Any],
|
|
) -> EuCordisProjectHighlight | None:
|
|
"""Extract project highlights from an Elasticsearch hit."""
|
|
|
|
raw_highlight = hit.get("highlight")
|
|
if not isinstance(raw_highlight, dict):
|
|
return None
|
|
|
|
highlight = EuCordisProjectHighlight(
|
|
title=cls._highlight_fragments(
|
|
raw_highlight.get("title")
|
|
),
|
|
acronym=cls._highlight_fragments(
|
|
raw_highlight.get("acronym")
|
|
),
|
|
objective=cls._highlight_fragments(
|
|
raw_highlight.get("objective")
|
|
),
|
|
keywords=cls._highlight_fragments(
|
|
raw_highlight.get("keywords")
|
|
),
|
|
cordis_topic_text=cls._highlight_fragments(
|
|
raw_highlight.get("topics")
|
|
),
|
|
)
|
|
|
|
has_highlights = any(
|
|
(
|
|
highlight.title,
|
|
highlight.acronym,
|
|
highlight.objective,
|
|
highlight.keywords,
|
|
highlight.cordis_topic_text,
|
|
)
|
|
)
|
|
|
|
return highlight if has_highlights else None
|
|
@staticmethod
|
|
def topic_from_match(match: dict[str, Any]) -> Topic:
|
|
domain_name = match.get("domain")
|
|
field_name = match.get("field")
|
|
subfield_name = match.get("subfield")
|
|
|
|
domain = TopicDomain(display_name=domain_name) if domain_name else None
|
|
field = TopicField(display_name=field_name) if field_name else None
|
|
subfield = TopicSubfield(display_name=subfield_name) if subfield_name else None
|
|
|
|
return Topic(
|
|
id=match.get("topic_id"),
|
|
display_name=match.get("topic_display_name"),
|
|
domain=domain,
|
|
field=field,
|
|
subfield=subfield,
|
|
)
|
|
|
|
|
|
class EuCordisProjectSearchPage(Page):
|
|
elements: list[EuCordisProjectSummary] = Field(
|
|
default_factory=list,
|
|
description="The EU CORDIS project summaries on this page.",
|
|
)
|
|
|
|
|
|
class EuCordisOrganizationSelectorSummary(BaseModel):
|
|
id: str | None = None
|
|
organisation_id: str | None = None
|
|
name: str | None = None
|
|
short_name: str | None = None
|
|
country: str | None = None
|
|
city: str | None = None
|
|
project_type: EuCordisProjectType | None = None
|
|
|
|
@classmethod
|
|
def from_es_source(
|
|
cls,
|
|
source: dict[str, Any],
|
|
project_type: EuCordisProjectType | None = None,
|
|
) -> "EuCordisOrganizationSelectorSummary":
|
|
return cls(
|
|
id=source.get("id"),
|
|
organisation_id=source.get("organisationID"),
|
|
name=source.get("name"),
|
|
short_name=source.get("shortName"),
|
|
country=source.get("country"),
|
|
city=source.get("city"),
|
|
project_type=project_type,
|
|
)
|
|
|
|
|
|
|
|
class EuCordisOrganizationSelectorPage(Page):
|
|
elements: list[EuCordisOrganizationSelectorSummary] = Field(default_factory=list) |