refactored projects backend endpoints an logic
This commit is contained in:
@@ -47,6 +47,17 @@ from inse.models.projects_eu_cordis.horizon_europe.heu_eurosci_voc import HEUEur
|
||||
from inse.models.projects_eu_cordis.horizon_europe.heu_legal_basis import HEULegalBasis
|
||||
from inse.models.projects_eu_cordis.horizon_europe.heu_project_details import HEUProjectDetails
|
||||
|
||||
from inse.projects.model import (
|
||||
EuCordisProjectType,
|
||||
EuCordisProjectSearchPage,
|
||||
EuCordisProjectSummary,
|
||||
EuCordisOrganizationSummary,
|
||||
EuCordisTopicSummary,
|
||||
EuCordisEurosciVocSummary,
|
||||
)
|
||||
from inse.projects.logic import get_eu_project_ids_by_openalex_topic_ids, get_openalex_topics_for_eu_projects
|
||||
|
||||
|
||||
settings = get_settings()
|
||||
logger = logging.getLogger(__name__)
|
||||
logger.setLevel(settings.logging_level)
|
||||
@@ -284,19 +295,6 @@ async def _enrich_heu_project(
|
||||
|
||||
|
||||
|
||||
from inse.projects.model import (
|
||||
EuCordisProjectType,
|
||||
EuCordisProjectSearchPage,
|
||||
EuCordisProjectSummary,
|
||||
EuCordisOrganizationSummary,
|
||||
EuCordisTopicSummary,
|
||||
EuCordisEurosciVocSummary,
|
||||
)
|
||||
from inse.projects.logic import (
|
||||
get_eu_project_ids_by_openalex_topic_ids,
|
||||
get_openalex_topics_for_eu_projects,
|
||||
)
|
||||
|
||||
def _eu_project_type_index_filter(
|
||||
project_ids_by_type: Dict[EuCordisProjectType, List[str]],
|
||||
) -> Optional[Dict[str, Any]]:
|
||||
@@ -396,11 +394,8 @@ async def get_eu_project_ids_by_organization_filters(
|
||||
for name in organization_names:
|
||||
should.append(
|
||||
{
|
||||
"match": {
|
||||
"name": {
|
||||
"query": name,
|
||||
"operator": "and",
|
||||
}
|
||||
"match_phrase": {
|
||||
"name": name
|
||||
}
|
||||
}
|
||||
)
|
||||
@@ -421,7 +416,7 @@ async def get_eu_project_ids_by_organization_filters(
|
||||
)
|
||||
|
||||
hits = response.get("hits", {}).get("hits", [])
|
||||
|
||||
|
||||
for hit in hits:
|
||||
source = hit.get("_source", {})
|
||||
project_id = source.get("projectID")
|
||||
@@ -437,16 +432,29 @@ async def get_eu_project_ids_by_organization_filters(
|
||||
for org_name in organization_names:
|
||||
if name and org_name.lower() in name.lower():
|
||||
project_org_matches[project_id].add(f"name:{org_name.lower()}")
|
||||
print(f"Project organization matches for {project_type}: {project_org_matches}")
|
||||
required_orgs = set()
|
||||
|
||||
required = {f"id:{x}" for x in organization_ids}
|
||||
required.update({f"name:{x.lower()}" for x in organization_names})
|
||||
# Add ID requirements
|
||||
for org_id in organization_ids:
|
||||
required_orgs.add(f"id:{org_id}")
|
||||
|
||||
result[project_type] = [
|
||||
project_id
|
||||
for project_id, found in project_org_matches.items()
|
||||
if required.issubset(found)
|
||||
]
|
||||
required_id_set = {f"id:{x}" for x in organization_ids}
|
||||
required_name_match = len(organization_names) > 0 # if any names, need at least one match
|
||||
|
||||
result[project_type] = []
|
||||
for project_id, found in project_org_matches.items():
|
||||
# Check ID matches
|
||||
if not required_id_set.issubset(found):
|
||||
continue
|
||||
|
||||
# Check name match: at least one name alias must be in found
|
||||
if required_name_match:
|
||||
if not any(f"name:{name.lower()}" in found for name in organization_names):
|
||||
continue
|
||||
|
||||
result[project_type].append(project_id)
|
||||
print(f"Final project IDs by type: {result}")
|
||||
return result
|
||||
|
||||
async def get_eu_organizations_for_projects(
|
||||
|
||||
@@ -3,7 +3,6 @@ import logging
|
||||
from typing import Any, Dict, List, Optional, Set, Tuple
|
||||
|
||||
from collections import defaultdict
|
||||
from inse.projects.eu_cordis_projects_client import get_enriched_cordis_project_by_id
|
||||
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster, ESIndex
|
||||
|
||||
@@ -7,7 +7,6 @@ from pydantic import BaseModel, Field, field_validator
|
||||
|
||||
from inse.models.bund_project import BundProject
|
||||
from inse.models.eu_project import EuProject
|
||||
from inse.models.cordis_eu_project import CordisEuProject
|
||||
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
|
||||
@@ -69,15 +68,95 @@ class Page(BaseModel):
|
||||
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"]],
|
||||
)
|
||||
|
||||
@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]
|
||||
print(f"oa_topics: {oa_topics}")
|
||||
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("Förderbeginn"),
|
||||
funding_end=source.get("Förderende"),
|
||||
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,
|
||||
)
|
||||
|
||||
@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[BundProject] = Field(
|
||||
elements: List[BundProjectSummary] = Field(
|
||||
default_factory=list, description="The bund projects on this page."
|
||||
)
|
||||
|
||||
|
||||
|
||||
|
||||
class BundProjectList(BaseModel):
|
||||
elements: List[BundProject] = Field(
|
||||
elements: List[BundProjectSummary] = Field(
|
||||
default_factory=list, description="All bund projects."
|
||||
)
|
||||
total: int = Field(default=0, description="The total number of bund projects.")
|
||||
@@ -317,11 +396,6 @@ class ProjectsFilteringProperties(BaseModel):
|
||||
)
|
||||
|
||||
|
||||
class CordisEuProjectPage(Page):
|
||||
elements: List[CordisEuProject] = Field(
|
||||
default_factory=list, description="The CORDIS EU projects on this page."
|
||||
)
|
||||
|
||||
class EuCordisProjectResponse(BaseModel):
|
||||
"""
|
||||
Response model for EU Cordis project endpoints.
|
||||
@@ -445,62 +519,6 @@ class EuProjectPage(Page):
|
||||
default_factory=list, description="The EU projects on this page."
|
||||
)
|
||||
|
||||
class EuOrganizationShort(BaseModel):
|
||||
project_id: str = Field(description="The unique identifier of the project.")
|
||||
organization_id: str = Field(
|
||||
description="The unique identifier of the organization."
|
||||
)
|
||||
ec_contribution: Optional[float] = Field(
|
||||
default=None,
|
||||
description="The EC contribution amount for the organization in the project.",
|
||||
)
|
||||
|
||||
|
||||
class EuProjectShort(BaseModel):
|
||||
id: str = Field(description="The unique identifier of the EU project.")
|
||||
title: Optional[str] = Field(
|
||||
default=None, description="The title of the EU project."
|
||||
)
|
||||
start_date: Optional[date] = Field(
|
||||
default=None, description="The funding start date of the EU project."
|
||||
)
|
||||
end_date: Optional[date] = Field(
|
||||
default=None, description="The funding end date of the EU project."
|
||||
)
|
||||
acronym: Optional[str] = Field(
|
||||
default=None, description="The acronym of the EU project."
|
||||
)
|
||||
|
||||
|
||||
class EuOrganizationProjectSummary(BaseModel):
|
||||
organization_id: str = Field(
|
||||
description="The unique identifier of the organization."
|
||||
)
|
||||
project_id: str = Field(description="The unique identifier of the project.")
|
||||
title: Optional[str] = Field(default=None, description="The title of the project.")
|
||||
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."
|
||||
)
|
||||
acronym: Optional[str] = Field(
|
||||
default=None, description="The acronym of the project."
|
||||
)
|
||||
ec_contribution: Optional[float] = Field(
|
||||
default=None,
|
||||
description="The EC contribution amount for the organization in the project.",
|
||||
)
|
||||
|
||||
|
||||
class EuOrganizationProjectSummaryPage(Page):
|
||||
elements: List[EuOrganizationProjectSummary] = Field(
|
||||
default_factory=list,
|
||||
description="The organization project summaries on this page.",
|
||||
)
|
||||
|
||||
|
||||
|
||||
################
|
||||
class EuCordisProjectType(StrEnum):
|
||||
FP7 = "fp7"
|
||||
|
||||
@@ -6,14 +6,10 @@ import urllib
|
||||
from inse.config import get_settings
|
||||
from inse.models.bund_project import BundProject
|
||||
from inse.projects.model import (
|
||||
BundProjectSummary,
|
||||
BundProjectPage,
|
||||
CordisEuProjectPage,
|
||||
DfgProjectPage,
|
||||
DfgProjectSummary,
|
||||
EuOrganizationProjectSummary,
|
||||
EuOrganizationProjectSummaryPage,
|
||||
EuOrganizationShort,
|
||||
EuProjectShort,
|
||||
FundingProject,
|
||||
FundingProjectPage,
|
||||
ProjectType,
|
||||
@@ -21,17 +17,12 @@ from inse.projects.model import (
|
||||
ProjectsSortBy,
|
||||
SortDirection,
|
||||
)
|
||||
from inse.projects.eu_cordis_projects_client import get_enriched_cordis_project_by_id
|
||||
from inse.models.dfg_project_details import DfgProjectDetails
|
||||
from inse.models.bund_project_details import BundProjectDetails
|
||||
from inse.models.cordis_eu_project import CordisEuProject
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster, 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.projects.logic import get_person_ids_by_institution_ids, get_dfg_project_ids_by_topic_ids, get_openalex_topics_for_dfg_projects, get_person_institutes
|
||||
from typing import Union
|
||||
|
||||
settings = get_settings()
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -189,7 +180,7 @@ def _complete_response_to_bund_project_page(
|
||||
hits_block = response.get("hits", {})
|
||||
total_hits = hits_block.get("total", {}).get("value", 0)
|
||||
elements = [
|
||||
BundProject.model_validate(hit["_source"]) for hit in hits_block.get("hits", [])
|
||||
BundProjectSummary.from_hit(hit) for hit in hits_block.get("hits", [])
|
||||
]
|
||||
return BundProjectPage(elements=elements, total=total_hits, page=page, size=size)
|
||||
|
||||
@@ -221,263 +212,10 @@ async def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails
|
||||
return None
|
||||
|
||||
|
||||
|
||||
# EU
|
||||
|
||||
|
||||
async def get_eu_organization_project_contributions(
|
||||
organization_names: List[str],
|
||||
projects_filtering_properties: ProjectsFilteringProperties,
|
||||
) -> EuOrganizationProjectSummaryPage:
|
||||
"""Fetches the contributions of EU organizations to projects based on the provided organization names and filtering properties, and returns a paginated summary of the projects.
|
||||
|
||||
Args:
|
||||
organization_names (List[str]): The list of organization names to fetch contributions for.
|
||||
projects_filtering_properties (ProjectsFilteringProperties): The filtering properties for the projects.
|
||||
|
||||
Returns:
|
||||
EuOrganizationProjectSummaryPage: The paginated summary of the projects.
|
||||
"""
|
||||
# Pagination depending on sorting criteria
|
||||
# For FUNDING_AMOUNT before on the organization project contributions
|
||||
# For the rest after the contributions are known on the real projects
|
||||
|
||||
organization_project_contributions = await get_eu_organization_contributions(
|
||||
organization_names=organization_names,
|
||||
)
|
||||
|
||||
total_projects, projects = await get_eu_organization_projects(
|
||||
project_contributions=list(organization_project_contributions.values()),
|
||||
projects_filtering_properties=projects_filtering_properties,
|
||||
)
|
||||
|
||||
elements: List[EuOrganizationProjectSummary] = _merge_project_data(
|
||||
projects=projects, contributions=organization_project_contributions
|
||||
)
|
||||
|
||||
if projects_filtering_properties.sort_by == ProjectsSortBy.FUNDING_AMOUNT:
|
||||
elements.sort(
|
||||
key=lambda x: x.ec_contribution or 0,
|
||||
reverse=projects_filtering_properties.sort_direction == SortDirection.DESC,
|
||||
)
|
||||
start = projects_filtering_properties.page * projects_filtering_properties.size
|
||||
end = start + projects_filtering_properties.size
|
||||
elements = elements[start:end]
|
||||
|
||||
return EuOrganizationProjectSummaryPage(
|
||||
elements=elements,
|
||||
total=total_projects,
|
||||
page=projects_filtering_properties.page,
|
||||
size=projects_filtering_properties.size,
|
||||
)
|
||||
|
||||
|
||||
async def get_eu_organization_contributions(
|
||||
organization_names: List[str],
|
||||
) -> Dict[str, EuOrganizationShort]:
|
||||
"""Fetches the contributions of EU organizations to projects based on the provided organization names.
|
||||
|
||||
Args:
|
||||
organization_names (List[str]): The list of organization names to fetch contributions for.
|
||||
|
||||
Returns:
|
||||
Dict[str, EuOrganizationShort]: A dictionary mapping project IDs to their corresponding organization contributions.
|
||||
"""
|
||||
|
||||
source = ["projectID", "organisationID", "ecContribution"]
|
||||
|
||||
query = {
|
||||
"terms": {
|
||||
"name.keyword": [
|
||||
name.upper() for name in organization_names if name.strip()
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD,
|
||||
cluster=ESCluster.INSE,
|
||||
source=source,
|
||||
size=10000,
|
||||
query=query,
|
||||
)
|
||||
|
||||
logger.debug(
|
||||
f"Received organization project contributions response: {json.dumps(response, indent=2)}"
|
||||
)
|
||||
|
||||
organization_project_contributions = _process_organization_project_contributions(
|
||||
response
|
||||
)
|
||||
|
||||
logger.debug(
|
||||
f"Found organization project contributions for organization names {organization_names}: {organization_project_contributions}"
|
||||
)
|
||||
|
||||
return organization_project_contributions
|
||||
|
||||
|
||||
def _process_organization_project_contributions(
|
||||
response: Dict[str, Any],
|
||||
) -> Dict[str, EuOrganizationShort]:
|
||||
"""Processes the raw Elasticsearch response to extract the contributions of EU organizations to projects.
|
||||
|
||||
Args:
|
||||
response (Dict[str, Any]): The raw Elasticsearch response.
|
||||
|
||||
Returns:
|
||||
Dict[str, EuOrganizationShort]: A dictionary mapping project IDs to their corresponding organization contributions.
|
||||
"""
|
||||
hits_block = response.get("hits", {})
|
||||
project_contributions: Dict[str, EuOrganizationShort] = {}
|
||||
for hit in hits_block.get("hits", []):
|
||||
source = hit.get("_source", {})
|
||||
project_id = source.get("projectID")
|
||||
organization_id = source.get("organisationID")
|
||||
ec_contribution = source.get("ecContribution")
|
||||
if project_id and organization_id:
|
||||
project_contributions[project_id] = EuOrganizationShort(
|
||||
project_id=project_id,
|
||||
organization_id=organization_id,
|
||||
ec_contribution=ec_contribution,
|
||||
)
|
||||
return project_contributions
|
||||
|
||||
|
||||
async def get_eu_organization_projects(
|
||||
project_contributions: List[EuOrganizationShort],
|
||||
projects_filtering_properties: ProjectsFilteringProperties,
|
||||
) -> Tuple[int, Dict[str, EuProjectShort]]:
|
||||
"""Fetches the projects associated with the given list of organization contributions, applying the specified filtering properties.
|
||||
|
||||
Args:
|
||||
project_contributions (List[EuOrganizationShort]): The list of organization contributions to fetch projects for.
|
||||
projects_filtering_properties (ProjectsFilteringProperties): The filtering properties to apply to the project search.
|
||||
|
||||
Returns:
|
||||
Tuple[int, Dict[str, EuProjectShort]]: A tuple containing the total number of projects and a dictionary mapping project IDs to their corresponding project details.
|
||||
"""
|
||||
project_ids = [contribution.project_id for contribution in project_contributions]
|
||||
|
||||
source = ["id", "title", "startDate", "endDate", "acronym"]
|
||||
|
||||
query = {
|
||||
"terms": {
|
||||
"id": project_ids,
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
projects_filtering_properties.query
|
||||
and projects_filtering_properties.query.strip()
|
||||
):
|
||||
query = {
|
||||
"bool": {
|
||||
"must": [
|
||||
{
|
||||
"match_phrase_prefix": {
|
||||
"title": {
|
||||
"query": projects_filtering_properties.query,
|
||||
"max_expansions": 50,
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"filter": query,
|
||||
}
|
||||
}
|
||||
|
||||
# Project contributions have been filtered before based on ecContribution
|
||||
if projects_filtering_properties.sort_by == ProjectsSortBy.FUNDING_AMOUNT:
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
|
||||
cluster=ESCluster.INSE,
|
||||
source=source,
|
||||
query=query,
|
||||
size=10000,
|
||||
)
|
||||
else:
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
|
||||
cluster=ESCluster.INSE,
|
||||
source=source,
|
||||
query=query,
|
||||
size=projects_filtering_properties.size,
|
||||
offset=projects_filtering_properties.page
|
||||
* projects_filtering_properties.size,
|
||||
sort=[
|
||||
{
|
||||
projects_filtering_properties.sort_by.to_cordis_eu_project_sort_field(): {
|
||||
"order": projects_filtering_properties.sort_direction
|
||||
}
|
||||
}
|
||||
],
|
||||
)
|
||||
|
||||
return _process_projects_response(response)
|
||||
|
||||
|
||||
def _process_projects_response(
|
||||
response: Dict[str, Any],
|
||||
) -> Tuple[int, Dict[str, EuProjectShort]]:
|
||||
"""Processes the raw Elasticsearch response to extract the project details and total count.
|
||||
|
||||
Args:
|
||||
response (Dict[str, Any]): The raw Elasticsearch response.
|
||||
|
||||
Returns:
|
||||
Tuple[int, Dict[str, EuProjectShort]]: A tuple containing the total number of projects and a dictionary mapping project IDs to their corresponding project details.
|
||||
"""
|
||||
hits_block = response.get("hits", {})
|
||||
total = hits_block.get("total", {}).get("value", 0)
|
||||
projects: Dict[str, EuProjectShort] = {}
|
||||
for hit in hits_block.get("hits", []):
|
||||
source = hit.get("_source", {})
|
||||
project_id = source.get("id")
|
||||
title = source.get("title")
|
||||
start_date = source.get("startDate")
|
||||
end_date = source.get("endDate")
|
||||
acronym = source.get("acronym")
|
||||
if not project_id:
|
||||
continue
|
||||
projects[project_id] = EuProjectShort(
|
||||
id=project_id,
|
||||
title=title,
|
||||
start_date=start_date,
|
||||
end_date=end_date,
|
||||
acronym=acronym,
|
||||
)
|
||||
|
||||
return total, projects
|
||||
|
||||
|
||||
def _merge_project_data(
|
||||
projects: Dict[str, EuProjectShort], contributions: Dict[str, EuOrganizationShort]
|
||||
) -> List[EuOrganizationProjectSummary]:
|
||||
"""Merges the project details with the organization contributions to create a list of EuOrganizationProjectSummary objects.
|
||||
|
||||
Args:
|
||||
projects (Dict[str, EuProjectShort]): The dictionary of project details.
|
||||
contributions (Dict[str, EuOrganizationShort]): The dictionary of organization contributions.
|
||||
|
||||
Returns:
|
||||
List[EuOrganizationProjectSummary]: The list of merged project-summary objects.
|
||||
"""
|
||||
merged_data = []
|
||||
for project_id, project_info in projects.items():
|
||||
contribution_info = contributions.get(project_id)
|
||||
if contribution_info:
|
||||
merged_entry = EuOrganizationProjectSummary(
|
||||
project_id=project_id,
|
||||
title=project_info.title,
|
||||
start_date=project_info.start_date,
|
||||
end_date=project_info.end_date,
|
||||
acronym=project_info.acronym,
|
||||
organization_id=contribution_info.organization_id,
|
||||
ec_contribution=contribution_info.ec_contribution,
|
||||
)
|
||||
merged_data.append(merged_entry)
|
||||
return merged_data
|
||||
|
||||
|
||||
def _get_raw_doi(doi: str) -> str:
|
||||
"""Extracts the raw DOI from a given DOI string, removing any URL prefixes if present.
|
||||
@@ -563,46 +301,6 @@ async def get_cordis_eu_project_ids_by_dois(dois: List[str]) -> List[str]:
|
||||
return list(project_ids)
|
||||
|
||||
|
||||
async def get_cordis_eu_projects_by_project_ids(
|
||||
project_ids: List[str],
|
||||
) -> CordisEuProjectPage:
|
||||
query = {"bool": {"filter": [{"terms": {"id": project_ids}}]}}
|
||||
|
||||
response = await elasticsearch.search(
|
||||
query=query,
|
||||
index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
|
||||
hits_block = response.get("hits", {})
|
||||
total_hits = hits_block.get("total", {}).get("value", 0)
|
||||
elements = [
|
||||
CordisEuProject.model_validate(hit["_source"])
|
||||
for hit in hits_block.get("hits", [])
|
||||
]
|
||||
return CordisEuProjectPage(
|
||||
elements=elements, total=total_hits, page=0, size=len(elements)
|
||||
)
|
||||
|
||||
|
||||
async def get_eu_cordis_projects_by_id(
|
||||
project_id: str,
|
||||
) -> Optional[Union[Fp7ProjectDetails, H2020ProjectDetails, HEUProjectDetails]]:
|
||||
"""
|
||||
Fetches and enriches a single Cordis EU project by its ID.
|
||||
|
||||
Args:
|
||||
project_id: The project ID to fetch
|
||||
|
||||
Returns:
|
||||
The enriched project details, or None if not found
|
||||
"""
|
||||
enriched_project = await get_enriched_cordis_project_by_id(
|
||||
project_id=project_id
|
||||
)
|
||||
return enriched_project
|
||||
|
||||
|
||||
# DFG
|
||||
async def search_dfg_projects(
|
||||
page: int,
|
||||
@@ -894,6 +592,232 @@ async def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]:
|
||||
return details
|
||||
return None
|
||||
|
||||
#BUND
|
||||
|
||||
async def get_bund_project_ids_by_topic_ids(topic_ids: List[str]) -> List[str]:
|
||||
"""
|
||||
Query the `projects_bund_openalex_topics` index to find BUND project IDs
|
||||
that match any of the given OpenAlex topic IDs.
|
||||
"""
|
||||
body: Dict[str, Any] = {
|
||||
"size": 0,
|
||||
"query": {
|
||||
"terms": {
|
||||
"topic_matches.topic_id": topic_ids
|
||||
}
|
||||
},
|
||||
"aggs": {
|
||||
"project_ids": {
|
||||
"terms": {
|
||||
"field": "project_id.keyword",
|
||||
"size": 10000
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.PROJECTS_BUND_TOPICS,
|
||||
body=body,
|
||||
cluster=ESCluster.INSE
|
||||
)
|
||||
print(f"Received response for topic_ids {topic_ids}: {json.dumps(response, indent=2)}")
|
||||
buckets = response.get("aggregations", {}).get("project_ids", {}).get("buckets", [])
|
||||
return [bucket["key"] for bucket in buckets]
|
||||
|
||||
|
||||
async def get_openalex_topics_for_bund_projects(project_ids: List[str]) -> Dict[str, List[Dict]]:
|
||||
"""
|
||||
Retrieve OpenAlex topic details for a list of BUND project IDs.
|
||||
Returns a dict mapping `project_id` -> list of topic_match objects.
|
||||
"""
|
||||
if not project_ids:
|
||||
return {}
|
||||
|
||||
body: Dict[str, Any] = {
|
||||
"size": 10000,
|
||||
"query": {
|
||||
"terms": {
|
||||
"project_id.keyword": project_ids
|
||||
}
|
||||
},
|
||||
"_source": ["project_id", "topic_matches"]
|
||||
}
|
||||
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.PROJECTS_BUND_TOPICS,
|
||||
body=body,
|
||||
cluster=ESCluster.INSE
|
||||
)
|
||||
|
||||
lookup: Dict[str, List[Dict]] = {}
|
||||
for hit in response.get("hits", {}).get("hits", []):
|
||||
src = hit["_source"]
|
||||
pid = src.get("project_id")
|
||||
if pid:
|
||||
lookup[pid] = src.get("topic_matches", [])
|
||||
return lookup
|
||||
|
||||
async def search_bund_projects_with_filters(
|
||||
executing_agency: Optional[List[str]] = None,
|
||||
institution_ids: Optional[List[int]] = None,
|
||||
funding_arts: Optional[List[str]] = None, # actually EuCordisProjectType, but treated as strings
|
||||
title: Optional[str] = None,
|
||||
keywords: Optional[List[str]] = None,
|
||||
topic_ids: Optional[List[str]] = None,
|
||||
filter_topic_ids: Optional[List[str]] = None,
|
||||
funding_start_years: Optional[List[str]] = None,
|
||||
funding_end_years: Optional[List[str]] = None,
|
||||
countries: Optional[List[str]] = None,
|
||||
page: int = 0,
|
||||
size: int = 10,
|
||||
sort_by: str = "title",
|
||||
sort_direction: str = "asc",
|
||||
fuzzy: bool = False,
|
||||
) -> BundProjectPage:
|
||||
"""
|
||||
Main search function for BUND projects, analogous to the DFG search.
|
||||
"""
|
||||
from_ = page * size
|
||||
|
||||
# Fields we need to build BundProject objects (validation aliases match these exact names)
|
||||
source_fields = [
|
||||
"Förderkennzeichen",
|
||||
"Ressort",
|
||||
"Ressort_fullname",
|
||||
"Referat",
|
||||
"Projektträger",
|
||||
"Projektträger_fullname",
|
||||
"Arb.-Einh.",
|
||||
"Zuwendungsempfänger",
|
||||
"Gemeindekennziffer",
|
||||
"Stadt/Gemeinde",
|
||||
"Ort",
|
||||
"Bundesland",
|
||||
"Staat",
|
||||
"Ausführende Stelle",
|
||||
"Thema",
|
||||
"Leistungsplansystematik",
|
||||
"Klartext Leistungsplansystematik",
|
||||
"Förderbeginn",
|
||||
"Förderende",
|
||||
"Fördersumme",
|
||||
"Förderprofil",
|
||||
"Verbundprojekt",
|
||||
"Förderart",
|
||||
"Publikationsdatum",
|
||||
"Unix-Timestamp",
|
||||
"datum",
|
||||
"neu",
|
||||
"Laufzeit",
|
||||
# Also include funding_start/end for sorting and filtering (they may also be needed)
|
||||
"funding_start",
|
||||
"funding_end",
|
||||
]
|
||||
|
||||
body: Dict[str, Any] = {
|
||||
"size": size,
|
||||
"from": from_,
|
||||
"_source": source_fields,
|
||||
"query": {},
|
||||
}
|
||||
|
||||
must_clauses: List[Dict[str, Any]] = []
|
||||
|
||||
# === Primary search clause: fuzzy(topic_ids) vs keyword phrase search ===
|
||||
if fuzzy and topic_ids:
|
||||
matching_project_ids = await get_bund_project_ids_by_topic_ids(topic_ids=topic_ids)
|
||||
if not matching_project_ids:
|
||||
return BundProjectPage(elements=[], total=0, page=page, size=size)
|
||||
must_clauses.append({"terms": {"Förderkennzeichen.keyword": matching_project_ids}})
|
||||
|
||||
elif keywords:
|
||||
keyword_clauses = []
|
||||
for kw in keywords:
|
||||
if kw.strip() == "":
|
||||
continue
|
||||
keyword_clauses.append({
|
||||
"multi_match": {
|
||||
"query": kw,
|
||||
"fields": ["Verbundprojekt"], # searching title/acronym field
|
||||
"type": "phrase_prefix",
|
||||
"max_expansions": 100,
|
||||
}
|
||||
})
|
||||
if keyword_clauses:
|
||||
must_clauses.append({"bool": {"must": keyword_clauses}})
|
||||
|
||||
# === Additional independent filters (applied regardless of fuzzy/keyword mode) ===
|
||||
if filter_topic_ids:
|
||||
matching_filter_ids = await get_bund_project_ids_by_topic_ids(topic_ids=filter_topic_ids)
|
||||
if not matching_filter_ids:
|
||||
return BundProjectPage(elements=[], total=0, page=page, size=size)
|
||||
must_clauses.append({"terms": {"Förderkennzeichen.keyword": matching_filter_ids}})
|
||||
|
||||
if title:
|
||||
must_clauses.append({
|
||||
"multi_match": {
|
||||
"query": title,
|
||||
"fields": ["Verbundprojekt"],
|
||||
"type": "phrase_prefix",
|
||||
"max_expansions": 100,
|
||||
}
|
||||
})
|
||||
|
||||
if executing_agency:
|
||||
must_clauses.append({"terms": {"Ausführende Stelle.keyword": executing_agency}})
|
||||
|
||||
if funding_arts:
|
||||
must_clauses.append({"terms": {"Förderart.keyword": funding_arts}})
|
||||
|
||||
if countries:
|
||||
must_clauses.append({"terms": {"Staat.keyword": countries}})
|
||||
|
||||
if funding_start_years:
|
||||
must_clauses.append({"terms": {"funding_start": funding_start_years}})
|
||||
|
||||
if funding_end_years:
|
||||
must_clauses.append({"terms": {"funding_end": funding_end_years}})
|
||||
|
||||
body["query"] = {"bool": {"must": must_clauses}} if must_clauses else {"match_all": {}}
|
||||
|
||||
# === Sorting ===
|
||||
sort_by = sort_by.strip().lower()
|
||||
sort_direction = sort_direction.strip().lower()
|
||||
if sort_direction not in ("asc", "desc"):
|
||||
sort_direction = "asc"
|
||||
|
||||
if sort_by == "title":
|
||||
sort_config = {"Verbundprojekt.keyword": {"order": sort_direction}}
|
||||
elif sort_by == "funding_start":
|
||||
sort_config = {"funding_start": {"order": sort_direction}}
|
||||
elif sort_by == "funding_end":
|
||||
sort_config = {"funding_end": {"order": sort_direction}}
|
||||
else:
|
||||
# Fallback to project ID
|
||||
sort_config = {"Förderkennzeichen.keyword": {"order": sort_direction}}
|
||||
|
||||
body["sort"] = [sort_config]
|
||||
|
||||
# === Execute Search ===
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.PROJECTS_BUND_V1,
|
||||
body=body,
|
||||
cluster=ESCluster.INSE,
|
||||
track_total_hits=True,
|
||||
)
|
||||
|
||||
hits = response.get("hits", {}).get("hits", [])
|
||||
|
||||
# Enrich with OpenAlex topics
|
||||
project_ids = [hit["_id"] for hit in hits]
|
||||
topic_lookup = await get_openalex_topics_for_bund_projects(project_ids=project_ids)
|
||||
print(f"Enriched BUND projects with topics: {json.dumps(topic_lookup, indent=2)}")
|
||||
for hit in hits:
|
||||
hit["_source"]["oa_topics"] = topic_lookup.get(hit["_id"], [])
|
||||
|
||||
return _complete_response_to_bund_project_page(response, page, size)
|
||||
|
||||
|
||||
# All
|
||||
|
||||
|
||||
@@ -5,9 +5,7 @@ from fastapi import APIRouter, Body, Depends, Path, Query, status
|
||||
|
||||
from inse.projects.model import (
|
||||
BundProjectPage,
|
||||
CordisEuProjectPage,
|
||||
DfgProjectPage,
|
||||
EuOrganizationProjectSummaryPage,
|
||||
FundingProjectPage,
|
||||
InstitutionFunderSummary,
|
||||
ProjectType,
|
||||
@@ -36,31 +34,6 @@ logger = logging.getLogger(__name__)
|
||||
router = APIRouter(prefix="/api/projects", tags=[Tags.PROJECTS])
|
||||
|
||||
|
||||
@router.get(
|
||||
"/author/{raw_oa_author_id}/eu",
|
||||
summary="Get EU projects for an author.",
|
||||
description="Returns a list of EU projects associated with the specified author ID.",
|
||||
operation_id="getEuProjectsForAuthor",
|
||||
responses={
|
||||
status.HTTP_200_OK: {
|
||||
"description": "Successful Response",
|
||||
"model": CordisEuProjectPage,
|
||||
},
|
||||
status.HTTP_404_NOT_FOUND: {"description": "Author not found"},
|
||||
},
|
||||
response_model_by_alias=False,
|
||||
)
|
||||
async def get_eu_projects_for_author(
|
||||
raw_oa_author_id: Annotated[str, Path(description="The author ID to filter by.")],
|
||||
) -> CordisEuProjectPage:
|
||||
logger.debug(
|
||||
f"Received request to get EU projects for author_id={raw_oa_author_id}"
|
||||
)
|
||||
return await projects_service.search_cordis_eu_projects_for_author_id(
|
||||
raw_oa_author_id=raw_oa_author_id,
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/institution/bund/search",
|
||||
summary="Get bund projects.",
|
||||
@@ -113,6 +86,91 @@ async def get_single_dfg_project(
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/bund/search",
|
||||
summary="Search BUND projects.",
|
||||
description="Returns a page of BUND project summaries.",
|
||||
operation_id="searchBundProjectsWithFilters",
|
||||
responses={
|
||||
status.HTTP_200_OK: {
|
||||
"description": "Successful Response",
|
||||
"model": BundProjectPage,
|
||||
},
|
||||
},
|
||||
response_model_by_alias=False,
|
||||
)
|
||||
async def search_bund_projects(
|
||||
|
||||
executing_agency: Annotated[
|
||||
Optional[List[str]],
|
||||
Query(description="Executing Agencies (Ausführende Stellen) to filter by."),
|
||||
] = None,
|
||||
funding_arts: Annotated[
|
||||
Optional[List[str]],
|
||||
Query(description="Project types to include: fp7, h2020, heu."),
|
||||
] = None,
|
||||
title: Annotated[
|
||||
Optional[str],
|
||||
Query(description="Project title/acronym search."),
|
||||
] = None,
|
||||
keywords: Annotated[
|
||||
Optional[List[str]],
|
||||
Query(description="Raw keywords to search in title/objective/keywords/topics."),
|
||||
] = None,
|
||||
topic_ids: Annotated[
|
||||
Optional[List[str]],
|
||||
Query(description="OpenAlex topic IDs used for fuzzy topic resolution."),
|
||||
] = None,
|
||||
filter_topic_ids: Annotated[
|
||||
Optional[List[str]],
|
||||
Query(description="Additional OpenAlex topic IDs used as mandatory filters."),
|
||||
] = None,
|
||||
funding_start_years: Annotated[
|
||||
Optional[List[str]],
|
||||
Query(description="Funding start years."),
|
||||
] = None,
|
||||
funding_end_years: Annotated[
|
||||
Optional[List[str]],
|
||||
Query(description="Funding end years."),
|
||||
] = None,
|
||||
countries: Annotated[
|
||||
Optional[List[str]],
|
||||
Query(description="Organization countries."),
|
||||
] = None,
|
||||
institution_ids: Annotated[
|
||||
Optional[List[str]],
|
||||
Query(description="Institution IDs to filter by."),
|
||||
] = None,
|
||||
page: Annotated[int, Query(description="The page number.", ge=0)] = 0,
|
||||
size: Annotated[int, Query(description="The page size.", ge=1)] = 20,
|
||||
sort_by: Annotated[str, Query(description="Sort field.")] = "title",
|
||||
sort_direction: Annotated[
|
||||
str,
|
||||
Query(description="Sort direction: asc or desc."),
|
||||
] = "asc",
|
||||
fuzzy: Annotated[
|
||||
bool,
|
||||
Query(description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."),
|
||||
] = False,
|
||||
) -> BundProjectPage:
|
||||
return await projects_service.search_bund_projects_with_filters(
|
||||
executing_agency=executing_agency,
|
||||
funding_arts=funding_arts,
|
||||
title=title,
|
||||
keywords=keywords,
|
||||
topic_ids=topic_ids,
|
||||
filter_topic_ids=filter_topic_ids,
|
||||
funding_start_years=funding_start_years,
|
||||
funding_end_years=funding_end_years,
|
||||
countries=countries,
|
||||
institution_ids=institution_ids,
|
||||
page=page,
|
||||
size=size,
|
||||
sort_by=sort_by,
|
||||
sort_direction=sort_direction,
|
||||
fuzzy=fuzzy
|
||||
)
|
||||
|
||||
@router.get(
|
||||
"/bund/{id}",
|
||||
summary="Get a single BUND project.",
|
||||
@@ -134,25 +192,37 @@ async def get_single_bund_project(
|
||||
return await projects_service.get_single_bund_project(
|
||||
project_id=id,
|
||||
)
|
||||
|
||||
|
||||
|
||||
########
|
||||
from inse.projects.model import EuCordisProjectSearchPage, EuCordisProjectType
|
||||
from inse.projects.service import search_eu_cordis_projects_summary_impl
|
||||
from inse.projects.service import search_eu_cordis_projects
|
||||
@router.get(
|
||||
"/eu/search",
|
||||
summary="Search EU CORDIS projects.",
|
||||
description="Returns a page of EU CORDIS project summaries across FP7, Horizon 2020 and Horizon Europe.",
|
||||
operation_id="searchEuCordisProjectsSummary",
|
||||
description=(
|
||||
"Returns a page of EU CORDIS project summaries across FP7, Horizon 2020 and "
|
||||
"Horizon Europe. Single entry point for EU CORDIS project search: filter by "
|
||||
"institution, author(s), organization, OpenAlex topic, programme, funding "
|
||||
"scheme, status, funding years and/or country, in any combination."
|
||||
),
|
||||
operation_id="searchEuCordisProjects",
|
||||
responses={
|
||||
status.HTTP_200_OK: {
|
||||
"description": "Successful Response",
|
||||
"model": EuCordisProjectSearchPage,
|
||||
},
|
||||
status.HTTP_404_NOT_FOUND: {"description": "Institution not found"},
|
||||
},
|
||||
response_model_by_alias=False,
|
||||
)
|
||||
async def search_eu_cordis_projects_summary(
|
||||
async def search_eu_cordis_projects_endpoint(
|
||||
institutions_search_client: Annotated[
|
||||
InstitutionsSearchClient, Depends(get_institutions_search_client)
|
||||
],
|
||||
raw_oa_institution_id: Annotated[
|
||||
Optional[str],
|
||||
Query(description="OpenAlex institution ID to filter by."),
|
||||
] = None,
|
||||
author_id: Annotated[
|
||||
Optional[str],
|
||||
Query(description="OpenAlex author ID to filter by."),
|
||||
@@ -226,12 +296,14 @@ async def search_eu_cordis_projects_summary(
|
||||
] = False,
|
||||
) -> EuCordisProjectSearchPage:
|
||||
logger.debug(
|
||||
"Received EU CORDIS search request: author_id=%s, author_ids=%s, "
|
||||
"Received EU CORDIS search request: raw_oa_institution_id=%s, "
|
||||
"author_id=%s, author_ids=%s, "
|
||||
"organization_ids=%s, organization_names=%s, project_types=%s, "
|
||||
"title=%s, keywords=%s, topic_ids=%s, filter_topic_ids=%s, "
|
||||
"funding_start_years=%s, funding_end_years=%s, countries=%s, "
|
||||
"framework_programmes=%s, funding_schemes=%s, statuses=%s, "
|
||||
"page=%s, size=%s, sort_by=%s, sort_direction=%s, fuzzy=%s",
|
||||
raw_oa_institution_id,
|
||||
author_id,
|
||||
author_ids,
|
||||
organization_ids,
|
||||
@@ -254,7 +326,9 @@ async def search_eu_cordis_projects_summary(
|
||||
fuzzy,
|
||||
)
|
||||
|
||||
return await search_eu_cordis_projects_summary_impl(
|
||||
return await search_eu_cordis_projects(
|
||||
institutions_search_client=institutions_search_client,
|
||||
raw_oa_institution_id=raw_oa_institution_id,
|
||||
author_id=author_id,
|
||||
author_ids=author_ids,
|
||||
organization_ids=organization_ids,
|
||||
@@ -383,35 +457,6 @@ async def get_institution_bund_projects_funding_over_time(
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/institution/eu/search",
|
||||
summary="Get EU projects.",
|
||||
description="Returns a page of EU projects based on the provided pagination parameters and optional institution filter.",
|
||||
operation_id="searchCordisEuProjects",
|
||||
responses={
|
||||
status.HTTP_200_OK: {
|
||||
"description": "Successful Response",
|
||||
"model": EuOrganizationProjectSummaryPage,
|
||||
},
|
||||
status.HTTP_404_NOT_FOUND: {"description": "Institution not found"},
|
||||
},
|
||||
response_model_by_alias=False,
|
||||
)
|
||||
async def search_cordis_eu_projects(
|
||||
institutions_search_client: Annotated[
|
||||
InstitutionsSearchClient, Depends(get_institutions_search_client)
|
||||
],
|
||||
projects_filtering_properties: Annotated[
|
||||
ProjectsFilteringProperties,
|
||||
Body(description="The filtering properties for the projects search."),
|
||||
],
|
||||
) -> EuOrganizationProjectSummaryPage:
|
||||
return await projects_service.search_cordis_eu_projects(
|
||||
institutions_search_client=institutions_search_client,
|
||||
projects_filtering_properties=projects_filtering_properties,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/institution/eu/funding-over-time",
|
||||
summary="Get funding over time for EU projects.",
|
||||
|
||||
@@ -3,21 +3,17 @@ import logging
|
||||
from typing import Any, Dict, List, Optional, Set
|
||||
|
||||
from inse.projects import projects_search_client
|
||||
from inse.projects.projects_search_client import (
|
||||
get_eu_organization_project_contributions,
|
||||
)
|
||||
from inse.projects.model import (
|
||||
BundProjectPage,
|
||||
CordisEuProjectPage,
|
||||
DfgProjectPage,
|
||||
EuOrganizationProjectSummaryPage,
|
||||
EuCordisProjectSearchPage,
|
||||
EuCordisProjectType,
|
||||
FundingProjectPage,
|
||||
InstitutionFunderSummary,
|
||||
ProjectType,
|
||||
ProjectsFilteringProperties,
|
||||
ProjectsSortBy,
|
||||
SortDirection,
|
||||
CordisEuProject
|
||||
)
|
||||
from inse.models.dfg_project_details import DfgProjectDetails
|
||||
from inse.models.bund_project_details import BundProjectDetails
|
||||
@@ -31,6 +27,10 @@ from inse.works.logic import get_publication_dois_of_author
|
||||
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.projects.eu_cordis_projects_client import (
|
||||
get_enriched_cordis_project_by_id,
|
||||
search_eu_cordis_projects as _search_eu_cordis_projects_es,
|
||||
)
|
||||
from typing import Union
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -102,51 +102,6 @@ async def get_bund_projects_by_institution_id(
|
||||
return response
|
||||
|
||||
|
||||
async def search_cordis_eu_projects(
|
||||
institutions_search_client: InstitutionsSearchClient,
|
||||
projects_filtering_properties: ProjectsFilteringProperties,
|
||||
) -> EuOrganizationProjectSummaryPage:
|
||||
if projects_filtering_properties.project_type != "eu":
|
||||
raise ValueError(
|
||||
f"Invalid project type: {projects_filtering_properties.project_type}. Expected 'eu'."
|
||||
)
|
||||
|
||||
return await get_cordis_eu_projects_by_institution_id(
|
||||
institutions_search_client=institutions_search_client,
|
||||
projects_filtering_properties=projects_filtering_properties,
|
||||
)
|
||||
|
||||
|
||||
async def get_cordis_eu_projects_by_institution_id(
|
||||
institutions_search_client: InstitutionsSearchClient,
|
||||
projects_filtering_properties: ProjectsFilteringProperties,
|
||||
) -> EuOrganizationProjectSummaryPage:
|
||||
if not projects_filtering_properties.raw_oa_institution_id:
|
||||
raise ValueError(
|
||||
"raw_oa_institution_id must be provided to fetch CORDIS EU projects by institution ID"
|
||||
)
|
||||
|
||||
logger.info(
|
||||
f"Fetching CORDIS EU projects for institution_id={projects_filtering_properties.raw_oa_institution_id}, page={projects_filtering_properties.page}, size={projects_filtering_properties.size}"
|
||||
)
|
||||
institution_aliases = (
|
||||
await institutions_search_client.get_institution_aliases_by_oa_institution_id(
|
||||
projects_filtering_properties.raw_oa_institution_id
|
||||
)
|
||||
)
|
||||
logger.debug(
|
||||
f"Found institution aliases for institution_id={projects_filtering_properties.raw_oa_institution_id}: {institution_aliases}"
|
||||
)
|
||||
|
||||
page = await get_eu_organization_project_contributions(
|
||||
organization_names=institution_aliases,
|
||||
projects_filtering_properties=projects_filtering_properties,
|
||||
)
|
||||
|
||||
logger.debug(f"get_cordis_eu_projects_by_institution_id response: {page}")
|
||||
|
||||
return page
|
||||
|
||||
async def get_dfg_projects_by_author_id(
|
||||
author_id: Optional[str],
|
||||
author_filter_ids: Optional[List[int]],
|
||||
@@ -232,18 +187,11 @@ async def get_institution_cordis_eu_projects_funding_over_time(
|
||||
institutions_search_client: InstitutionsSearchClient,
|
||||
raw_oa_institution_id: str,
|
||||
) -> InstitutionFunderSummary:
|
||||
institution_aliases = (
|
||||
await institutions_search_client.get_institution_aliases_by_oa_institution_id(
|
||||
raw_oa_institution_id
|
||||
)
|
||||
)
|
||||
page = await get_eu_organization_project_contributions(
|
||||
organization_names=institution_aliases,
|
||||
projects_filtering_properties=ProjectsFilteringProperties(
|
||||
project_type=ProjectType.EU,
|
||||
page=0,
|
||||
size=10000,
|
||||
),
|
||||
page = await search_eu_cordis_projects(
|
||||
page=0,
|
||||
size=10000,
|
||||
raw_oa_institution_id=raw_oa_institution_id,
|
||||
institutions_search_client=institutions_search_client,
|
||||
)
|
||||
|
||||
return _calculate_funding_over_time(
|
||||
@@ -251,7 +199,7 @@ async def get_institution_cordis_eu_projects_funding_over_time(
|
||||
projects=page.elements,
|
||||
funding_start_attr="start_date",
|
||||
funding_end_attr="end_date",
|
||||
funding_amount_attr="ec_contribution",
|
||||
funding_amount_attr="ec_max_contribution",
|
||||
)
|
||||
|
||||
|
||||
@@ -286,7 +234,42 @@ async def get_institution_bund_projects_funding_over_time(
|
||||
funding_end_attr="funding_end",
|
||||
funding_amount_attr="grant_amount",
|
||||
)
|
||||
|
||||
|
||||
#Bund
|
||||
async def search_bund_projects_with_filters(
|
||||
executing_agency: Optional[str],
|
||||
institution_ids: Optional[List[str]],
|
||||
title: Optional[str],
|
||||
keywords: Optional[List[str]],
|
||||
funding_arts: Optional[List[str]],
|
||||
topic_ids: Optional[List[str]],
|
||||
filter_topic_ids: Optional[List[str]],
|
||||
funding_start_years: Optional[List[str]],
|
||||
funding_end_years: Optional[List[str]],
|
||||
countries: Optional[List[str]],
|
||||
page: int,
|
||||
size: int,
|
||||
sort_by: str = "title",
|
||||
sort_direction: str = "asc",
|
||||
fuzzy: bool = False,
|
||||
) -> BundProjectPage:
|
||||
return await projects_search_client.search_bund_projects_with_filters(
|
||||
executing_agency=executing_agency,
|
||||
institution_ids=[],
|
||||
funding_arts=funding_arts,
|
||||
title=title,
|
||||
keywords=keywords,
|
||||
filter_topic_ids=filter_topic_ids,
|
||||
topic_ids=topic_ids,
|
||||
funding_start_years=funding_start_years,
|
||||
funding_end_years=funding_end_years,
|
||||
countries=countries,
|
||||
page=page,
|
||||
size=size,
|
||||
sort_by=sort_by,
|
||||
sort_direction=sort_direction,
|
||||
fuzzy=fuzzy
|
||||
)
|
||||
|
||||
def _calculate_funding_over_time(
|
||||
project_type: ProjectType,
|
||||
@@ -383,43 +366,14 @@ async def get_single_eu_cordis_project(
|
||||
) -> Optional[Union[Fp7ProjectDetails, H2020ProjectDetails, HEUProjectDetails]]:
|
||||
logger.debug(f"Fetching single EU Cordis project for id={project_id}")
|
||||
|
||||
project = await projects_search_client.get_eu_cordis_projects_by_id(project_id)
|
||||
project = await get_enriched_cordis_project_by_id(project_id)
|
||||
if not project:
|
||||
return None
|
||||
return project
|
||||
|
||||
|
||||
async def search_cordis_eu_projects_for_author_id(
|
||||
raw_oa_author_id: str,
|
||||
) -> CordisEuProjectPage:
|
||||
# EU CORDIS project search
|
||||
|
||||
# Direct search not possible -> multi stage search
|
||||
# 1. Exisiting author has publications with DOIs
|
||||
# 2. CORDIS EU projects have associated publications with DOIs
|
||||
# 3. Matching DOIs of author publications with DOIs of CORDIS EU project publications -> projects with associated publications of the author
|
||||
|
||||
dois = await get_publication_dois_of_author(raw_oa_author_id=raw_oa_author_id)
|
||||
|
||||
logger.debug(f"Found DOIs for author_id={raw_oa_author_id}: {dois}")
|
||||
|
||||
project_ids = await projects_search_client.get_cordis_eu_project_ids_by_dois(dois=dois)
|
||||
|
||||
logger.debug(
|
||||
f"Found project IDs {project_ids} for author_id={raw_oa_author_id} and dois={dois}"
|
||||
)
|
||||
|
||||
funding_project_page = await projects_search_client.get_cordis_eu_projects_by_project_ids(
|
||||
project_ids=project_ids
|
||||
)
|
||||
|
||||
return funding_project_page
|
||||
|
||||
|
||||
|
||||
################
|
||||
from inse.projects.eu_cordis_projects_client import search_eu_cordis_projects
|
||||
from inse.projects.model import EuCordisProjectType, EuCordisProjectSearchPage
|
||||
from inse.works.logic import get_publication_dois_of_author
|
||||
|
||||
async def _get_eu_project_ids_for_openalex_authors(
|
||||
author_ids: List[str],
|
||||
@@ -456,10 +410,12 @@ async def _get_eu_project_ids_for_openalex_authors(
|
||||
return list(set.intersection(*project_sets))
|
||||
|
||||
|
||||
async def search_eu_cordis_projects_summary_impl(
|
||||
async def search_eu_cordis_projects(
|
||||
page: int,
|
||||
size: int,
|
||||
project_types: Optional[List[EuCordisProjectType]] = None,
|
||||
raw_oa_institution_id: Optional[str] = None,
|
||||
institutions_search_client: Optional[InstitutionsSearchClient] = None,
|
||||
author_id: Optional[str] = None,
|
||||
author_ids: Optional[List[str]] = None,
|
||||
organization_ids: Optional[List[str]] = None,
|
||||
@@ -478,7 +434,37 @@ async def search_eu_cordis_projects_summary_impl(
|
||||
sort_direction: str = "asc",
|
||||
fuzzy: bool = False,
|
||||
) -> EuCordisProjectSearchPage:
|
||||
|
||||
"""Single entry point for EU CORDIS project search.
|
||||
|
||||
Institution search: pass raw_oa_institution_id (and institutions_search_client
|
||||
to resolve it to name aliases) - equivalent to what used to be a separate
|
||||
"institution projects" endpoint, now just another organization_names source.
|
||||
|
||||
Author search: pass author_id/author_ids (OpenAlex author ids). Multiple
|
||||
authors use AND semantics - a project must be linked to publications from
|
||||
every selected author.
|
||||
|
||||
All other filters (organization id/name, topic, framework programme,
|
||||
funding scheme, status, funding years, country) are ANDed together as in
|
||||
eu_cordis_projects_client.search_eu_cordis_projects.
|
||||
"""
|
||||
resolved_organization_names: List[str] = list(organization_names or [])
|
||||
|
||||
if raw_oa_institution_id:
|
||||
if institutions_search_client is None:
|
||||
raise ValueError(
|
||||
"institutions_search_client must be provided when raw_oa_institution_id is set"
|
||||
)
|
||||
institution_aliases = (
|
||||
await institutions_search_client.get_institution_aliases_by_oa_institution_id(
|
||||
raw_oa_institution_id
|
||||
)
|
||||
)
|
||||
logger.debug(
|
||||
f"Found institution aliases for institution_id={raw_oa_institution_id}: {institution_aliases}"
|
||||
)
|
||||
resolved_organization_names.extend(institution_aliases)
|
||||
print("Resolved organization names:", resolved_organization_names)
|
||||
all_author_ids: List[str] = []
|
||||
|
||||
if author_id:
|
||||
@@ -488,12 +474,12 @@ async def search_eu_cordis_projects_summary_impl(
|
||||
author_ids=all_author_ids
|
||||
)
|
||||
|
||||
return await search_eu_cordis_projects(
|
||||
return await _search_eu_cordis_projects_es(
|
||||
page=page,
|
||||
size=size,
|
||||
project_types=project_types,
|
||||
organization_ids=organization_ids,
|
||||
organization_names=organization_names,
|
||||
organization_names=resolved_organization_names or None,
|
||||
author_project_ids=author_project_ids,
|
||||
keywords=keywords,
|
||||
topic_ids=topic_ids,
|
||||
|
||||
Reference in New Issue
Block a user