Files
smartguide/service/src/main/inse/projects/model.py
T

794 lines
28 KiB
Python

from datetime import date
import datetime
from enum import StrEnum
from typing import List, Optional, Dict, Any
from pydantic import BaseModel, Field, field_validator
from inse.models.bund_project import BundProject
from inse.models.eu_project import EuProject
from inse.model import ESIndex
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.models.projects_eu_cordis.fp7.fp7_project_details import Fp7ProjectDetails
from inse.models.projects_dfg_v2.project.dfg_project_fachgebiete_inner import DFGProjectFachgebieteInner
from inse.models.openalex.topic import Topic, TopicDomain, TopicField, TopicSubfield
from inse.authors.v2.model import AuthorPage
from inse.projects.bund_institutions.model import BundInstitutionSummary
from typing import Union
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 BundProjectSummary(BundProject):
oa_topics: Optional[list[Topic]] = Field(
default=None,
validation_alias="oa_topics",
description="The OpenAlex topics of the project",
examples=[["Artificial Intelligence", "Machine Learning"]],
)
institution: Optional[BundInstitutionSummary] = Field(
default=None,
description="The executing agency / recipient institution for this project, "
"derived from the project's own agency fields.",
)
@classmethod
def from_hit(cls, hit: dict) -> "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(
(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"),
)
oa_topics = [cls._topic_from_match(t) for t 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"),
implementing_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),
)
@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 DfgInstitutionSummary(BaseModel):
"""A summary of a DFG institution."""
id: int
institute_name_de: Optional[str] = None
institute_name_en: Optional[str] = None
root_id: Optional[int] = None
root_name_de: Optional[str] = None
root_name_en: Optional[str] = None
address_country_de: Optional[str] = None
address_country_en: Optional[str] = None
class DfgPersonSummary(BaseModel):
person_id: int
orcid_id: Optional[str] = None
project_ref_id: Optional[int] = None
full_name: Optional[str] = None
role_label_en: Optional[str] = None,
role_label_de: Optional[str] = None,
institution: Optional[DfgInstitutionSummary] = None
class DfgProjectSummary(BaseModel):
id: str = Field(
description="The unique identifier of the DFG project."
)
link: Optional[str] = Field(
default=None,
description="The link to the DFG project details."
)
title: Optional[str] = Field(
default=None,
description="The title of the DFG project."
)
professional_classification: Optional[str] = Field(
default=None,
description="The professional classification of the DFG project."
)
funding_start: Optional[str] = Field(
default=None,
description="The funding start date of the DFG project."
)
funding_end: Optional[str] = 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: Optional[List[DFGProjectFachgebieteInner]] = Field(
default=None,
description="The subject classifications of the DFG project.",
)
topics: Optional[List[Topic]] = Field(
default=None,
description="The topics associated with the DFG project.",
)
@classmethod
def from_hit(cls, hit: dict) -> "DfgProjectSummary":
source = hit.get("_source", {})
fields = hit.get("fields", {})
names = []
institutions = {}
project_persons = []
persons = source.get("persons", [])
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())
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=institution,
)
)
topics_raw = source.get("topics") or []
print(f"Raw topics for DFG project {hit.get('_id', '')}: {topics_raw}")
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]
return cls(
id=hit.get("_id", ""),
link=source.get("link") or source.get("page_url"),
title=(
source.get("title")
or source.get("title_de")
or source.get("title_en")
),
professional_classification=(
source.get("Fachliche Zuordnung")
or source.get("subject_area_de")
or source.get("subject_area_en")
),
funding_start=(
str(source.get("funding_start"))
if source.get("funding_start") is not None
else None
),
funding_end=(
str(source.get("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(cls) for cls in source.get('subject_classifications', [])],
topics=topics
)
@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,
)
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: Optional[str] = Field(
default=None, description="The raw OA institution ID to filter by."
)
query: Optional[str] = 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: Optional[str] = Field(
default=None,
description="The type of project: 'fp7', 'h2020', or 'heu'"
)
eu_project_data: Optional[Union[Fp7ProjectDetails, H2020ProjectDetails, HEUProjectDetails]] = Field(
default=None,
description="The project data"
)
error: Optional[str] = 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: Optional[str] = Field(default=None, description="The title of the project.")
acronym: Optional[str] = Field(
default=None, description="The acronym of the project (if available)."
)
start_date: Optional[date] = Field(
default=None, description="The funding start date of the project."
)
end_date: Optional[date] = Field(
default=None, description="The funding end date of the project."
)
funding_amount: Optional[float] = 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: Optional[str] = None
organisation_id: Optional[str] = None
name: Optional[str] = None
short_name: Optional[str] = None
country: Optional[str] = None
city: Optional[str] = None
role: Optional[str] = None
activity_type: Optional[str] = None
project_id: Optional[str] = None
ec_contribution: Optional[float] = None
total_cost: Optional[float] = 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: Optional[str] = None
project_id: Optional[str] = None
title: Optional[str] = None
topic: Optional[str] = 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: Optional[str] = None
project_id: Optional[str] = None
code: Optional[str] = None
title: Optional[str] = None
description: Optional[str] = None
path: Optional[str] = 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 EuCordisProjectSummary(BaseModel):
id: str
project_type: EuCordisProjectType
title: Optional[str] = None
acronym: Optional[str] = None
objective: Optional[str] = None
keywords: Optional[str] = None
framework_programme: Optional[str] = None
funding_scheme: Optional[str] = None
status: Optional[str] = None
start_date: Optional[date] = None
end_date: Optional[date] = None
ec_max_contribution: Optional[float] = None
total_cost: Optional[float] = None
authors: Optional[AuthorPage] = 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.")
@classmethod
def from_hit(
cls,
hit: Dict[str, Any],
authors: Optional[AuthorPage] = None,
organizations: Optional[List[EuCordisOrganizationSummary]] = None,
cordis_topics: Optional[List[EuCordisTopicSummary]] = None,
eurosci_voc: Optional[List[EuCordisEurosciVocSummary]] = None,
topics: Optional[List[Topic]] = None,
) -> "EuCordisProjectSummary":
source = hit.get("_source", {})
project_type = EuCordisProjectType.from_index_name(hit.get("_index", ""))
return cls(
id=source.get("id") or hit.get("_id", ""),
project_type=project_type,
title=source.get("title"),
acronym=source.get("acronym"),
objective=source.get("objective"),
keywords=source.get("keywords"),
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 or None,
organizations=organizations or [],
cordis_topics=cordis_topics or [],
eurosci_voc=eurosci_voc or [],
topics=topics or [],
)
@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: Optional[str] = None
organisation_id: Optional[str] = None
name: Optional[str] = None
short_name: Optional[str] = None
country: Optional[str] = None
city: Optional[str] = None
project_type: Optional[EuCordisProjectType] = None
@classmethod
def from_es_source(
cls,
source: Dict[str, Any],
project_type: Optional[EuCordisProjectType] = 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)