Merge branch 'dev' into feature/timeline
This commit is contained in:
@@ -13,7 +13,6 @@ RUN pip install --root-user-action=ignore --no-cache-dir --disable-pip-version-c
|
||||
"pytest~=8.1.0" \
|
||||
"httpx~=0.27.0" \
|
||||
"python-multipart~=0.0.19"\
|
||||
"elasticsearch~=9.4.0" \
|
||||
"openai~=2.41.0"
|
||||
|
||||
COPY [ "src/main", "/home" ]
|
||||
|
||||
@@ -7,7 +7,6 @@ requires-python = ">=3.12"
|
||||
dependencies = [
|
||||
"cryptography~=42.0.0",
|
||||
"dotenv>=0.9.9",
|
||||
"elasticsearch~=9.4.0",
|
||||
"fastapi~=0.115.0",
|
||||
"httpx~=0.27.0",
|
||||
"openai~=2.41.0",
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from fastapi import HTTPException
|
||||
from starlette.status import HTTP_502_BAD_GATEWAY, HTTP_503_SERVICE_UNAVAILABLE
|
||||
|
||||
from . import model
|
||||
from .search_client import CompanyConnectionsSearchClient, MissingApiKeyError
|
||||
from inse.exceptions import MissingApiKeyError, ElasticsearchException, NotFoundException
|
||||
from .search_client import CompanyConnectionsSearchClient
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -23,22 +20,10 @@ async def get_company_connections_by_author_id(
|
||||
) -> model.CompanyConnectionsResponse:
|
||||
search_client = client or CompanyConnectionsSearchClient()
|
||||
|
||||
try:
|
||||
author_hit = await search_client.get_openalex_author(author_id)
|
||||
except MissingApiKeyError as exc:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Elasticsearch is not configured.",
|
||||
) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
logger.exception("OpenAlex author lookup failed for %s.", author_id)
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex author lookup failed.",
|
||||
) from exc
|
||||
author_hit = await search_client.get_openalex_author(author_id)
|
||||
|
||||
if author_hit is None:
|
||||
raise HTTPException(status_code=404, detail=f"Author {author_id} not found.")
|
||||
raise NotFoundException(f"Author {author_id} not found.")
|
||||
|
||||
source = author_hit.get("_source", {})
|
||||
display_name = _clean(source.get("display_name"))
|
||||
@@ -59,21 +44,9 @@ async def get_company_connections_by_author_id(
|
||||
connections=[],
|
||||
)
|
||||
|
||||
try:
|
||||
hr_response = await search_client.search_handelsregister_by_officer_name(
|
||||
display_name
|
||||
)
|
||||
except MissingApiKeyError as exc:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Elasticsearch is not configured.",
|
||||
) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
logger.exception("Handelsregister lookup failed for %s.", display_name)
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="Handelsregister lookup failed.",
|
||||
) from exc
|
||||
hr_response = await search_client.search_handelsregister_by_officer_name(
|
||||
display_name
|
||||
)
|
||||
|
||||
company_count, company_count_relation = _parse_total(hr_response)
|
||||
connections = _parse_company_connections(
|
||||
|
||||
@@ -5,8 +5,12 @@ import httpx
|
||||
from .. import config
|
||||
|
||||
|
||||
class MissingApiKeyError(Exception):
|
||||
pass
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster
|
||||
from inse.exceptions import ElasticsearchNotFoundException
|
||||
|
||||
|
||||
from inse.exceptions import MissingApiKeyError
|
||||
|
||||
|
||||
class CompanyConnectionsSearchClient:
|
||||
@@ -28,7 +32,7 @@ class CompanyConnectionsSearchClient:
|
||||
api_key
|
||||
if api_key is not None
|
||||
else config.settings.elasticsearch_api_key
|
||||
)
|
||||
)
|
||||
self.openalex_index = openalex_index
|
||||
self.handelsregister_index = handelsregister_index
|
||||
self.timeout = timeout
|
||||
@@ -39,26 +43,15 @@ class CompanyConnectionsSearchClient:
|
||||
return author_id.strip().removeprefix("https://openalex.org/")
|
||||
|
||||
async def get_openalex_author(self, author_id: str) -> dict[str, Any] | None:
|
||||
if not self.api_key:
|
||||
raise MissingApiKeyError("Elasticsearch API key is not configured.")
|
||||
|
||||
doc_id = self.openalex_doc_id(author_id)
|
||||
|
||||
async with httpx.AsyncClient(
|
||||
base_url=self.base_url,
|
||||
timeout=self.timeout,
|
||||
transport=self.transport,
|
||||
) as client:
|
||||
response = await client.get(
|
||||
f"/{self.openalex_index}/_doc/{doc_id}",
|
||||
headers={"Authorization": f"ApiKey {self.api_key}"},
|
||||
try:
|
||||
return await elasticsearch.get(
|
||||
index=self.openalex_index,
|
||||
doc_id=doc_id,
|
||||
cluster=ESCluster.NES,
|
||||
)
|
||||
|
||||
if response.status_code == 404:
|
||||
return None
|
||||
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
except ElasticsearchNotFoundException:
|
||||
return None
|
||||
|
||||
async def search_handelsregister_by_officer_name(
|
||||
self,
|
||||
@@ -66,27 +59,16 @@ class CompanyConnectionsSearchClient:
|
||||
size: int = 10000,
|
||||
track_total_hits: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
if not self.api_key:
|
||||
raise MissingApiKeyError("Elasticsearch API key is not configured.")
|
||||
|
||||
payload = self.handelsregister_officer_name_query(
|
||||
officer_name=officer_name,
|
||||
size=size,
|
||||
track_total_hits=track_total_hits,
|
||||
)
|
||||
|
||||
async with httpx.AsyncClient(
|
||||
base_url=self.base_url,
|
||||
timeout=self.timeout,
|
||||
transport=self.transport,
|
||||
) as client:
|
||||
response = await client.post(
|
||||
f"/{self.handelsregister_index}/_search",
|
||||
headers={"Authorization": f"ApiKey {self.api_key}"},
|
||||
json=payload,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
return await elasticsearch.search(
|
||||
index=self.handelsregister_index,
|
||||
body=payload,
|
||||
cluster=ESCluster.NES,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def handelsregister_officer_name_query(
|
||||
|
||||
@@ -1,3 +1,36 @@
|
||||
class NotFoundException(Exception):
|
||||
def __init__(self, message: str):
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
class ElasticsearchException(Exception):
|
||||
"""Base exception for all Elasticsearch integrations."""
|
||||
pass
|
||||
|
||||
|
||||
class ElasticsearchNotFoundException(NotFoundException, ElasticsearchException):
|
||||
"""Raised when an Elasticsearch document or index is not found."""
|
||||
pass
|
||||
|
||||
|
||||
class ElasticsearchConnectionException(ElasticsearchException):
|
||||
"""Raised when connecting to Elasticsearch fails."""
|
||||
pass
|
||||
|
||||
|
||||
class MissingApiKeyError(Exception):
|
||||
"""Raised when a required API key is missing."""
|
||||
pass
|
||||
|
||||
|
||||
class UpstreamAPIException(Exception):
|
||||
"""Raised when an upstream third-party service (e.g. REST API) fails."""
|
||||
def __init__(self, message: str, status_code: int = 502):
|
||||
self.message = message
|
||||
self.status_code = status_code
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
class BadRequestException(Exception):
|
||||
"""Raised when request parameters are invalid or validation fails."""
|
||||
pass
|
||||
|
||||
@@ -8,10 +8,11 @@ from typing import Any
|
||||
import httpx
|
||||
|
||||
from .. import config
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster
|
||||
|
||||
|
||||
class MissingApiKeyError(Exception):
|
||||
pass
|
||||
from inse.exceptions import MissingApiKeyError
|
||||
|
||||
|
||||
class FundedPublicationsSearchClient:
|
||||
@@ -177,15 +178,8 @@ class FundedPublicationsSearchClient:
|
||||
if not self.api_key:
|
||||
raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.")
|
||||
|
||||
async with httpx.AsyncClient(
|
||||
base_url=self.base_url,
|
||||
timeout=self.timeout,
|
||||
transport=self.transport,
|
||||
) as client:
|
||||
response = await client.post(
|
||||
f"/{self.index}/_search",
|
||||
headers={"Authorization": f"ApiKey {self.api_key}"},
|
||||
json=payload,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
return await elasticsearch.search(
|
||||
index=self.index,
|
||||
body=payload,
|
||||
cluster=ESCluster.NES,
|
||||
)
|
||||
|
||||
@@ -6,16 +6,11 @@
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from fastapi import HTTPException
|
||||
from pydantic import ValidationError
|
||||
from starlette.status import HTTP_502_BAD_GATEWAY
|
||||
from starlette.status import HTTP_503_SERVICE_UNAVAILABLE
|
||||
|
||||
from ..persons import logic as person_logic
|
||||
from . import model
|
||||
from .elastic_search_client import FundedPublicationsSearchClient
|
||||
from .elastic_search_client import MissingApiKeyError
|
||||
from inse.exceptions import MissingApiKeyError, ElasticsearchException, UpstreamAPIException
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -62,7 +57,7 @@ async def get_funders_by_author_id(
|
||||
funder_counts: dict[str, dict[str, Any]] = {}
|
||||
|
||||
normalized_author_id = FundedPublicationsSearchClient.indexed_author_id(author_id)
|
||||
author_name = _get_author_name(author_id)
|
||||
author_name = await _get_author_name(author_id)
|
||||
|
||||
try:
|
||||
_, all_hits = await _fetch_all_author_work_hits(
|
||||
@@ -92,9 +87,9 @@ async def get_funders_by_author_id(
|
||||
)
|
||||
except ValidationError as exc:
|
||||
logger.exception("Funders response could not be validated for author %s.", author_id)
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="Funders response could not be parsed.",
|
||||
raise UpstreamAPIException(
|
||||
message="Funders response could not be parsed.",
|
||||
status_code=502,
|
||||
) from exc
|
||||
|
||||
|
||||
@@ -144,26 +139,13 @@ async def _search_funded_publications(
|
||||
*,
|
||||
funded_only: bool = False,
|
||||
) -> dict:
|
||||
try:
|
||||
payload = search_client.publications_by_author_query(
|
||||
author_id,
|
||||
page,
|
||||
page_size,
|
||||
funded_only=funded_only,
|
||||
)
|
||||
return await search_client.search(payload)
|
||||
except MissingApiKeyError as exc:
|
||||
logger.error("OpenAlex works Elasticsearch API key is not configured.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="OpenAlex works search is not configured.",
|
||||
) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
logger.exception("OpenAlex works search request failed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex works search request failed.",
|
||||
) from exc
|
||||
payload = search_client.publications_by_author_query(
|
||||
author_id,
|
||||
page,
|
||||
page_size,
|
||||
funded_only=funded_only,
|
||||
)
|
||||
return await search_client.search(payload)
|
||||
|
||||
|
||||
def _parse_publication_search_response(data: dict) -> tuple[int, list[dict]]:
|
||||
@@ -180,9 +162,9 @@ def _parse_publication_search_response(data: dict) -> tuple[int, list[dict]]:
|
||||
return total, results
|
||||
|
||||
|
||||
def _get_author_name(author_id: str) -> str | None:
|
||||
async def _get_author_name(author_id: str) -> str | None:
|
||||
short_author_id = author_id.replace("https://openalex.org/", "")
|
||||
search_result = person_logic.search_persons(author_id=short_author_id)
|
||||
search_result = await person_logic.search_persons(author_id=short_author_id)
|
||||
|
||||
if not search_result.results:
|
||||
return None
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import json
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
from unittest.mock import AsyncMock, patch
|
||||
from inse.exceptions import MissingApiKeyError
|
||||
|
||||
from inse.funders import logic
|
||||
from inse.funders.elastic_search_client import FundedPublicationsSearchClient
|
||||
@@ -68,201 +66,177 @@ def _funded_publication_hit(
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_get_funders_by_author_id_aggregates_funders_and_awards(monkeypatch):
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
payload = json.loads(request.content.decode("utf-8"))
|
||||
assert payload["from"] == 0
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"hits": {
|
||||
"total": {"value": 2},
|
||||
"hits": [
|
||||
_funded_publication_hit(
|
||||
"https://openalex.org/W1",
|
||||
funder_id="https://openalex.org/F123",
|
||||
funder_name="Funder A",
|
||||
author_position="first",
|
||||
pdf_url="https://example.org/w1.pdf",
|
||||
abstract_inverted_index={
|
||||
"This": [0],
|
||||
"is": [1],
|
||||
"an": [2],
|
||||
"abstract.": [3],
|
||||
async def test_get_funders_by_author_id_aggregates_funders_and_awards():
|
||||
mock_es_response = {
|
||||
"hits": {
|
||||
"total": {"value": 2},
|
||||
"hits": [
|
||||
_funded_publication_hit(
|
||||
"https://openalex.org/W1",
|
||||
funder_id="https://openalex.org/F123",
|
||||
funder_name="Funder A",
|
||||
author_position="first",
|
||||
pdf_url="https://example.org/w1.pdf",
|
||||
abstract_inverted_index={
|
||||
"This": [0],
|
||||
"is": [1],
|
||||
"an": [2],
|
||||
"abstract.": [3],
|
||||
},
|
||||
extra_source={
|
||||
"title": "Example publication: full detail",
|
||||
"funders": [
|
||||
{
|
||||
"id": "https://openalex.org/F456",
|
||||
"display_name": "Funder B",
|
||||
}
|
||||
],
|
||||
"publication_year": 2020,
|
||||
"publication_date": "2020-05-10",
|
||||
"type": "article",
|
||||
"language": "en",
|
||||
"cited_by_count": 12,
|
||||
"is_retracted": False,
|
||||
"primary_location": {
|
||||
"pdf_url": "https://example.org/w1.pdf",
|
||||
"is_oa": True,
|
||||
"license": "cc-by",
|
||||
"source": {
|
||||
"display_name": "Example Journal",
|
||||
"type": "journal",
|
||||
},
|
||||
extra_source={
|
||||
"title": "Example publication: full detail",
|
||||
"funders": [
|
||||
{
|
||||
"id": "https://openalex.org/F456",
|
||||
"display_name": "Funder B",
|
||||
}
|
||||
],
|
||||
"publication_year": 2020,
|
||||
"publication_date": "2020-05-10",
|
||||
"type": "article",
|
||||
"language": "en",
|
||||
"cited_by_count": 12,
|
||||
"is_retracted": False,
|
||||
"primary_location": {
|
||||
"pdf_url": "https://example.org/w1.pdf",
|
||||
"is_oa": True,
|
||||
"license": "cc-by",
|
||||
"source": {
|
||||
"display_name": "Example Journal",
|
||||
"type": "journal",
|
||||
},
|
||||
},
|
||||
"open_access": {
|
||||
"is_oa": True,
|
||||
"oa_status": "gold",
|
||||
"any_repository_has_fulltext": True,
|
||||
},
|
||||
"primary_topic": {
|
||||
"display_name": "Clinical Trials",
|
||||
"subfield": {"display_name": "Medicine"},
|
||||
"field": {"display_name": "Health Sciences"},
|
||||
"domain": {"display_name": "Life Sciences"},
|
||||
},
|
||||
"topics": [
|
||||
{"display_name": "Trials", "score": 0.8},
|
||||
{"display_name": "Guidelines", "score": 0.6},
|
||||
],
|
||||
"keywords": [
|
||||
{"display_name": "randomised trials", "score": 0.9},
|
||||
{"display_name": "reporting guideline", "score": 0.7},
|
||||
],
|
||||
"counts_by_year": [
|
||||
{"year": 2024, "cited_by_count": 3},
|
||||
{"year": 2023, "cited_by_count": 2},
|
||||
],
|
||||
},
|
||||
),
|
||||
_funded_publication_hit(
|
||||
"https://openalex.org/W2",
|
||||
funder_id=None,
|
||||
funder_name=None,
|
||||
award_funder_id="https://openalex.org/F123",
|
||||
award_funder_name="Funder A",
|
||||
award_display_name="Project Grant",
|
||||
award_number="PG-42",
|
||||
author_position="last",
|
||||
),
|
||||
],
|
||||
},
|
||||
},
|
||||
)
|
||||
},
|
||||
"open_access": {
|
||||
"is_oa": True,
|
||||
"oa_status": "gold",
|
||||
"any_repository_has_fulltext": True,
|
||||
},
|
||||
"primary_topic": {
|
||||
"display_name": "Clinical Trials",
|
||||
"subfield": {"display_name": "Medicine"},
|
||||
"field": {"display_name": "Health Sciences"},
|
||||
"domain": {"display_name": "Life Sciences"},
|
||||
},
|
||||
"topics": [
|
||||
{"display_name": "Trials", "score": 0.8},
|
||||
{"display_name": "Guidelines", "score": 0.6},
|
||||
],
|
||||
"keywords": [
|
||||
{"display_name": "randomised trials", "score": 0.9},
|
||||
{"display_name": "reporting guideline", "score": 0.7},
|
||||
],
|
||||
"counts_by_year": [
|
||||
{"year": 2024, "cited_by_count": 3},
|
||||
{"year": 2023, "cited_by_count": 2},
|
||||
],
|
||||
},
|
||||
),
|
||||
_funded_publication_hit(
|
||||
"https://openalex.org/W2",
|
||||
funder_id=None,
|
||||
funder_name=None,
|
||||
award_funder_id="https://openalex.org/F123",
|
||||
award_funder_name="Funder A",
|
||||
award_display_name="Project Grant",
|
||||
award_number="PG-42",
|
||||
author_position="last",
|
||||
),
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
monkeypatch.setattr(
|
||||
logic.person_logic,
|
||||
"search_persons",
|
||||
lambda author_id: type(
|
||||
"Result",
|
||||
(),
|
||||
{"results": [type("Author", (), {"display_name": "Example Author"})()]},
|
||||
)(),
|
||||
)
|
||||
mock_author_result = type(
|
||||
"Result",
|
||||
(),
|
||||
{"results": [type("Author", (), {"display_name": "Example Author"})()]}
|
||||
)()
|
||||
|
||||
client = FundedPublicationsSearchClient(
|
||||
base_url="https://project.nes.uni-due.de/elastic",
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search, \
|
||||
patch("inse.persons.logic.search_persons", new_callable=AsyncMock) as mock_search_persons:
|
||||
mock_search.return_value = mock_es_response
|
||||
mock_search_persons.return_value = mock_author_result
|
||||
|
||||
response = await logic.get_funders_by_author_id("A5023888391", client=client)
|
||||
client = FundedPublicationsSearchClient(api_key="test-key")
|
||||
response = await logic.get_funders_by_author_id("A5023888391", client=client)
|
||||
|
||||
assert response.author_id == "https://openalex.org/A5023888391"
|
||||
assert response.author_name == "Example Author"
|
||||
assert response.funder_count == 2
|
||||
assert response.funders[0].funder_id == "https://openalex.org/F123"
|
||||
assert response.funders[0].funder_name == "Funder A"
|
||||
assert response.funders[0].publication_count == 2
|
||||
assert response.funders[0].author_position_count.first == 1
|
||||
assert response.funders[0].author_position_count.last == 1
|
||||
assert response.funders[0].publication_ids.first == ["https://openalex.org/W1"]
|
||||
assert response.funders[0].publication_ids.last == ["https://openalex.org/W2"]
|
||||
assert response.funders[0].publication_urls["https://openalex.org/W1"] == "https://example.org/w1.pdf"
|
||||
assert response.funders[0].publication_urls["https://openalex.org/W2"] == "https://openalex.org/W2"
|
||||
publication_detail = response.funders[0].publication_details["https://openalex.org/W1"]
|
||||
assert publication_detail.title == "Example publication: full detail"
|
||||
assert publication_detail.funder_names == ["Funder A", "Funder B"]
|
||||
assert publication_detail.abstract == "This is an abstract."
|
||||
assert publication_detail.publication_date == "2020-05-10"
|
||||
assert publication_detail.publication_type == "article"
|
||||
assert publication_detail.source_name == "Example Journal"
|
||||
assert publication_detail.source_type == "journal"
|
||||
assert publication_detail.is_open_access is True
|
||||
assert publication_detail.open_access_status == "gold"
|
||||
assert publication_detail.has_fulltext is True
|
||||
assert publication_detail.license == "cc-by"
|
||||
assert publication_detail.cited_by_count == 12
|
||||
assert publication_detail.primary_topic == "Clinical Trials"
|
||||
assert publication_detail.topic_field == "Health Sciences"
|
||||
assert publication_detail.topic_subfield == "Medicine"
|
||||
assert publication_detail.topic_domain == "Life Sciences"
|
||||
assert publication_detail.topics == ["Trials", "Guidelines"]
|
||||
assert publication_detail.keywords == ["randomised trials", "reporting guideline"]
|
||||
assert publication_detail.counts_by_year == [
|
||||
{"year": 2024, "cited_by_count": 3},
|
||||
{"year": 2023, "cited_by_count": 2},
|
||||
]
|
||||
assert response.funders[0].publication_details["https://openalex.org/W2"].grant_labels == [
|
||||
"Project Grant"
|
||||
]
|
||||
assert response.author_id == "https://openalex.org/A5023888391"
|
||||
assert response.author_name == "Example Author"
|
||||
assert response.funder_count == 2
|
||||
|
||||
funder_a = next(f for f in response.funders if f.funder_id == "https://openalex.org/F123")
|
||||
assert funder_a.funder_name == "Funder A"
|
||||
assert funder_a.publication_count == 2
|
||||
assert funder_a.author_position_count.first == 1
|
||||
assert funder_a.author_position_count.last == 1
|
||||
assert funder_a.publication_ids.first == ["https://openalex.org/W1"]
|
||||
assert funder_a.publication_ids.last == ["https://openalex.org/W2"]
|
||||
assert funder_a.publication_urls["https://openalex.org/W1"] == "https://example.org/w1.pdf"
|
||||
assert funder_a.publication_urls["https://openalex.org/W2"] == "https://openalex.org/W2"
|
||||
|
||||
pub1_detail = funder_a.publication_details["https://openalex.org/W1"]
|
||||
assert pub1_detail.title == "Example publication: full detail"
|
||||
assert pub1_detail.funder_names == ["Funder A", "Funder B"]
|
||||
assert pub1_detail.abstract == "This is an abstract."
|
||||
assert pub1_detail.publication_date == "2020-05-10"
|
||||
assert pub1_detail.publication_type == "article"
|
||||
assert pub1_detail.source_name == "Example Journal"
|
||||
assert pub1_detail.source_type == "journal"
|
||||
assert pub1_detail.is_open_access is True
|
||||
assert pub1_detail.open_access_status == "gold"
|
||||
assert pub1_detail.has_fulltext is True
|
||||
assert pub1_detail.license == "cc-by"
|
||||
assert pub1_detail.cited_by_count == 12
|
||||
assert pub1_detail.primary_topic == "Clinical Trials"
|
||||
assert pub1_detail.topic_field == "Health Sciences"
|
||||
assert pub1_detail.topic_subfield == "Medicine"
|
||||
assert pub1_detail.topic_domain == "Life Sciences"
|
||||
assert pub1_detail.topics == ["Trials", "Guidelines"]
|
||||
assert pub1_detail.keywords == ["randomised trials", "reporting guideline"]
|
||||
assert pub1_detail.counts_by_year == [
|
||||
{"year": 2024, "cited_by_count": 3},
|
||||
{"year": 2023, "cited_by_count": 2},
|
||||
]
|
||||
assert funder_a.publication_details["https://openalex.org/W2"].grant_labels == ["Project Grant"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_publication_grant_labels_ignore_funder_award_id_without_display_name(monkeypatch):
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"hits": {
|
||||
"total": {"value": 1},
|
||||
"hits": [
|
||||
_funded_publication_hit(
|
||||
"https://openalex.org/W3",
|
||||
funder_id="https://openalex.org/F123",
|
||||
funder_name="Funder A",
|
||||
award_funder_id="https://openalex.org/F123",
|
||||
award_funder_name="Funder A",
|
||||
award_display_name=None,
|
||||
award_number="ANR-12-1234",
|
||||
),
|
||||
],
|
||||
},
|
||||
},
|
||||
)
|
||||
async def test_publication_grant_labels_ignore_funder_award_id_without_display_name():
|
||||
mock_es_response = {
|
||||
"hits": {
|
||||
"total": {"value": 1},
|
||||
"hits": [
|
||||
_funded_publication_hit(
|
||||
"https://openalex.org/W3",
|
||||
funder_id="https://openalex.org/F123",
|
||||
funder_name="Funder A",
|
||||
award_funder_id="https://openalex.org/F123",
|
||||
award_funder_name="Funder A",
|
||||
award_display_name=None,
|
||||
award_number="ANR-12-1234",
|
||||
),
|
||||
],
|
||||
},
|
||||
}
|
||||
mock_author_result = type("Result", (), {"results": [type("Author", (), {"display_name": "Example Author"})()]})()
|
||||
|
||||
monkeypatch.setattr(
|
||||
logic.person_logic,
|
||||
"search_persons",
|
||||
lambda author_id: type(
|
||||
"Result",
|
||||
(),
|
||||
{"results": [type("Author", (), {"display_name": "Example Author"})()]},
|
||||
)(),
|
||||
)
|
||||
with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search, \
|
||||
patch("inse.persons.logic.search_persons", new_callable=AsyncMock) as mock_search_persons:
|
||||
mock_search.return_value = mock_es_response
|
||||
mock_search_persons.return_value = mock_author_result
|
||||
|
||||
client = FundedPublicationsSearchClient(
|
||||
base_url="https://project.nes.uni-due.de/elastic",
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
client = FundedPublicationsSearchClient(api_key="test-key")
|
||||
response = await logic.get_funders_by_author_id("A5023888391", client=client)
|
||||
|
||||
response = await logic.get_funders_by_author_id("A5023888391", client=client)
|
||||
|
||||
assert response.funders[0].publication_details["https://openalex.org/W3"].grant_labels == []
|
||||
assert response.funders[0].publication_details["https://openalex.org/W3"].grant_labels == []
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_get_funders_by_author_id_paginates_until_all_results_are_loaded(monkeypatch):
|
||||
async def test_get_funders_by_author_id_paginates_until_all_results_are_loaded():
|
||||
requested_pages: list[int] = []
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
payload = json.loads(request.content.decode("utf-8"))
|
||||
size = payload["size"]
|
||||
offset = payload["from"]
|
||||
async def mock_search_func(index, body, cluster=None):
|
||||
size = body["size"]
|
||||
offset = body["from"]
|
||||
page = offset // size + 1
|
||||
requested_pages.append(page)
|
||||
total = size + 1
|
||||
@@ -284,115 +258,87 @@ async def test_get_funders_by_author_id_paginates_until_all_results_are_loaded(m
|
||||
)
|
||||
]
|
||||
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"hits": {
|
||||
"total": {"value": total},
|
||||
"hits": hits,
|
||||
},
|
||||
return {
|
||||
"hits": {
|
||||
"total": {"value": total},
|
||||
"hits": hits,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
monkeypatch.setattr(
|
||||
logic.person_logic,
|
||||
"search_persons",
|
||||
lambda author_id: type("Result", (), {"results": []})(),
|
||||
)
|
||||
mock_author_result = type("Result", (), {"results": []})()
|
||||
|
||||
client = FundedPublicationsSearchClient(
|
||||
base_url="https://project.nes.uni-due.de/elastic",
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
with patch("inse.integrations.elasticsearch.search", side_effect=mock_search_func) as mock_search, \
|
||||
patch("inse.persons.logic.search_persons", new_callable=AsyncMock) as mock_search_persons:
|
||||
mock_search_persons.return_value = mock_author_result
|
||||
|
||||
response = await logic.get_funders_by_author_id("A5023888391", client=client)
|
||||
client = FundedPublicationsSearchClient(api_key="test-key")
|
||||
response = await logic.get_funders_by_author_id("A5023888391", client=client)
|
||||
|
||||
assert requested_pages == [1, 2]
|
||||
assert response.funder_count > 1
|
||||
funder_names = {funder.funder_name for funder in response.funders}
|
||||
assert "Funder 1" in funder_names
|
||||
assert requested_pages == [1, 2]
|
||||
assert response.funder_count > 1
|
||||
funder_names = {funder.funder_name for funder in response.funders}
|
||||
assert "Funder 1" in funder_names
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_get_funders_by_author_id_ignores_publications_without_funders(monkeypatch):
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"hits": {
|
||||
"total": {"value": 2},
|
||||
"hits": [
|
||||
_funded_publication_hit(
|
||||
"https://openalex.org/W1",
|
||||
funder_id="https://openalex.org/F123",
|
||||
funder_name="Bundesministerium",
|
||||
),
|
||||
_funded_publication_hit(
|
||||
"https://openalex.org/W2",
|
||||
funder_id=None,
|
||||
funder_name=None,
|
||||
),
|
||||
],
|
||||
},
|
||||
},
|
||||
)
|
||||
async def test_get_funders_by_author_id_ignores_publications_without_funders():
|
||||
mock_es_response = {
|
||||
"hits": {
|
||||
"total": {"value": 2},
|
||||
"hits": [
|
||||
_funded_publication_hit(
|
||||
"https://openalex.org/W1",
|
||||
funder_id="https://openalex.org/F123",
|
||||
funder_name="Bundesministerium",
|
||||
),
|
||||
_funded_publication_hit(
|
||||
"https://openalex.org/W2",
|
||||
funder_id=None,
|
||||
funder_name=None,
|
||||
),
|
||||
],
|
||||
},
|
||||
}
|
||||
mock_author_result = type("Result", (), {"results": []})()
|
||||
|
||||
monkeypatch.setattr(
|
||||
logic.person_logic,
|
||||
"search_persons",
|
||||
lambda author_id: type("Result", (), {"results": []})(),
|
||||
)
|
||||
with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search, \
|
||||
patch("inse.persons.logic.search_persons", new_callable=AsyncMock) as mock_search_persons:
|
||||
mock_search.return_value = mock_es_response
|
||||
mock_search_persons.return_value = mock_author_result
|
||||
|
||||
client = FundedPublicationsSearchClient(
|
||||
base_url="https://project.nes.uni-due.de/elastic",
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
client = FundedPublicationsSearchClient(api_key="test-key")
|
||||
response = await logic.get_funders_by_author_id("A5093075883", client=client)
|
||||
|
||||
response = await logic.get_funders_by_author_id("A5093075883", client=client)
|
||||
|
||||
assert response.funder_count == 1
|
||||
assert response.funders[0].funder_name == "Bundesministerium"
|
||||
assert response.funders[0].publication_count == 1
|
||||
assert response.funder_count == 1
|
||||
assert response.funders[0].funder_name == "Bundesministerium"
|
||||
assert response.funders[0].publication_count == 1
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_get_funders_by_author_id_returns_empty_when_elasticsearch_has_no_funders(monkeypatch):
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={"hits": {"total": {"value": 0}, "hits": []}},
|
||||
)
|
||||
async def test_get_funders_by_author_id_returns_empty_when_elasticsearch_has_no_funders():
|
||||
mock_es_response = {"hits": {"total": {"value": 0}, "hits": []}}
|
||||
mock_author_result = type("Result", (), {"results": []})()
|
||||
|
||||
monkeypatch.setattr(
|
||||
logic.person_logic,
|
||||
"search_persons",
|
||||
lambda author_id: type("Result", (), {"results": []})(),
|
||||
)
|
||||
with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search, \
|
||||
patch("inse.persons.logic.search_persons", new_callable=AsyncMock) as mock_search_persons:
|
||||
mock_search.return_value = mock_es_response
|
||||
mock_search_persons.return_value = mock_author_result
|
||||
|
||||
client = FundedPublicationsSearchClient(
|
||||
base_url="https://project.nes.uni-due.de/elastic",
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
client = FundedPublicationsSearchClient(api_key="test-key")
|
||||
response = await logic.get_funders_by_author_id("A5093075883", client=client)
|
||||
|
||||
response = await logic.get_funders_by_author_id("A5093075883", client=client)
|
||||
|
||||
assert response.funder_count == 0
|
||||
assert response.funders == []
|
||||
assert response.funder_count == 0
|
||||
assert response.funders == []
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_get_funders_by_author_id_maps_missing_api_key_to_service_unavailable(monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
logic.person_logic,
|
||||
"search_persons",
|
||||
lambda author_id: type("Result", (), {"results": []})(),
|
||||
)
|
||||
client = FundedPublicationsSearchClient(api_key="")
|
||||
async def test_get_funders_by_author_id_maps_missing_api_key_to_service_unavailable():
|
||||
mock_author_result = type("Result", (), {"results": []})()
|
||||
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
await logic.get_funders_by_author_id("A5023888391", client=client)
|
||||
with patch("inse.persons.logic.search_persons", new_callable=AsyncMock) as mock_search_persons:
|
||||
mock_search_persons.return_value = mock_author_result
|
||||
|
||||
assert exc.value.status_code == 503
|
||||
client = FundedPublicationsSearchClient(api_key="")
|
||||
|
||||
with pytest.raises(MissingApiKeyError):
|
||||
await logic.get_funders_by_author_id("A5023888391", client=client)
|
||||
|
||||
@@ -20,7 +20,7 @@ class InstitutionsSearchClient:
|
||||
"""
|
||||
pass
|
||||
|
||||
def get_institution_by_id(self, raw_oa_institution_id: str) -> Institution:
|
||||
async def get_institution_by_id(self, raw_oa_institution_id: str) -> Institution:
|
||||
"""Retrieves an institution by its raw OpenAlex institution ID.
|
||||
|
||||
Args:
|
||||
@@ -38,7 +38,7 @@ class InstitutionsSearchClient:
|
||||
}
|
||||
}
|
||||
|
||||
res = elasticsearch.search(index="openalex-institutions", query=query, size=1)
|
||||
res = await elasticsearch.search(index="openalex-institutions", query=query, size=1)
|
||||
|
||||
hits = res.get("hits", {}).get("hits", [])
|
||||
if not hits:
|
||||
@@ -72,7 +72,7 @@ class InstitutionsSearchClient:
|
||||
# TODO: Implement actual retrieval of RCN from Elasticsearch or another source instead of using a hardcoded cache.
|
||||
return cache.get(raw_institution_id)
|
||||
|
||||
def get_institutions_by_name(
|
||||
async def get_institutions_by_name(
|
||||
self,
|
||||
name: str,
|
||||
page: int = 0,
|
||||
@@ -122,7 +122,7 @@ class InstitutionsSearchClient:
|
||||
query,
|
||||
)
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index="openalex-institutions",
|
||||
offset=page * size,
|
||||
size=size,
|
||||
@@ -189,7 +189,7 @@ class InstitutionsSearchClient:
|
||||
query,
|
||||
)
|
||||
|
||||
res = elasticsearch.search(index="openalex-authors", query=query)
|
||||
res = await elasticsearch.search(index="openalex-authors", query=query)
|
||||
hits = res.get("hits", {}).get("hits", [])
|
||||
|
||||
# Extracting display_name directly from the author document source
|
||||
@@ -200,7 +200,7 @@ class InstitutionsSearchClient:
|
||||
}
|
||||
return list(authors)
|
||||
|
||||
def search_institutions(
|
||||
async def search_institutions(
|
||||
self,
|
||||
query_text: str,
|
||||
country_code: str | None = None,
|
||||
@@ -265,7 +265,7 @@ class InstitutionsSearchClient:
|
||||
}
|
||||
}
|
||||
|
||||
res = elasticsearch.search(
|
||||
res = await elasticsearch.search(
|
||||
index="openalex-institutions",
|
||||
query=query,
|
||||
size=limit,
|
||||
@@ -288,7 +288,7 @@ class InstitutionsSearchClient:
|
||||
|
||||
return [Institution.from_dict(hit["_source"]) for hit in hits]
|
||||
|
||||
def get_institution_aliases_by_oa_institution_id(
|
||||
async def get_institution_aliases_by_oa_institution_id(
|
||||
self, raw_oa_institution_id: str
|
||||
) -> List[str]:
|
||||
"""Get a list of institution aliases for a given institution ID, including both display name alternatives and predefined aliases.
|
||||
@@ -299,7 +299,7 @@ class InstitutionsSearchClient:
|
||||
Returns:
|
||||
List[str]: A list of aliases for the given institution ID.
|
||||
"""
|
||||
institution = self.get_institution_by_id(raw_oa_institution_id)
|
||||
institution = await self.get_institution_by_id(raw_oa_institution_id)
|
||||
aliases = list(
|
||||
self.augment_aliases(set(institution.display_name_alternatives or []))
|
||||
| self.get_predefined_institution_aliases(raw_oa_institution_id)
|
||||
@@ -426,7 +426,7 @@ class InstitutionsSearchClient:
|
||||
)
|
||||
return None
|
||||
|
||||
def get_cordis_eu_organisation_ids_by_oa_institution_id(
|
||||
async def get_cordis_eu_organisation_ids_by_oa_institution_id(
|
||||
self, raw_oa_institution_id: str
|
||||
) -> Optional[List[str]]:
|
||||
"""Retrieves the corresponding EU organisation IDs for a given OpenAlex institution ID by searching for institution aliases and matching them against the Cordis EU organisations indices.
|
||||
@@ -439,7 +439,7 @@ class InstitutionsSearchClient:
|
||||
"""
|
||||
|
||||
institution_aliases = set(
|
||||
self.get_institution_aliases_by_oa_institution_id(
|
||||
await self.get_institution_aliases_by_oa_institution_id(
|
||||
raw_oa_institution_id=raw_oa_institution_id
|
||||
)
|
||||
)
|
||||
@@ -476,7 +476,7 @@ class InstitutionsSearchClient:
|
||||
|
||||
try:
|
||||
# IMPORTANT: The indices are named organizations and not organisations. + 15 Minutes debugging why the search returns 0 results
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index="cordis_eu_*_organizations", body=body, cluster="inse"
|
||||
)
|
||||
except Exception as e:
|
||||
|
||||
@@ -9,10 +9,8 @@ from copy import deepcopy
|
||||
from typing import Any, Optional
|
||||
|
||||
import httpx
|
||||
from fastapi import HTTPException
|
||||
from pydantic import ValidationError
|
||||
from starlette.status import HTTP_400_BAD_REQUEST
|
||||
from starlette.status import HTTP_502_BAD_GATEWAY
|
||||
from inse.exceptions import UpstreamAPIException, BadRequestException
|
||||
|
||||
from inse.models.openalex.autocomplete_response import AutocompleteResponse
|
||||
from inse.models.openalex.autocomplete_response_meta import AutocompleteResponseMeta
|
||||
@@ -41,7 +39,7 @@ _VALID_INSTITUTION_TYPES = {
|
||||
async def get_institution_by_id(
|
||||
raw_institution_id: str, client: InstitutionsSearchClient
|
||||
) -> Institution:
|
||||
return client.get_institution_by_id(raw_institution_id)
|
||||
return await client.get_institution_by_id(raw_institution_id)
|
||||
|
||||
|
||||
async def list_institutions(
|
||||
@@ -58,10 +56,7 @@ async def list_institutions(
|
||||
client: OpenAlexInstitutionsClient | None = None,
|
||||
) -> InstitutionsListResponse:
|
||||
if sample is not None and (sort or page not in (None, 1)):
|
||||
raise HTTPException(
|
||||
status_code=HTTP_400_BAD_REQUEST,
|
||||
detail="sample cannot be combined with sort or page.",
|
||||
)
|
||||
raise BadRequestException("sample cannot be combined with sort or page.")
|
||||
|
||||
openalex_client = client or OpenAlexInstitutionsClient()
|
||||
|
||||
@@ -86,12 +81,12 @@ async def list_institutions(
|
||||
except ValueError:
|
||||
if exc.response.text:
|
||||
detail = exc.response.text
|
||||
raise HTTPException(status_code=status_code, detail=detail) from exc
|
||||
raise UpstreamAPIException(message=detail, status_code=status_code) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
logger.exception("OpenAlex institutions request failed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex institutions request failed.",
|
||||
raise UpstreamAPIException(
|
||||
message="OpenAlex institutions request failed.",
|
||||
status_code=502,
|
||||
) from exc
|
||||
|
||||
try:
|
||||
@@ -102,9 +97,9 @@ async def list_institutions(
|
||||
)
|
||||
except ValidationError as exc:
|
||||
logger.exception("OpenAlex institutions response could not be parsed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex institutions response could not be parsed.",
|
||||
raise UpstreamAPIException(
|
||||
message="OpenAlex institutions response could not be parsed.",
|
||||
status_code=502,
|
||||
) from exc
|
||||
|
||||
|
||||
@@ -120,7 +115,7 @@ async def autocomplete_institutions(
|
||||
Returns institution options for autocomplete inputs using the local
|
||||
Elasticsearch cluster via the provided client.
|
||||
"""
|
||||
institutions = client.search_institutions(
|
||||
institutions = await client.search_institutions(
|
||||
query_text=query,
|
||||
country_code=country_code,
|
||||
institution_type=institution_type,
|
||||
|
||||
@@ -72,7 +72,7 @@ async def search_institutions_by_name(
|
||||
),
|
||||
] = "asc",
|
||||
) -> InstitutionPage:
|
||||
return client.get_institutions_by_name(
|
||||
return await client.get_institutions_by_name(
|
||||
name=name,
|
||||
page=page,
|
||||
size=size,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import httpx
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
from inse.exceptions import BadRequestException
|
||||
|
||||
from inse.institutions import logic
|
||||
from inse.institutions.search_client import OpenAlexInstitutionsClient
|
||||
@@ -96,11 +96,9 @@ async def test_list_institutions_maps_openalex_response_to_model():
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_institutions_rejects_sample_with_sort():
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
with pytest.raises(BadRequestException) as exc_info:
|
||||
await logic.list_institutions(sample=10, sort="works_count:desc")
|
||||
|
||||
assert exc_info.value.status_code == 400
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_institutions_accepts_practical_openalex_type_variants():
|
||||
|
||||
@@ -1,13 +1,37 @@
|
||||
import json
|
||||
import logging
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
from typing import Any, Dict, AsyncIterator, List, Optional, Tuple
|
||||
|
||||
import httpx
|
||||
|
||||
from inse.exceptions import (
|
||||
ElasticsearchException,
|
||||
ElasticsearchNotFoundException,
|
||||
ElasticsearchConnectionException,
|
||||
MissingApiKeyError,
|
||||
)
|
||||
from inse.model import ESCluster, ESIndex
|
||||
from .. import config
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_client: Optional[httpx.AsyncClient] = None
|
||||
_loop = None
|
||||
|
||||
|
||||
def get_client() -> httpx.AsyncClient:
|
||||
global _client, _loop
|
||||
try:
|
||||
import asyncio
|
||||
current_loop = asyncio.get_running_loop()
|
||||
except RuntimeError:
|
||||
current_loop = None
|
||||
|
||||
if _client is None or _loop is not current_loop:
|
||||
_client = httpx.AsyncClient(timeout=httpx.Timeout(30.0))
|
||||
_loop = current_loop
|
||||
return _client
|
||||
|
||||
|
||||
def _cluster_credentials(cluster: ESCluster) -> Tuple[str, str]:
|
||||
"""Retrieves the Elasticsearch URL and API key for the specified cluster from the configuration.
|
||||
@@ -21,22 +45,23 @@ def _cluster_credentials(cluster: ESCluster) -> Tuple[str, str]:
|
||||
Returns:
|
||||
Tuple[str, str]: The Elasticsearch URL and API key for the specified cluster.
|
||||
"""
|
||||
|
||||
|
||||
if cluster == ESCluster.NES:
|
||||
if (
|
||||
not config.settings.elasticsearch_url
|
||||
or not config.settings.elasticsearch_api_key
|
||||
):
|
||||
raise ValueError(
|
||||
raise MissingApiKeyError(
|
||||
"Elasticsearch URL and API key must be set in the configuration for cluster 'nes'"
|
||||
)
|
||||
|
||||
return config.settings.elasticsearch_url, config.settings.elasticsearch_api_key
|
||||
elif cluster == ESCluster.INSE:
|
||||
if (
|
||||
not config.settings.elasticsearch_inse_url
|
||||
or not config.settings.elasticsearch_inse_api_key
|
||||
):
|
||||
raise ValueError(
|
||||
raise MissingApiKeyError(
|
||||
"Elasticsearch INSE URL and API key must be set in the configuration for cluster 'inse'"
|
||||
)
|
||||
|
||||
@@ -80,8 +105,18 @@ def _index_to_cluster(index: ESIndex) -> Optional[ESCluster]:
|
||||
return None
|
||||
|
||||
|
||||
def search(
|
||||
index: ESIndex | List[ESIndex],
|
||||
def _wrap_exception(e: Exception) -> Exception:
|
||||
if isinstance(e, httpx.HTTPStatusError):
|
||||
if e.response.status_code == 404:
|
||||
return ElasticsearchNotFoundException(f"Elasticsearch resource not found: {e}")
|
||||
return ElasticsearchException(f"Elasticsearch returned status {e.response.status_code}: {e}")
|
||||
elif isinstance(e, httpx.RequestError):
|
||||
return ElasticsearchConnectionException(f"Elasticsearch connection error: {e}")
|
||||
return ElasticsearchException(f"Unexpected Elasticsearch error: {e}")
|
||||
|
||||
|
||||
async def search(
|
||||
index: ESIndex | List[ESIndex] | str | List[str],
|
||||
query: Optional[Dict] = None,
|
||||
source: Optional[List] = None,
|
||||
size: Optional[int] = None,
|
||||
@@ -112,10 +147,11 @@ def search(
|
||||
clusters = set()
|
||||
if isinstance(index, list):
|
||||
for idx in index:
|
||||
cluster_for_index = _index_to_cluster(idx)
|
||||
if cluster_for_index is not None:
|
||||
clusters.add(cluster_for_index)
|
||||
else:
|
||||
if isinstance(idx, ESIndex):
|
||||
cluster_for_index = _index_to_cluster(idx)
|
||||
if cluster_for_index is not None:
|
||||
clusters.add(cluster_for_index)
|
||||
elif isinstance(index, ESIndex):
|
||||
cluster_for_index = _index_to_cluster(index)
|
||||
if cluster_for_index is not None:
|
||||
clusters.add(cluster_for_index)
|
||||
@@ -156,24 +192,125 @@ def search(
|
||||
"At least one of 'query', 'body', 'source', 'size', 'offset', 'sort' must be provided"
|
||||
)
|
||||
|
||||
with httpx.Client(timeout=httpx.Timeout(30.0)) as client:
|
||||
logger.debug(
|
||||
f"Sending search request to Elasticsearch cluster '{cluster}' at {elasticsearch_url} for {index} with payload: {json.dumps(payload)}"
|
||||
)
|
||||
if isinstance(index, list):
|
||||
index_str = ",".join(index)
|
||||
else:
|
||||
index_str = index
|
||||
client = get_client()
|
||||
logger.debug(
|
||||
f"Sending search request to Elasticsearch cluster '{cluster}' at {elasticsearch_url} for {index} with payload: {json.dumps(payload)}"
|
||||
)
|
||||
if isinstance(index, list):
|
||||
index_str = ",".join(str(idx) for idx in index)
|
||||
else:
|
||||
index_str = str(index)
|
||||
|
||||
response = client.post(
|
||||
try:
|
||||
response = await client.post(
|
||||
f"{elasticsearch_url}/{index_str}/_search", json=payload, headers=headers
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
except Exception as exc:
|
||||
raise _wrap_exception(exc) from exc
|
||||
|
||||
|
||||
def get(
|
||||
index: ESIndex,
|
||||
async def open_point_in_time(index: str, keep_alive: str = "1m", cluster: str = "nes") -> str:
|
||||
"""Opens a point-in-time on the given index and returns its id."""
|
||||
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
||||
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
|
||||
|
||||
client = get_client()
|
||||
try:
|
||||
response = await client.post(
|
||||
f"{elasticsearch_url}/{index}/_pit",
|
||||
params={"keep_alive": keep_alive},
|
||||
headers=headers,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()["id"]
|
||||
except Exception as exc:
|
||||
raise _wrap_exception(exc) from exc
|
||||
|
||||
|
||||
async def close_point_in_time(pit_id: str, cluster: str = "nes") -> None:
|
||||
"""Closes a previously opened point-in-time."""
|
||||
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
||||
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
|
||||
|
||||
client = get_client()
|
||||
try:
|
||||
response = await client.request(
|
||||
"DELETE",
|
||||
f"{elasticsearch_url}/_pit",
|
||||
json={"id": pit_id},
|
||||
headers=headers,
|
||||
)
|
||||
response.raise_for_status()
|
||||
except Exception as exc:
|
||||
raise _wrap_exception(exc) from exc
|
||||
|
||||
|
||||
async def scan(
|
||||
index: str,
|
||||
query: Dict,
|
||||
source: Optional[List] = None,
|
||||
page_size: int = 1000,
|
||||
keep_alive: str = "1m",
|
||||
cluster: str = "nes",
|
||||
) -> AsyncIterator[Dict[str, Any]]:
|
||||
"""Yields every hit matching ``query`` using a point-in-time + ``search_after``.
|
||||
|
||||
Unlike ``from``/``size`` pagination, this is not bounded by
|
||||
``index.max_result_window``, so it can stream result sets larger than 10k.
|
||||
"""
|
||||
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
||||
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
|
||||
|
||||
pit_id = await open_point_in_time(index, keep_alive=keep_alive, cluster=cluster)
|
||||
search_after: Optional[List] = None
|
||||
try:
|
||||
client = get_client()
|
||||
while True:
|
||||
payload: Dict[str, Any] = {
|
||||
"size": page_size,
|
||||
"query": query,
|
||||
"pit": {"id": pit_id, "keep_alive": keep_alive},
|
||||
"sort": [{"_shard_doc": "asc"}],
|
||||
"track_total_hits": False,
|
||||
}
|
||||
if source is not None:
|
||||
payload["_source"] = source
|
||||
if search_after is not None:
|
||||
payload["search_after"] = search_after
|
||||
|
||||
try:
|
||||
response = await client.post(
|
||||
f"{elasticsearch_url}/_search", json=payload, headers=headers
|
||||
)
|
||||
response.raise_for_status()
|
||||
except Exception as exc:
|
||||
raise _wrap_exception(exc) from exc
|
||||
|
||||
result = response.json()
|
||||
|
||||
hits = result.get("hits", {}).get("hits", [])
|
||||
if not hits:
|
||||
break
|
||||
|
||||
for hit in hits:
|
||||
yield hit
|
||||
|
||||
# The pit id can be refreshed between requests; keep the latest.
|
||||
pit_id = result.get("pit_id", pit_id)
|
||||
search_after = hits[-1].get("sort")
|
||||
if search_after is None or len(hits) < page_size:
|
||||
break
|
||||
finally:
|
||||
try:
|
||||
await close_point_in_time(pit_id, cluster=cluster)
|
||||
except Exception:
|
||||
logger.exception("Failed to close Elasticsearch point-in-time.")
|
||||
|
||||
|
||||
async def get(
|
||||
index: ESIndex | str,
|
||||
doc_id: str,
|
||||
source: Optional[list] = None,
|
||||
cluster: ESCluster = ESCluster.NES,
|
||||
@@ -187,9 +324,56 @@ def get(
|
||||
if source is not None:
|
||||
params["_source_includes"] = ",".join(source)
|
||||
|
||||
with httpx.Client() as client:
|
||||
response = client.get(
|
||||
client = get_client()
|
||||
try:
|
||||
response = await client.get(
|
||||
f"{elasticsearch_url}/{index}/_doc/{doc_id}", params=params, headers=headers
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
except Exception as exc:
|
||||
raise _wrap_exception(exc) from exc
|
||||
|
||||
|
||||
async def update(
|
||||
index: str,
|
||||
doc_id: str,
|
||||
doc: Dict[str, Any],
|
||||
cluster: ESCluster = ESCluster.NES,
|
||||
) -> Dict[str, Any]:
|
||||
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
||||
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
|
||||
|
||||
client = get_client()
|
||||
try:
|
||||
response = await client.post(
|
||||
f"{elasticsearch_url}/{index}/_update/{doc_id}",
|
||||
json={"doc": doc},
|
||||
headers=headers,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
except Exception as exc:
|
||||
raise _wrap_exception(exc) from exc
|
||||
|
||||
|
||||
async def index_doc(
|
||||
index: str,
|
||||
doc_id: str,
|
||||
document: Dict[str, Any],
|
||||
cluster: ESCluster = ESCluster.NES,
|
||||
) -> Dict[str, Any]:
|
||||
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
||||
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
|
||||
|
||||
client = get_client()
|
||||
try:
|
||||
response = await client.put(
|
||||
f"{elasticsearch_url}/{index}/_doc/{doc_id}",
|
||||
json=document,
|
||||
headers=headers,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
except Exception as exc:
|
||||
raise _wrap_exception(exc) from exc
|
||||
|
||||
@@ -18,6 +18,7 @@ import json
|
||||
from . import schema
|
||||
from . import model
|
||||
from . import config
|
||||
from inse.integrations import elasticsearch
|
||||
|
||||
|
||||
from inse.models.openalex.topic import Topic
|
||||
@@ -103,56 +104,42 @@ def _load_topic_cache() -> dict:
|
||||
return {}
|
||||
|
||||
|
||||
def build_topic_cache(page_size: int = 200, save_json: bool = True) -> dict:
|
||||
async def build_topic_cache(save_json: bool = True) -> dict:
|
||||
"""
|
||||
Fetch topics from the hosted OpenAlex topics index and build a lookup cache (scheduled task).
|
||||
|
||||
Arguments:
|
||||
page_size (int): Number of topics to fetch per request (default: 200)
|
||||
save_json (bool): Whether to save the cache as a JSON file (default: True)
|
||||
|
||||
Returns:
|
||||
taxonomy_cache (dict): The topic hierarchy dictionary.
|
||||
"""
|
||||
output_filename: str = "topic_hierarchy_cache.json"
|
||||
headers = {
|
||||
"Authorization": f"ApiKey {config.settings.elasticsearch_api_key}",
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
taxonomy_cache = {}
|
||||
offset = 0
|
||||
|
||||
with httpx.Client(timeout=30.0) as client:
|
||||
while True:
|
||||
payload = {"query": {"match_all": {}}, "from": offset, "size": page_size}
|
||||
response = client.post(
|
||||
config.settings.elasticsearch_url + "/openalex-topics/_search",
|
||||
json=payload,
|
||||
headers=headers,
|
||||
)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
try:
|
||||
async for hit in elasticsearch.scan(
|
||||
index="openalex-topics",
|
||||
query={"match_all": {}},
|
||||
source=["display_name", "name", "id", "subfield", "field", "domain"],
|
||||
cluster="nes",
|
||||
):
|
||||
source = hit.get("_source", {})
|
||||
topic_name = source.get("display_name") or source.get("name")
|
||||
if not topic_name:
|
||||
continue
|
||||
|
||||
hits = data.get("hits", {}).get("hits", [])
|
||||
if not hits:
|
||||
break
|
||||
taxonomy_cache[topic_name] = {
|
||||
"topic_id": source.get("id") or hit.get("_id", ""),
|
||||
"subfield": source.get("subfield", {}).get("display_name", ""),
|
||||
"field": source.get("field", {}).get("display_name", ""),
|
||||
"domain": source.get("domain", {}).get("display_name", ""),
|
||||
}
|
||||
except Exception as exc:
|
||||
logger.error("Failed to scan topics from Elasticsearch: %s", exc)
|
||||
|
||||
for hit in hits:
|
||||
source = hit.get("_source", {})
|
||||
topic_name = source.get("display_name") or source.get("name")
|
||||
if not topic_name:
|
||||
continue
|
||||
|
||||
taxonomy_cache[topic_name] = {
|
||||
"topic_id": source.get("id") or hit.get("_id", ""),
|
||||
"subfield": source.get("subfield", {}).get("display_name", ""),
|
||||
"field": source.get("field", {}).get("display_name", ""),
|
||||
"domain": source.get("domain", {}).get("display_name", ""),
|
||||
}
|
||||
|
||||
offset += len(hits)
|
||||
logger.info("Processed %s topics total", len(taxonomy_cache))
|
||||
logger.info("Processed %s topics total", len(taxonomy_cache))
|
||||
|
||||
if save_json:
|
||||
data_json = json.dumps(taxonomy_cache, indent=2, ensure_ascii=True)
|
||||
|
||||
@@ -14,7 +14,13 @@ from fastapi.responses import JSONResponse, RedirectResponse
|
||||
|
||||
from inse.collaboration_network.router import router as collaboration_network_router
|
||||
from inse.company_connections.service import router as company_connections_router
|
||||
from inse.exceptions import NotFoundException
|
||||
from inse.exceptions import (
|
||||
NotFoundException,
|
||||
ElasticsearchException,
|
||||
MissingApiKeyError,
|
||||
UpstreamAPIException,
|
||||
BadRequestException,
|
||||
)
|
||||
from inse.funders.service import router as funders_service_router
|
||||
from inse.projects.router import router as projects_router
|
||||
from inse.university_ranking.router import router as university_ranking_router
|
||||
@@ -34,6 +40,7 @@ from inse.institutions.router import router as institutions_router
|
||||
from . import config
|
||||
from .account.service import router as account_router
|
||||
from .service import router as service_router
|
||||
from inse.patents.service import router as patents_service_router, patents_router as patents_all_router
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -61,6 +68,7 @@ app.include_router(account_router)
|
||||
app.include_router(patents_service_router)
|
||||
app.include_router(university_ranking_router)
|
||||
app.include_router(projects_router)
|
||||
app.include_router(patents_all_router)
|
||||
|
||||
app.add_middleware(
|
||||
ETagCacheMiddleware,
|
||||
@@ -76,11 +84,37 @@ app.add_middleware(
|
||||
)
|
||||
|
||||
|
||||
# exception handlers
|
||||
|
||||
@app.exception_handler(NotFoundException)
|
||||
async def handle_not_found(request: Request, exc: NotFoundException):
|
||||
return JSONResponse(status_code=404, content={"message": str(exc)})
|
||||
|
||||
|
||||
@app.exception_handler(ElasticsearchException)
|
||||
async def handle_elasticsearch_error(request: Request, exc: ElasticsearchException):
|
||||
logger.error("Elasticsearch integration error: %s", str(exc))
|
||||
return JSONResponse(status_code=502, content={"message": "Search service temporarily unavailable"})
|
||||
|
||||
|
||||
@app.exception_handler(MissingApiKeyError)
|
||||
async def handle_missing_api_key(request: Request, exc: MissingApiKeyError):
|
||||
logger.error("Configuration error: %s", str(exc))
|
||||
return JSONResponse(status_code=503, content={"message": str(exc) or "Search service is not configured"})
|
||||
|
||||
|
||||
@app.exception_handler(UpstreamAPIException)
|
||||
async def handle_upstream_api_error(request: Request, exc: UpstreamAPIException):
|
||||
logger.error("Upstream API error: %s", str(exc))
|
||||
return JSONResponse(status_code=exc.status_code, content={"message": exc.message})
|
||||
|
||||
|
||||
@app.exception_handler(BadRequestException)
|
||||
async def handle_bad_request(request: Request, exc: BadRequestException):
|
||||
logger.error("Bad Request: %s", str(exc))
|
||||
return JSONResponse(status_code=400, content={"message": str(exc)})
|
||||
|
||||
|
||||
@app.exception_handler(404)
|
||||
async def redirect(_, __):
|
||||
return RedirectResponse(url="/inse-webapp/")
|
||||
|
||||
@@ -55,10 +55,44 @@ class ESIndex(StrEnum):
|
||||
OPENALEX_AUTHORS = "openalex-authors"
|
||||
OPENALEX_INSTITUTIONS = "openalex-institutions"
|
||||
OPENALEX_PUBLICATIONS = "openalex-publications"
|
||||
|
||||
CORDIS_EU_ORGANIZATIONS_WILDCARD = "cordis_eu_*_organizations"
|
||||
CORDIS_EU_PROJECTS_WILDCARD = "cordis_eu_*_projects"
|
||||
CORDIS_EU_PUBLICATIONS_WILDCARD = "cordis_eu_*_publications"
|
||||
|
||||
EPO_INDEX = "epo_index_1.0"
|
||||
USPTO_INDEX = "uspto_patents_3.0"
|
||||
|
||||
PROJECTS_BUND_V1 = "projects_bund_v1"
|
||||
PROJECTS_DFG_ALL = "projects_dfg_all"
|
||||
PROJECTS_DFG_ALL = "projects_dfg_all"
|
||||
|
||||
CORDIS_EU_ORGANIZATIONS_WILDCARD = "cordis_eu_*_organizations"
|
||||
CORDIS_EU_PROJECTS_WILDCARD = "cordis_eu_*_projects"
|
||||
CORDIS_EU_PUBLICATIONS_WILDCARD = "cordis_eu_*_publications"
|
||||
CORDIS_EU_FP7_OGANIZATIONS = "cordis_eu_fp7_organizations"
|
||||
# FP7
|
||||
CORDIS_EU_FP7_ORGANIZATIONS = "cordis_eu_fp7_organizations"
|
||||
CORDIS_EU_FP7_PUBLICATIONS = "cordis_eu_fp7_publications"
|
||||
CORDIS_EU_FP7_PROJECT_IPRS = "cordis_eu_fp7_project_iprs"
|
||||
CORDIS_EU_FP7_REPORT_SUMMARIES = "cordis_eu_fp7_report_summaries"
|
||||
CORDIS_EU_FP7_TOPICS = "cordis_eu_fp7_topics"
|
||||
CORDIS_EU_FP7_WEB_LINKS = "cordis_eu_fp7_web_links"
|
||||
CORDIS_EU_FP7_EUROSCIVOC = "cordis_eu_fp7_euroscivoc"
|
||||
CORDIS_EU_FP7_LEGAL_BASIS = "cordis_eu_fp7_legal_basis"
|
||||
|
||||
# Horizon 2020
|
||||
CORDIS_EU_HORIZON_2020_ORGANIZATIONS = "cordis_eu_horizon_2020_organizations"
|
||||
CORDIS_EU_HORIZON_2020_PUBLICATIONS = "cordis_eu_horizon_2020_publications"
|
||||
CORDIS_EU_HORIZON_2020_DELIVERABLES = "cordis_eu_horizon_2020_deliverables"
|
||||
CORDIS_EU_HORIZON_2020_REPORT_SUMMARIES = "cordis_eu_horizon_2020_report_summaries"
|
||||
CORDIS_EU_HORIZON_2020_TOPICS = "cordis_eu_horizon_2020_topics"
|
||||
CORDIS_EU_HORIZON_2020_WEB_LINKS = "cordis_eu_horizon_2020_web_links"
|
||||
CORDIS_EU_HORIZON_2020_EUROSCIVOC = "cordis_eu_horizon_2020_euroscivoc"
|
||||
CORDIS_EU_HORIZON_2020_LEGAL_BASIS = "cordis_eu_horizon_2020_legal_basis"
|
||||
CORDIS_EU_HORIZON_2020_ERC_PIS = "cordis_eu_horizon_2020_erc_pis"
|
||||
|
||||
# Horizon Europe
|
||||
CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS = "cordis_eu_horizon_europe_organizations"
|
||||
CORDIS_EU_HORIZON_EUROPE_PUBLICATIONS = "cordis_eu_horizon_europe_publications"
|
||||
CORDIS_EU_HORIZON_EUROPE_DELIVERABLES = "cordis_eu_horizon_europe_deliverables"
|
||||
CORDIS_EU_HORIZON_EUROPE_REPORT_SUMMARIES = "cordis_eu_horizon_europe_report_summaries"
|
||||
CORDIS_EU_HORIZON_EUROPE_TOPICS = "cordis_eu_horizon_europe_topics"
|
||||
CORDIS_EU_HORIZON_EUROPE_WEB_LINKS = "cordis_eu_horizon_europe_web_links"
|
||||
CORDIS_EU_HORIZON_EUROPE_EUROSCIVOC = "cordis_eu_horizon_europe_euroscivoc"
|
||||
CORDIS_EU_HORIZON_EUROPE_LEGAL_BASIS = "cordis_eu_horizon_europe_legal_basis"
|
||||
@@ -0,0 +1,98 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
CORDIS FP7 Multi-Index API
|
||||
|
||||
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by OpenAPI Generator (https://openapi-generator.tech)
|
||||
|
||||
Do not edit the class manually.
|
||||
""" # noqa: E501
|
||||
|
||||
|
||||
from __future__ import annotations
|
||||
import pprint
|
||||
import re # noqa: F401
|
||||
import json
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictStr
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
|
||||
class Fp7EurosciVoc(BaseModel):
|
||||
"""
|
||||
Fp7EurosciVoc
|
||||
""" # noqa: E501
|
||||
code: Optional[StrictStr] = None
|
||||
description: Optional[StrictStr] = None
|
||||
id: Optional[StrictStr] = None
|
||||
path: Optional[StrictStr] = None
|
||||
project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
|
||||
title: Optional[StrictStr] = None
|
||||
__properties: ClassVar[List[str]] = ["code", "description", "id", "path", "projectID", "title"]
|
||||
|
||||
model_config = ConfigDict(
|
||||
validate_by_name=True,
|
||||
validate_by_alias=True,
|
||||
validate_assignment=True,
|
||||
protected_namespaces=(),
|
||||
)
|
||||
|
||||
|
||||
def to_str(self) -> str:
|
||||
"""Returns the string representation of the model using alias"""
|
||||
return pprint.pformat(self.model_dump(by_alias=True))
|
||||
|
||||
def to_json(self) -> str:
|
||||
"""Returns the JSON representation of the model using alias"""
|
||||
return json.dumps(to_jsonable_python(self.to_dict()))
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, json_str: str) -> Optional[Self]:
|
||||
"""Create an instance of Fp7EurosciVoc from a JSON string"""
|
||||
return cls.from_dict(json.loads(json_str))
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Return the dictionary representation of the model using alias.
|
||||
|
||||
This has the following differences from calling pydantic's
|
||||
`self.model_dump(by_alias=True)`:
|
||||
|
||||
* `None` is only added to the output dict for nullable fields that
|
||||
were set at model initialization. Other fields with value `None`
|
||||
are ignored.
|
||||
"""
|
||||
excluded_fields: Set[str] = set([
|
||||
])
|
||||
|
||||
_dict = self.model_dump(
|
||||
by_alias=True,
|
||||
exclude=excluded_fields,
|
||||
exclude_none=True,
|
||||
)
|
||||
return _dict
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
|
||||
"""Create an instance of Fp7EurosciVoc from a dict"""
|
||||
if obj is None:
|
||||
return None
|
||||
|
||||
if not isinstance(obj, dict):
|
||||
return cls.model_validate(obj)
|
||||
|
||||
_obj = cls.model_validate({
|
||||
"code": obj.get("code"),
|
||||
"description": obj.get("description"),
|
||||
"id": obj.get("id"),
|
||||
"path": obj.get("path"),
|
||||
"projectID": obj.get("projectID"),
|
||||
"title": obj.get("title")
|
||||
})
|
||||
return _obj
|
||||
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
CORDIS FP7 Multi-Index API
|
||||
|
||||
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by OpenAPI Generator (https://openapi-generator.tech)
|
||||
|
||||
Do not edit the class manually.
|
||||
""" # noqa: E501
|
||||
|
||||
|
||||
from __future__ import annotations
|
||||
import pprint
|
||||
import re # noqa: F401
|
||||
import json
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictStr
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
|
||||
class Fp7LegalBasis(BaseModel):
|
||||
"""
|
||||
Fp7LegalBasis
|
||||
""" # noqa: E501
|
||||
id: Optional[StrictStr] = None
|
||||
legal_basis: Optional[StrictStr] = Field(default=None, alias="legalBasis")
|
||||
project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
|
||||
title: Optional[StrictStr] = None
|
||||
unique_programme_part: Optional[StrictStr] = Field(default=None, alias="uniqueProgrammePart")
|
||||
__properties: ClassVar[List[str]] = ["id", "legalBasis", "projectID", "title", "uniqueProgrammePart"]
|
||||
|
||||
model_config = ConfigDict(
|
||||
validate_by_name=True,
|
||||
validate_by_alias=True,
|
||||
validate_assignment=True,
|
||||
protected_namespaces=(),
|
||||
)
|
||||
|
||||
|
||||
def to_str(self) -> str:
|
||||
"""Returns the string representation of the model using alias"""
|
||||
return pprint.pformat(self.model_dump(by_alias=True))
|
||||
|
||||
def to_json(self) -> str:
|
||||
"""Returns the JSON representation of the model using alias"""
|
||||
return json.dumps(to_jsonable_python(self.to_dict()))
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, json_str: str) -> Optional[Self]:
|
||||
"""Create an instance of Fp7LegalBasis from a JSON string"""
|
||||
return cls.from_dict(json.loads(json_str))
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Return the dictionary representation of the model using alias.
|
||||
|
||||
This has the following differences from calling pydantic's
|
||||
`self.model_dump(by_alias=True)`:
|
||||
|
||||
* `None` is only added to the output dict for nullable fields that
|
||||
were set at model initialization. Other fields with value `None`
|
||||
are ignored.
|
||||
"""
|
||||
excluded_fields: Set[str] = set([
|
||||
])
|
||||
|
||||
_dict = self.model_dump(
|
||||
by_alias=True,
|
||||
exclude=excluded_fields,
|
||||
exclude_none=True,
|
||||
)
|
||||
return _dict
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
|
||||
"""Create an instance of Fp7LegalBasis from a dict"""
|
||||
if obj is None:
|
||||
return None
|
||||
|
||||
if not isinstance(obj, dict):
|
||||
return cls.model_validate(obj)
|
||||
|
||||
_obj = cls.model_validate({
|
||||
"id": obj.get("id"),
|
||||
"legalBasis": obj.get("legalBasis"),
|
||||
"projectID": obj.get("projectID"),
|
||||
"title": obj.get("title"),
|
||||
"uniqueProgrammePart": obj.get("uniqueProgrammePart")
|
||||
})
|
||||
return _obj
|
||||
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
CORDIS FP7 Multi-Index API
|
||||
|
||||
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by OpenAPI Generator (https://openapi-generator.tech)
|
||||
|
||||
Do not edit the class manually.
|
||||
""" # noqa: E501
|
||||
|
||||
|
||||
from __future__ import annotations
|
||||
import pprint
|
||||
import re # noqa: F401
|
||||
import json
|
||||
|
||||
from datetime import datetime
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt, StrictStr
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
|
||||
class Fp7Organization(BaseModel):
|
||||
"""
|
||||
Fp7Organization
|
||||
""" # noqa: E501
|
||||
sme: Optional[StrictBool] = Field(default=None, alias="SME")
|
||||
active: Optional[StrictBool] = None
|
||||
activity_type: Optional[StrictStr] = Field(default=None, alias="activityType")
|
||||
city: Optional[StrictStr] = None
|
||||
contact_form: Optional[StrictStr] = Field(default=None, alias="contactForm")
|
||||
content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate")
|
||||
country: Optional[StrictStr] = None
|
||||
ec_contribution: Optional[StrictFloat] = Field(default=None, alias="ecContribution")
|
||||
end_of_participation: Optional[StrictBool] = Field(default=None, alias="endOfParticipation")
|
||||
geolocation: Optional[StrictStr] = None
|
||||
id: Optional[StrictStr] = None
|
||||
name: Optional[StrictStr] = None
|
||||
net_ec_contribution: Optional[StrictFloat] = Field(default=None, alias="netEcContribution")
|
||||
nuts_code: Optional[StrictStr] = Field(default=None, alias="nutsCode")
|
||||
order: Optional[StrictInt] = None
|
||||
organisation_id: Optional[StrictStr] = Field(default=None, alias="organisationID")
|
||||
organization_url: Optional[StrictStr] = Field(default=None, alias="organizationURL")
|
||||
post_code: Optional[StrictStr] = Field(default=None, alias="postCode")
|
||||
project_acronym: Optional[StrictStr] = Field(default=None, alias="projectAcronym")
|
||||
project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
|
||||
rcn: Optional[StrictStr] = None
|
||||
role: Optional[StrictStr] = None
|
||||
short_name: Optional[StrictStr] = Field(default=None, alias="shortName")
|
||||
street: Optional[StrictStr] = None
|
||||
total_cost: Optional[StrictFloat] = Field(default=None, alias="totalCost")
|
||||
vat_number: Optional[StrictStr] = Field(default=None, alias="vatNumber")
|
||||
__properties: ClassVar[List[str]] = ["SME", "active", "activityType", "city", "contactForm", "contentUpdateDate", "country", "ecContribution", "endOfParticipation", "geolocation", "id", "name", "netEcContribution", "nutsCode", "order", "organisationID", "organizationURL", "postCode", "projectAcronym", "projectID", "rcn", "role", "shortName", "street", "totalCost", "vatNumber"]
|
||||
|
||||
model_config = ConfigDict(
|
||||
validate_by_name=True,
|
||||
validate_by_alias=True,
|
||||
validate_assignment=True,
|
||||
protected_namespaces=(),
|
||||
)
|
||||
|
||||
|
||||
def to_str(self) -> str:
|
||||
"""Returns the string representation of the model using alias"""
|
||||
return pprint.pformat(self.model_dump(by_alias=True))
|
||||
|
||||
def to_json(self) -> str:
|
||||
"""Returns the JSON representation of the model using alias"""
|
||||
return json.dumps(to_jsonable_python(self.to_dict()))
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, json_str: str) -> Optional[Self]:
|
||||
"""Create an instance of Fp7Organization from a JSON string"""
|
||||
return cls.from_dict(json.loads(json_str))
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Return the dictionary representation of the model using alias.
|
||||
|
||||
This has the following differences from calling pydantic's
|
||||
`self.model_dump(by_alias=True)`:
|
||||
|
||||
* `None` is only added to the output dict for nullable fields that
|
||||
were set at model initialization. Other fields with value `None`
|
||||
are ignored.
|
||||
"""
|
||||
excluded_fields: Set[str] = set([
|
||||
])
|
||||
|
||||
_dict = self.model_dump(
|
||||
by_alias=True,
|
||||
exclude=excluded_fields,
|
||||
exclude_none=True,
|
||||
)
|
||||
return _dict
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
|
||||
"""Create an instance of Fp7Organization from a dict"""
|
||||
if obj is None:
|
||||
return None
|
||||
|
||||
if not isinstance(obj, dict):
|
||||
return cls.model_validate(obj)
|
||||
|
||||
_obj = cls.model_validate({
|
||||
"SME": obj.get("SME"),
|
||||
"active": obj.get("active"),
|
||||
"activityType": obj.get("activityType"),
|
||||
"city": obj.get("city"),
|
||||
"contactForm": obj.get("contactForm"),
|
||||
"contentUpdateDate": obj.get("contentUpdateDate"),
|
||||
"country": obj.get("country"),
|
||||
"ecContribution": obj.get("ecContribution"),
|
||||
"endOfParticipation": obj.get("endOfParticipation"),
|
||||
"geolocation": obj.get("geolocation"),
|
||||
"id": obj.get("id"),
|
||||
"name": obj.get("name"),
|
||||
"netEcContribution": obj.get("netEcContribution"),
|
||||
"nutsCode": obj.get("nutsCode"),
|
||||
"order": obj.get("order"),
|
||||
"organisationID": obj.get("organisationID"),
|
||||
"organizationURL": obj.get("organizationURL"),
|
||||
"postCode": obj.get("postCode"),
|
||||
"projectAcronym": obj.get("projectAcronym"),
|
||||
"projectID": obj.get("projectID"),
|
||||
"rcn": obj.get("rcn"),
|
||||
"role": obj.get("role"),
|
||||
"shortName": obj.get("shortName"),
|
||||
"street": obj.get("street"),
|
||||
"totalCost": obj.get("totalCost"),
|
||||
"vatNumber": obj.get("vatNumber")
|
||||
})
|
||||
return _obj
|
||||
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
CORDIS FP7 Multi-Index API
|
||||
|
||||
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by OpenAPI Generator (https://openapi-generator.tech)
|
||||
|
||||
Do not edit the class manually.
|
||||
""" # noqa: E501
|
||||
|
||||
|
||||
from __future__ import annotations
|
||||
import pprint
|
||||
import re # noqa: F401
|
||||
import json
|
||||
|
||||
from datetime import date, datetime
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt, StrictStr
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
|
||||
class Fp7Project(BaseModel):
|
||||
"""
|
||||
Fp7Project
|
||||
""" # noqa: E501
|
||||
acronym: Optional[StrictStr] = None
|
||||
content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate")
|
||||
ec_max_contribution: Optional[StrictFloat] = Field(default=None, alias="ecMaxContribution")
|
||||
ec_signature_date: Optional[date] = Field(default=None, alias="ecSignatureDate")
|
||||
end_date: Optional[date] = Field(default=None, alias="endDate")
|
||||
framework_programme: Optional[StrictStr] = Field(default=None, alias="frameworkProgramme")
|
||||
funding_scheme: Optional[StrictStr] = Field(default=None, alias="fundingScheme")
|
||||
grant_doi: Optional[StrictStr] = Field(default=None, alias="grantDoi")
|
||||
human_validated: Optional[StrictBool] = Field(default=None, alias="humanValidated")
|
||||
id: Optional[StrictStr] = None
|
||||
keywords: Optional[StrictStr] = None
|
||||
legal_basis: Optional[StrictStr] = Field(default=None, alias="legalBasis")
|
||||
master_call: Optional[StrictStr] = Field(default=None, alias="masterCall")
|
||||
nature: Optional[StrictStr] = None
|
||||
objective: Optional[StrictStr] = None
|
||||
rcn: Optional[StrictStr] = None
|
||||
start_date: Optional[date] = Field(default=None, alias="startDate")
|
||||
status: Optional[StrictStr] = None
|
||||
sub_call: Optional[StrictStr] = Field(default=None, alias="subCall")
|
||||
title: Optional[StrictStr] = None
|
||||
topics: Optional[StrictStr] = None
|
||||
total_cost: Optional[StrictFloat] = Field(default=None, alias="totalCost")
|
||||
__properties: ClassVar[List[str]] = ["acronym", "contentUpdateDate", "ecMaxContribution", "ecSignatureDate", "endDate", "frameworkProgramme", "fundingScheme", "grantDoi", "humanValidated", "id", "keywords", "legalBasis", "masterCall", "nature", "objective", "rcn", "startDate", "status", "subCall", "title", "topics", "totalCost"]
|
||||
|
||||
model_config = ConfigDict(
|
||||
validate_by_name=True,
|
||||
validate_by_alias=True,
|
||||
validate_assignment=True,
|
||||
protected_namespaces=(),
|
||||
)
|
||||
|
||||
|
||||
def to_str(self) -> str:
|
||||
"""Returns the string representation of the model using alias"""
|
||||
return pprint.pformat(self.model_dump(by_alias=True))
|
||||
|
||||
def to_json(self) -> str:
|
||||
"""Returns the JSON representation of the model using alias"""
|
||||
return json.dumps(to_jsonable_python(self.to_dict()))
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, json_str: str) -> Optional[Self]:
|
||||
"""Create an instance of Fp7Project from a JSON string"""
|
||||
return cls.from_dict(json.loads(json_str))
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Return the dictionary representation of the model using alias.
|
||||
|
||||
This has the following differences from calling pydantic's
|
||||
`self.model_dump(by_alias=True)`:
|
||||
|
||||
* `None` is only added to the output dict for nullable fields that
|
||||
were set at model initialization. Other fields with value `None`
|
||||
are ignored.
|
||||
"""
|
||||
excluded_fields: Set[str] = set([
|
||||
])
|
||||
|
||||
_dict = self.model_dump(
|
||||
by_alias=True,
|
||||
exclude=excluded_fields,
|
||||
exclude_none=True,
|
||||
)
|
||||
return _dict
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
|
||||
"""Create an instance of Fp7Project from a dict"""
|
||||
if obj is None:
|
||||
return None
|
||||
|
||||
if not isinstance(obj, dict):
|
||||
return cls.model_validate(obj)
|
||||
|
||||
_obj = cls.model_validate({
|
||||
"acronym": obj.get("acronym"),
|
||||
"contentUpdateDate": obj.get("contentUpdateDate"),
|
||||
"ecMaxContribution": obj.get("ecMaxContribution"),
|
||||
"ecSignatureDate": obj.get("ecSignatureDate"),
|
||||
"endDate": obj.get("endDate"),
|
||||
"frameworkProgramme": obj.get("frameworkProgramme"),
|
||||
"fundingScheme": obj.get("fundingScheme"),
|
||||
"grantDoi": obj.get("grantDoi"),
|
||||
"humanValidated": obj.get("humanValidated"),
|
||||
"id": obj.get("id"),
|
||||
"keywords": obj.get("keywords"),
|
||||
"legalBasis": obj.get("legalBasis"),
|
||||
"masterCall": obj.get("masterCall"),
|
||||
"nature": obj.get("nature"),
|
||||
"objective": obj.get("objective"),
|
||||
"rcn": obj.get("rcn"),
|
||||
"startDate": obj.get("startDate"),
|
||||
"status": obj.get("status"),
|
||||
"subCall": obj.get("subCall"),
|
||||
"title": obj.get("title"),
|
||||
"topics": obj.get("topics"),
|
||||
"totalCost": obj.get("totalCost")
|
||||
})
|
||||
return _obj
|
||||
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
CORDIS FP7 Multi-Index API - Extended Models
|
||||
""" # noqa: E501
|
||||
|
||||
from __future__ import annotations
|
||||
import pprint
|
||||
import re # noqa: F401
|
||||
import json
|
||||
from datetime import date, datetime
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt, StrictStr
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
|
||||
# Import all the base models
|
||||
from inse.models.projects_eu_cordis.fp7.fp7_project import Fp7Project
|
||||
from inse.models.projects_eu_cordis.fp7.fp7_organization import Fp7Organization
|
||||
from inse.models.projects_eu_cordis.fp7.fp7_publication import Fp7Publication
|
||||
from inse.models.projects_eu_cordis.fp7.fp7_project_ipr import Fp7ProjectIPR
|
||||
from inse.models.projects_eu_cordis.fp7.fp7_report_summary import Fp7ReportSummary
|
||||
from inse.models.projects_eu_cordis.fp7.fp7_topic import Fp7Topic
|
||||
from inse.models.projects_eu_cordis.fp7.fp7_web_link import Fp7WebLink
|
||||
from inse.models.projects_eu_cordis.fp7.fp7_eurosci_voc import Fp7EurosciVoc
|
||||
from inse.models.projects_eu_cordis.fp7.fp7_legal_basis import Fp7LegalBasis
|
||||
|
||||
|
||||
class Fp7ProjectDetails(BaseModel):
|
||||
"""
|
||||
Comprehensive FP7 Project model combining all related entities.
|
||||
This model extends the base Fp7Project with all associated data.
|
||||
"""
|
||||
# Project core information (flattened from Fp7Project)
|
||||
acronym: Optional[StrictStr] = None
|
||||
content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate")
|
||||
ec_max_contribution: Optional[StrictFloat] = Field(default=None, alias="ecMaxContribution")
|
||||
ec_signature_date: Optional[date] = Field(default=None, alias="ecSignatureDate")
|
||||
end_date: Optional[date] = Field(default=None, alias="endDate")
|
||||
framework_programme: Optional[StrictStr] = Field(default=None, alias="frameworkProgramme")
|
||||
funding_scheme: Optional[StrictStr] = Field(default=None, alias="fundingScheme")
|
||||
grant_doi: Optional[StrictStr] = Field(default=None, alias="grantDoi")
|
||||
human_validated: Optional[StrictBool] = Field(default=None, alias="humanValidated")
|
||||
id: Optional[StrictStr] = None
|
||||
keywords: Optional[StrictStr] = None
|
||||
legal_basis: Optional[StrictStr] = Field(default=None, alias="legalBasis")
|
||||
master_call: Optional[StrictStr] = Field(default=None, alias="masterCall")
|
||||
nature: Optional[StrictStr] = None
|
||||
objective: Optional[StrictStr] = None
|
||||
rcn: Optional[StrictStr] = None
|
||||
start_date: Optional[date] = Field(default=None, alias="startDate")
|
||||
status: Optional[StrictStr] = None
|
||||
sub_call: Optional[StrictStr] = Field(default=None, alias="subCall")
|
||||
title: Optional[StrictStr] = None
|
||||
topics: Optional[StrictStr] = None
|
||||
total_cost: Optional[StrictFloat] = Field(default=None, alias="totalCost")
|
||||
|
||||
# Related entities (collections)
|
||||
organizations: Optional[List[Fp7Organization]] = Field(default=None, description="Organizations participating in the project")
|
||||
publications: Optional[List[Fp7Publication]] = Field(default=None, description="Publications related to the project")
|
||||
iprs: Optional[List[Fp7ProjectIPR]] = Field(default=None, description="Intellectual Property Rights related to the project")
|
||||
report_summaries: Optional[List[Fp7ReportSummary]] = Field(default=None, description="Report summaries for the project")
|
||||
topics_list: Optional[List[Fp7Topic]] = Field(default=None, alias="topicsList", description="Topics associated with the project")
|
||||
web_links: Optional[List[Fp7WebLink]] = Field(default=None, description="Web links related to the project")
|
||||
eurosci_voc: Optional[List[Fp7EurosciVoc]] = Field(default=None, alias="eurosciVoc", description="EuroSciVoc classifications")
|
||||
legal_basis_list: Optional[List[Fp7LegalBasis]] = Field(default=None, alias="legalBasisList", description="Legal basis information")
|
||||
|
||||
# Project statistics (aggregated)
|
||||
organization_count: Optional[int] = Field(default=None, alias="organizationCount")
|
||||
publication_count: Optional[int] = Field(default=None, alias="publicationCount")
|
||||
ipr_count: Optional[int] = Field(default=None, alias="iprCount")
|
||||
|
||||
__properties: ClassVar[List[str]] = [
|
||||
"acronym", "contentUpdateDate", "ecMaxContribution", "ecSignatureDate",
|
||||
"endDate", "frameworkProgramme", "fundingScheme", "grantDoi",
|
||||
"humanValidated", "id", "keywords", "legalBasis", "masterCall",
|
||||
"nature", "objective", "rcn", "startDate", "status", "subCall",
|
||||
"title", "topics", "totalCost",
|
||||
"organizations", "publications", "iprs", "reportSummaries",
|
||||
"topicsList", "webLinks", "eurosciVoc", "legalBasisList",
|
||||
"organizationCount", "publicationCount", "iprCount"
|
||||
]
|
||||
|
||||
model_config = ConfigDict(
|
||||
validate_by_name=True,
|
||||
validate_by_alias=True,
|
||||
validate_assignment=True,
|
||||
protected_namespaces=(),
|
||||
populate_by_name=True,
|
||||
)
|
||||
|
||||
def to_str(self) -> str:
|
||||
"""Returns the string representation of the model using alias"""
|
||||
return pprint.pformat(self.model_dump(by_alias=True))
|
||||
|
||||
def to_json(self) -> str:
|
||||
"""Returns the JSON representation of the model using alias"""
|
||||
return json.dumps(to_jsonable_python(self.to_dict()))
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, json_str: str) -> Optional[Self]:
|
||||
"""Create an instance of Fp7ProjectDetailed from a JSON string"""
|
||||
return cls.from_dict(json.loads(json_str))
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Return the dictionary representation of the model using alias."""
|
||||
excluded_fields: Set[str] = set([
|
||||
])
|
||||
|
||||
_dict = self.model_dump(
|
||||
by_alias=True,
|
||||
exclude=excluded_fields,
|
||||
exclude_none=True,
|
||||
)
|
||||
return _dict
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
|
||||
"""Create an instance of Fp7ProjectDetailed from a dict"""
|
||||
if obj is None:
|
||||
return None
|
||||
|
||||
if not isinstance(obj, dict):
|
||||
return cls.model_validate(obj)
|
||||
|
||||
_obj = cls.model_validate({
|
||||
# Project core fields
|
||||
"acronym": obj.get("acronym"),
|
||||
"contentUpdateDate": obj.get("contentUpdateDate"),
|
||||
"ecMaxContribution": obj.get("ecMaxContribution"),
|
||||
"ecSignatureDate": obj.get("ecSignatureDate"),
|
||||
"endDate": obj.get("endDate"),
|
||||
"frameworkProgramme": obj.get("frameworkProgramme"),
|
||||
"fundingScheme": obj.get("fundingScheme"),
|
||||
"grantDoi": obj.get("grantDoi"),
|
||||
"humanValidated": obj.get("humanValidated"),
|
||||
"id": obj.get("id"),
|
||||
"keywords": obj.get("keywords"),
|
||||
"legalBasis": obj.get("legalBasis"),
|
||||
"masterCall": obj.get("masterCall"),
|
||||
"nature": obj.get("nature"),
|
||||
"objective": obj.get("objective"),
|
||||
"rcn": obj.get("rcn"),
|
||||
"startDate": obj.get("startDate"),
|
||||
"status": obj.get("status"),
|
||||
"subCall": obj.get("subCall"),
|
||||
"title": obj.get("title"),
|
||||
"topics": obj.get("topics"),
|
||||
"totalCost": obj.get("totalCost"),
|
||||
|
||||
# Related entities
|
||||
"organizations": [Fp7Organization.from_dict(org) for org in obj.get("organizations", [])] if obj.get("organizations") else None,
|
||||
"publications": [Fp7Publication.from_dict(pub) for pub in obj.get("publications", [])] if obj.get("publications") else None,
|
||||
"iprs": [Fp7ProjectIPR.from_dict(ipr) for ipr in obj.get("iprs", [])] if obj.get("iprs") else None,
|
||||
"reportSummaries": [Fp7ReportSummary.from_dict(report) for report in obj.get("reportSummaries", [])] if obj.get("reportSummaries") else None,
|
||||
"topicsList": [Fp7Topic.from_dict(topic) for topic in obj.get("topicsList", [])] if obj.get("topicsList") else None,
|
||||
"webLinks": [Fp7WebLink.from_dict(link) for link in obj.get("webLinks", [])] if obj.get("webLinks") else None,
|
||||
"eurosciVoc": [Fp7EurosciVoc.from_dict(voc) for voc in obj.get("eurosciVoc", [])] if obj.get("eurosciVoc") else None,
|
||||
"legalBasisList": [Fp7LegalBasis.from_dict(lb) for lb in obj.get("legalBasisList", [])] if obj.get("legalBasisList") else None,
|
||||
|
||||
# Statistics
|
||||
"organizationCount": len(obj.get("organizations", [])) if obj.get("organizations") else 0,
|
||||
"publicationCount": len(obj.get("publications", [])) if obj.get("publications") else 0,
|
||||
"iprCount": len(obj.get("iprs", [])) if obj.get("iprs") else 0,
|
||||
})
|
||||
return _obj
|
||||
|
||||
@classmethod
|
||||
def from_project_with_relations(
|
||||
cls,
|
||||
project: Fp7Project,
|
||||
organizations: Optional[List[Fp7Organization]] = None,
|
||||
publications: Optional[List[Fp7Publication]] = None,
|
||||
iprs: Optional[List[Fp7ProjectIPR]] = None,
|
||||
report_summaries: Optional[List[Fp7ReportSummary]] = None,
|
||||
topics_list: Optional[List[Fp7Topic]] = None,
|
||||
web_links: Optional[List[Fp7WebLink]] = None,
|
||||
eurosci_voc: Optional[List[Fp7EurosciVoc]] = None,
|
||||
legal_basis_list: Optional[List[Fp7LegalBasis]] = None,
|
||||
) -> Self:
|
||||
"""
|
||||
Factory method to create a detailed project from a base project and its relations.
|
||||
|
||||
Args:
|
||||
project: The base Fp7Project object
|
||||
organizations: List of organizations participating in the project
|
||||
publications: List of publications related to the project
|
||||
iprs: List of IPRs related to the project
|
||||
report_summaries: List of report summaries
|
||||
topics_list: List of topics associated with the project
|
||||
web_links: List of web links
|
||||
eurosci_voc: List of EuroSciVoc classifications
|
||||
legal_basis_list: List of legal basis information
|
||||
|
||||
Returns:
|
||||
Fp7ProjectDetailed instance
|
||||
"""
|
||||
project_dict = project.to_dict() if project else {}
|
||||
|
||||
return cls(
|
||||
**project_dict,
|
||||
organizations=organizations or [],
|
||||
publications=publications or [],
|
||||
iprs=iprs or [],
|
||||
reportSummaries=report_summaries or [],
|
||||
topicsList=topics_list or [],
|
||||
webLinks=web_links or [],
|
||||
eurosciVoc=eurosci_voc or [],
|
||||
legalBasisList=legal_basis_list or [],
|
||||
organizationCount=len(organizations) if organizations else 0,
|
||||
publicationCount=len(publications) if publications else 0,
|
||||
iprCount=len(iprs) if iprs else 0,
|
||||
)
|
||||
@@ -0,0 +1,125 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
CORDIS FP7 Multi-Index API
|
||||
|
||||
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by OpenAPI Generator (https://openapi-generator.tech)
|
||||
|
||||
Do not edit the class manually.
|
||||
""" # noqa: E501
|
||||
|
||||
|
||||
from __future__ import annotations
|
||||
import pprint
|
||||
import re # noqa: F401
|
||||
import json
|
||||
|
||||
from datetime import date
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictStr
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
|
||||
class Fp7ProjectIPR(BaseModel):
|
||||
"""
|
||||
Fp7ProjectIPR
|
||||
""" # noqa: E501
|
||||
applicant_name: Optional[StrictStr] = Field(default=None, alias="applicantName")
|
||||
application_date: Optional[date] = Field(default=None, alias="applicationDate")
|
||||
application_identifier: Optional[StrictStr] = Field(default=None, alias="applicationIdentifier")
|
||||
application_kind: Optional[StrictStr] = Field(default=None, alias="applicationKind")
|
||||
application_prefix: Optional[StrictStr] = Field(default=None, alias="applicationPrefix")
|
||||
award_date: Optional[date] = Field(default=None, alias="awardDate")
|
||||
award_identifier: Optional[StrictStr] = Field(default=None, alias="awardIdentifier")
|
||||
award_kind: Optional[StrictStr] = Field(default=None, alias="awardKind")
|
||||
award_prefix: Optional[StrictStr] = Field(default=None, alias="awardPrefix")
|
||||
epo_app_url: Optional[StrictStr] = Field(default=None, alias="epoAppUrl")
|
||||
epo_pub_url: Optional[StrictStr] = Field(default=None, alias="epoPubUrl")
|
||||
id: Optional[StrictStr] = None
|
||||
organisation_id: Optional[StrictStr] = Field(default=None, alias="organisationID")
|
||||
patent_family_identifier: Optional[StrictStr] = Field(default=None, alias="patentFamilyIdentifier")
|
||||
patent_type: Optional[StrictStr] = Field(default=None, alias="patentType")
|
||||
priority_date: Optional[date] = Field(default=None, alias="priorityDate")
|
||||
project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
|
||||
title: Optional[StrictStr] = None
|
||||
type: Optional[StrictStr] = None
|
||||
__properties: ClassVar[List[str]] = ["applicantName", "applicationDate", "applicationIdentifier", "applicationKind", "applicationPrefix", "awardDate", "awardIdentifier", "awardKind", "awardPrefix", "epoAppUrl", "epoPubUrl", "id", "organisationID", "patentFamilyIdentifier", "patentType", "priorityDate", "projectID", "title", "type"]
|
||||
|
||||
model_config = ConfigDict(
|
||||
validate_by_name=True,
|
||||
validate_by_alias=True,
|
||||
validate_assignment=True,
|
||||
protected_namespaces=(),
|
||||
)
|
||||
|
||||
|
||||
def to_str(self) -> str:
|
||||
"""Returns the string representation of the model using alias"""
|
||||
return pprint.pformat(self.model_dump(by_alias=True))
|
||||
|
||||
def to_json(self) -> str:
|
||||
"""Returns the JSON representation of the model using alias"""
|
||||
return json.dumps(to_jsonable_python(self.to_dict()))
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, json_str: str) -> Optional[Self]:
|
||||
"""Create an instance of Fp7ProjectIPR from a JSON string"""
|
||||
return cls.from_dict(json.loads(json_str))
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Return the dictionary representation of the model using alias.
|
||||
|
||||
This has the following differences from calling pydantic's
|
||||
`self.model_dump(by_alias=True)`:
|
||||
|
||||
* `None` is only added to the output dict for nullable fields that
|
||||
were set at model initialization. Other fields with value `None`
|
||||
are ignored.
|
||||
"""
|
||||
excluded_fields: Set[str] = set([
|
||||
])
|
||||
|
||||
_dict = self.model_dump(
|
||||
by_alias=True,
|
||||
exclude=excluded_fields,
|
||||
exclude_none=True,
|
||||
)
|
||||
return _dict
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
|
||||
"""Create an instance of Fp7ProjectIPR from a dict"""
|
||||
if obj is None:
|
||||
return None
|
||||
|
||||
if not isinstance(obj, dict):
|
||||
return cls.model_validate(obj)
|
||||
|
||||
_obj = cls.model_validate({
|
||||
"applicantName": obj.get("applicantName"),
|
||||
"applicationDate": obj.get("applicationDate"),
|
||||
"applicationIdentifier": obj.get("applicationIdentifier"),
|
||||
"applicationKind": obj.get("applicationKind"),
|
||||
"applicationPrefix": obj.get("applicationPrefix"),
|
||||
"awardDate": obj.get("awardDate"),
|
||||
"awardIdentifier": obj.get("awardIdentifier"),
|
||||
"awardKind": obj.get("awardKind"),
|
||||
"awardPrefix": obj.get("awardPrefix"),
|
||||
"epoAppUrl": obj.get("epoAppUrl"),
|
||||
"epoPubUrl": obj.get("epoPubUrl"),
|
||||
"id": obj.get("id"),
|
||||
"organisationID": obj.get("organisationID"),
|
||||
"patentFamilyIdentifier": obj.get("patentFamilyIdentifier"),
|
||||
"patentType": obj.get("patentType"),
|
||||
"priorityDate": obj.get("priorityDate"),
|
||||
"projectID": obj.get("projectID"),
|
||||
"title": obj.get("title"),
|
||||
"type": obj.get("type")
|
||||
})
|
||||
return _obj
|
||||
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
CORDIS FP7 Multi-Index API
|
||||
|
||||
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by OpenAPI Generator (https://openapi-generator.tech)
|
||||
|
||||
Do not edit the class manually.
|
||||
""" # noqa: E501
|
||||
|
||||
|
||||
from __future__ import annotations
|
||||
import pprint
|
||||
import re # noqa: F401
|
||||
import json
|
||||
|
||||
from datetime import datetime
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
|
||||
class Fp7Publication(BaseModel):
|
||||
"""
|
||||
Fp7Publication
|
||||
""" # noqa: E501
|
||||
authors: Optional[StrictStr] = None
|
||||
collection: Optional[StrictStr] = None
|
||||
content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate")
|
||||
doi: Optional[StrictStr] = None
|
||||
id: Optional[StrictStr] = None
|
||||
is_published_as: Optional[StrictStr] = Field(default=None, alias="isPublishedAs")
|
||||
journal_number: Optional[StrictStr] = Field(default=None, alias="journalNumber")
|
||||
journal_title: Optional[StrictStr] = Field(default=None, alias="journalTitle")
|
||||
project_acronym: Optional[StrictStr] = Field(default=None, alias="projectAcronym")
|
||||
project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
|
||||
published_pages: Optional[StrictStr] = Field(default=None, alias="publishedPages")
|
||||
published_year: Optional[StrictInt] = Field(default=None, alias="publishedYear")
|
||||
publisher: Optional[StrictStr] = None
|
||||
qa_processed_doi: Optional[StrictStr] = Field(default=None, alias="qaProcessedDoi")
|
||||
rcn: Optional[StrictStr] = None
|
||||
repository_url: Optional[StrictStr] = Field(default=None, alias="repositoryUrl")
|
||||
title: Optional[StrictStr] = None
|
||||
volume: Optional[StrictStr] = None
|
||||
__properties: ClassVar[List[str]] = ["authors", "collection", "contentUpdateDate", "doi", "id", "isPublishedAs", "journalNumber", "journalTitle", "projectAcronym", "projectID", "publishedPages", "publishedYear", "publisher", "qaProcessedDoi", "rcn", "repositoryUrl", "title", "volume"]
|
||||
|
||||
model_config = ConfigDict(
|
||||
validate_by_name=True,
|
||||
validate_by_alias=True,
|
||||
validate_assignment=True,
|
||||
protected_namespaces=(),
|
||||
)
|
||||
|
||||
|
||||
def to_str(self) -> str:
|
||||
"""Returns the string representation of the model using alias"""
|
||||
return pprint.pformat(self.model_dump(by_alias=True))
|
||||
|
||||
def to_json(self) -> str:
|
||||
"""Returns the JSON representation of the model using alias"""
|
||||
return json.dumps(to_jsonable_python(self.to_dict()))
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, json_str: str) -> Optional[Self]:
|
||||
"""Create an instance of Fp7Publication from a JSON string"""
|
||||
return cls.from_dict(json.loads(json_str))
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Return the dictionary representation of the model using alias.
|
||||
|
||||
This has the following differences from calling pydantic's
|
||||
`self.model_dump(by_alias=True)`:
|
||||
|
||||
* `None` is only added to the output dict for nullable fields that
|
||||
were set at model initialization. Other fields with value `None`
|
||||
are ignored.
|
||||
"""
|
||||
excluded_fields: Set[str] = set([
|
||||
])
|
||||
|
||||
_dict = self.model_dump(
|
||||
by_alias=True,
|
||||
exclude=excluded_fields,
|
||||
exclude_none=True,
|
||||
)
|
||||
return _dict
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
|
||||
"""Create an instance of Fp7Publication from a dict"""
|
||||
if obj is None:
|
||||
return None
|
||||
|
||||
if not isinstance(obj, dict):
|
||||
return cls.model_validate(obj)
|
||||
|
||||
_obj = cls.model_validate({
|
||||
"authors": obj.get("authors"),
|
||||
"collection": obj.get("collection"),
|
||||
"contentUpdateDate": obj.get("contentUpdateDate"),
|
||||
"doi": obj.get("doi"),
|
||||
"id": obj.get("id"),
|
||||
"isPublishedAs": obj.get("isPublishedAs"),
|
||||
"journalNumber": obj.get("journalNumber"),
|
||||
"journalTitle": obj.get("journalTitle"),
|
||||
"projectAcronym": obj.get("projectAcronym"),
|
||||
"projectID": obj.get("projectID"),
|
||||
"publishedPages": obj.get("publishedPages"),
|
||||
"publishedYear": obj.get("publishedYear"),
|
||||
"publisher": obj.get("publisher"),
|
||||
"qaProcessedDoi": obj.get("qaProcessedDoi"),
|
||||
"rcn": obj.get("rcn"),
|
||||
"repositoryUrl": obj.get("repositoryUrl"),
|
||||
"title": obj.get("title"),
|
||||
"volume": obj.get("volume")
|
||||
})
|
||||
return _obj
|
||||
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
CORDIS FP7 Multi-Index API
|
||||
|
||||
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by OpenAPI Generator (https://openapi-generator.tech)
|
||||
|
||||
Do not edit the class manually.
|
||||
""" # noqa: E501
|
||||
|
||||
|
||||
from __future__ import annotations
|
||||
import pprint
|
||||
import re # noqa: F401
|
||||
import json
|
||||
|
||||
from datetime import datetime
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictStr
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
|
||||
class Fp7ReportSummary(BaseModel):
|
||||
"""
|
||||
Fp7ReportSummary
|
||||
""" # noqa: E501
|
||||
attachments: Optional[StrictStr] = None
|
||||
content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate")
|
||||
id: Optional[StrictStr] = None
|
||||
project_acronym: Optional[StrictStr] = Field(default=None, alias="projectAcronym")
|
||||
project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
|
||||
rcn: Optional[StrictStr] = None
|
||||
title: Optional[StrictStr] = None
|
||||
__properties: ClassVar[List[str]] = ["attachments", "contentUpdateDate", "id", "projectAcronym", "projectID", "rcn", "title"]
|
||||
|
||||
model_config = ConfigDict(
|
||||
validate_by_name=True,
|
||||
validate_by_alias=True,
|
||||
validate_assignment=True,
|
||||
protected_namespaces=(),
|
||||
)
|
||||
|
||||
|
||||
def to_str(self) -> str:
|
||||
"""Returns the string representation of the model using alias"""
|
||||
return pprint.pformat(self.model_dump(by_alias=True))
|
||||
|
||||
def to_json(self) -> str:
|
||||
"""Returns the JSON representation of the model using alias"""
|
||||
return json.dumps(to_jsonable_python(self.to_dict()))
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, json_str: str) -> Optional[Self]:
|
||||
"""Create an instance of Fp7ReportSummary from a JSON string"""
|
||||
return cls.from_dict(json.loads(json_str))
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Return the dictionary representation of the model using alias.
|
||||
|
||||
This has the following differences from calling pydantic's
|
||||
`self.model_dump(by_alias=True)`:
|
||||
|
||||
* `None` is only added to the output dict for nullable fields that
|
||||
were set at model initialization. Other fields with value `None`
|
||||
are ignored.
|
||||
"""
|
||||
excluded_fields: Set[str] = set([
|
||||
])
|
||||
|
||||
_dict = self.model_dump(
|
||||
by_alias=True,
|
||||
exclude=excluded_fields,
|
||||
exclude_none=True,
|
||||
)
|
||||
return _dict
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
|
||||
"""Create an instance of Fp7ReportSummary from a dict"""
|
||||
if obj is None:
|
||||
return None
|
||||
|
||||
if not isinstance(obj, dict):
|
||||
return cls.model_validate(obj)
|
||||
|
||||
_obj = cls.model_validate({
|
||||
"attachments": obj.get("attachments"),
|
||||
"contentUpdateDate": obj.get("contentUpdateDate"),
|
||||
"id": obj.get("id"),
|
||||
"projectAcronym": obj.get("projectAcronym"),
|
||||
"projectID": obj.get("projectID"),
|
||||
"rcn": obj.get("rcn"),
|
||||
"title": obj.get("title")
|
||||
})
|
||||
return _obj
|
||||
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
CORDIS FP7 Multi-Index API
|
||||
|
||||
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by OpenAPI Generator (https://openapi-generator.tech)
|
||||
|
||||
Do not edit the class manually.
|
||||
""" # noqa: E501
|
||||
|
||||
|
||||
from __future__ import annotations
|
||||
import pprint
|
||||
import re # noqa: F401
|
||||
import json
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictStr
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
|
||||
class Fp7Topic(BaseModel):
|
||||
"""
|
||||
Fp7Topic
|
||||
""" # noqa: E501
|
||||
id: Optional[StrictStr] = None
|
||||
project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
|
||||
title: Optional[StrictStr] = None
|
||||
topic: Optional[StrictStr] = None
|
||||
__properties: ClassVar[List[str]] = ["id", "projectID", "title", "topic"]
|
||||
|
||||
model_config = ConfigDict(
|
||||
validate_by_name=True,
|
||||
validate_by_alias=True,
|
||||
validate_assignment=True,
|
||||
protected_namespaces=(),
|
||||
)
|
||||
|
||||
|
||||
def to_str(self) -> str:
|
||||
"""Returns the string representation of the model using alias"""
|
||||
return pprint.pformat(self.model_dump(by_alias=True))
|
||||
|
||||
def to_json(self) -> str:
|
||||
"""Returns the JSON representation of the model using alias"""
|
||||
return json.dumps(to_jsonable_python(self.to_dict()))
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, json_str: str) -> Optional[Self]:
|
||||
"""Create an instance of Fp7Topic from a JSON string"""
|
||||
return cls.from_dict(json.loads(json_str))
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Return the dictionary representation of the model using alias.
|
||||
|
||||
This has the following differences from calling pydantic's
|
||||
`self.model_dump(by_alias=True)`:
|
||||
|
||||
* `None` is only added to the output dict for nullable fields that
|
||||
were set at model initialization. Other fields with value `None`
|
||||
are ignored.
|
||||
"""
|
||||
excluded_fields: Set[str] = set([
|
||||
])
|
||||
|
||||
_dict = self.model_dump(
|
||||
by_alias=True,
|
||||
exclude=excluded_fields,
|
||||
exclude_none=True,
|
||||
)
|
||||
return _dict
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
|
||||
"""Create an instance of Fp7Topic from a dict"""
|
||||
if obj is None:
|
||||
return None
|
||||
|
||||
if not isinstance(obj, dict):
|
||||
return cls.model_validate(obj)
|
||||
|
||||
_obj = cls.model_validate({
|
||||
"id": obj.get("id"),
|
||||
"projectID": obj.get("projectID"),
|
||||
"title": obj.get("title"),
|
||||
"topic": obj.get("topic")
|
||||
})
|
||||
return _obj
|
||||
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
CORDIS FP7 Multi-Index API
|
||||
|
||||
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by OpenAPI Generator (https://openapi-generator.tech)
|
||||
|
||||
Do not edit the class manually.
|
||||
""" # noqa: E501
|
||||
|
||||
|
||||
from __future__ import annotations
|
||||
import pprint
|
||||
import re # noqa: F401
|
||||
import json
|
||||
|
||||
from datetime import datetime
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictStr
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
|
||||
class Fp7WebLink(BaseModel):
|
||||
"""
|
||||
Fp7WebLink
|
||||
""" # noqa: E501
|
||||
archived_date: Optional[datetime] = Field(default=None, alias="archivedDate")
|
||||
available_languages: Optional[StrictStr] = Field(default=None, alias="availableLanguages")
|
||||
id: Optional[StrictStr] = None
|
||||
link_id: Optional[StrictStr] = Field(default=None, alias="linkId")
|
||||
project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
|
||||
represents: Optional[StrictStr] = None
|
||||
source: Optional[StrictStr] = None
|
||||
status: Optional[StrictStr] = None
|
||||
type: Optional[StrictStr] = None
|
||||
url: Optional[StrictStr] = None
|
||||
__properties: ClassVar[List[str]] = ["archivedDate", "availableLanguages", "id", "linkId", "projectID", "represents", "source", "status", "type", "url"]
|
||||
|
||||
model_config = ConfigDict(
|
||||
validate_by_name=True,
|
||||
validate_by_alias=True,
|
||||
validate_assignment=True,
|
||||
protected_namespaces=(),
|
||||
)
|
||||
|
||||
|
||||
def to_str(self) -> str:
|
||||
"""Returns the string representation of the model using alias"""
|
||||
return pprint.pformat(self.model_dump(by_alias=True))
|
||||
|
||||
def to_json(self) -> str:
|
||||
"""Returns the JSON representation of the model using alias"""
|
||||
return json.dumps(to_jsonable_python(self.to_dict()))
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, json_str: str) -> Optional[Self]:
|
||||
"""Create an instance of Fp7WebLink from a JSON string"""
|
||||
return cls.from_dict(json.loads(json_str))
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Return the dictionary representation of the model using alias.
|
||||
|
||||
This has the following differences from calling pydantic's
|
||||
`self.model_dump(by_alias=True)`:
|
||||
|
||||
* `None` is only added to the output dict for nullable fields that
|
||||
were set at model initialization. Other fields with value `None`
|
||||
are ignored.
|
||||
"""
|
||||
excluded_fields: Set[str] = set([
|
||||
])
|
||||
|
||||
_dict = self.model_dump(
|
||||
by_alias=True,
|
||||
exclude=excluded_fields,
|
||||
exclude_none=True,
|
||||
)
|
||||
return _dict
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
|
||||
"""Create an instance of Fp7WebLink from a dict"""
|
||||
if obj is None:
|
||||
return None
|
||||
|
||||
if not isinstance(obj, dict):
|
||||
return cls.model_validate(obj)
|
||||
|
||||
_obj = cls.model_validate({
|
||||
"archivedDate": obj.get("archivedDate"),
|
||||
"availableLanguages": obj.get("availableLanguages"),
|
||||
"id": obj.get("id"),
|
||||
"linkId": obj.get("linkId"),
|
||||
"projectID": obj.get("projectID"),
|
||||
"represents": obj.get("represents"),
|
||||
"source": obj.get("source"),
|
||||
"status": obj.get("status"),
|
||||
"type": obj.get("type"),
|
||||
"url": obj.get("url")
|
||||
})
|
||||
return _obj
|
||||
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
CORDIS Horizon 2020 Multi-Index API
|
||||
|
||||
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by OpenAPI Generator (https://openapi-generator.tech)
|
||||
|
||||
Do not edit the class manually.
|
||||
""" # noqa: E501
|
||||
|
||||
|
||||
from __future__ import annotations
|
||||
import pprint
|
||||
import re # noqa: F401
|
||||
import json
|
||||
|
||||
from datetime import datetime
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictStr
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
|
||||
class H2020Deliverable(BaseModel):
|
||||
"""
|
||||
H2020Deliverable
|
||||
""" # noqa: E501
|
||||
collection: Optional[StrictStr] = None
|
||||
content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate")
|
||||
deliverable_type: Optional[StrictStr] = Field(default=None, alias="deliverableType")
|
||||
description: Optional[StrictStr] = None
|
||||
project_acronym: Optional[StrictStr] = Field(default=None, alias="projectAcronym")
|
||||
project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
|
||||
rcn: Optional[StrictStr] = None
|
||||
url: Optional[StrictStr] = None
|
||||
__properties: ClassVar[List[str]] = ["collection", "contentUpdateDate", "deliverableType", "description", "projectAcronym", "projectID", "rcn", "url"]
|
||||
|
||||
model_config = ConfigDict(
|
||||
validate_by_name=True,
|
||||
validate_by_alias=True,
|
||||
validate_assignment=True,
|
||||
protected_namespaces=(),
|
||||
)
|
||||
|
||||
|
||||
def to_str(self) -> str:
|
||||
"""Returns the string representation of the model using alias"""
|
||||
return pprint.pformat(self.model_dump(by_alias=True))
|
||||
|
||||
def to_json(self) -> str:
|
||||
"""Returns the JSON representation of the model using alias"""
|
||||
return json.dumps(to_jsonable_python(self.to_dict()))
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, json_str: str) -> Optional[Self]:
|
||||
"""Create an instance of H2020Deliverable from a JSON string"""
|
||||
return cls.from_dict(json.loads(json_str))
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Return the dictionary representation of the model using alias.
|
||||
|
||||
This has the following differences from calling pydantic's
|
||||
`self.model_dump(by_alias=True)`:
|
||||
|
||||
* `None` is only added to the output dict for nullable fields that
|
||||
were set at model initialization. Other fields with value `None`
|
||||
are ignored.
|
||||
"""
|
||||
excluded_fields: Set[str] = set([
|
||||
])
|
||||
|
||||
_dict = self.model_dump(
|
||||
by_alias=True,
|
||||
exclude=excluded_fields,
|
||||
exclude_none=True,
|
||||
)
|
||||
return _dict
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
|
||||
"""Create an instance of H2020Deliverable from a dict"""
|
||||
if obj is None:
|
||||
return None
|
||||
|
||||
if not isinstance(obj, dict):
|
||||
return cls.model_validate(obj)
|
||||
|
||||
_obj = cls.model_validate({
|
||||
"collection": obj.get("collection"),
|
||||
"contentUpdateDate": obj.get("contentUpdateDate"),
|
||||
"deliverableType": obj.get("deliverableType"),
|
||||
"description": obj.get("description"),
|
||||
"projectAcronym": obj.get("projectAcronym"),
|
||||
"projectID": obj.get("projectID"),
|
||||
"rcn": obj.get("rcn"),
|
||||
"url": obj.get("url")
|
||||
})
|
||||
return _obj
|
||||
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
CORDIS Horizon 2020 Multi-Index API
|
||||
|
||||
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by OpenAPI Generator (https://openapi-generator.tech)
|
||||
|
||||
Do not edit the class manually.
|
||||
""" # noqa: E501
|
||||
|
||||
|
||||
from __future__ import annotations
|
||||
import pprint
|
||||
import re # noqa: F401
|
||||
import json
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictStr
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
|
||||
class H2020ErcPI(BaseModel):
|
||||
"""
|
||||
H2020ErcPI
|
||||
""" # noqa: E501
|
||||
first_name: Optional[StrictStr] = Field(default=None, alias="firstName")
|
||||
funding_scheme: Optional[StrictStr] = Field(default=None, alias="fundingScheme")
|
||||
id: Optional[StrictStr] = None
|
||||
last_name: Optional[StrictStr] = Field(default=None, alias="lastName")
|
||||
organisation_id: Optional[StrictStr] = Field(default=None, alias="organisationID")
|
||||
project_acronym: Optional[StrictStr] = Field(default=None, alias="projectAcronym")
|
||||
project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
|
||||
title: Optional[StrictStr] = None
|
||||
__properties: ClassVar[List[str]] = ["firstName", "fundingScheme", "id", "lastName", "organisationID", "projectAcronym", "projectID", "title"]
|
||||
|
||||
model_config = ConfigDict(
|
||||
validate_by_name=True,
|
||||
validate_by_alias=True,
|
||||
validate_assignment=True,
|
||||
protected_namespaces=(),
|
||||
)
|
||||
|
||||
|
||||
def to_str(self) -> str:
|
||||
"""Returns the string representation of the model using alias"""
|
||||
return pprint.pformat(self.model_dump(by_alias=True))
|
||||
|
||||
def to_json(self) -> str:
|
||||
"""Returns the JSON representation of the model using alias"""
|
||||
return json.dumps(to_jsonable_python(self.to_dict()))
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, json_str: str) -> Optional[Self]:
|
||||
"""Create an instance of H2020ErcPI from a JSON string"""
|
||||
return cls.from_dict(json.loads(json_str))
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Return the dictionary representation of the model using alias.
|
||||
|
||||
This has the following differences from calling pydantic's
|
||||
`self.model_dump(by_alias=True)`:
|
||||
|
||||
* `None` is only added to the output dict for nullable fields that
|
||||
were set at model initialization. Other fields with value `None`
|
||||
are ignored.
|
||||
"""
|
||||
excluded_fields: Set[str] = set([
|
||||
])
|
||||
|
||||
_dict = self.model_dump(
|
||||
by_alias=True,
|
||||
exclude=excluded_fields,
|
||||
exclude_none=True,
|
||||
)
|
||||
return _dict
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
|
||||
"""Create an instance of H2020ErcPI from a dict"""
|
||||
if obj is None:
|
||||
return None
|
||||
|
||||
if not isinstance(obj, dict):
|
||||
return cls.model_validate(obj)
|
||||
|
||||
_obj = cls.model_validate({
|
||||
"firstName": obj.get("firstName"),
|
||||
"fundingScheme": obj.get("fundingScheme"),
|
||||
"id": obj.get("id"),
|
||||
"lastName": obj.get("lastName"),
|
||||
"organisationID": obj.get("organisationID"),
|
||||
"projectAcronym": obj.get("projectAcronym"),
|
||||
"projectID": obj.get("projectID"),
|
||||
"title": obj.get("title")
|
||||
})
|
||||
return _obj
|
||||
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
CORDIS Horizon 2020 Multi-Index API
|
||||
|
||||
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by OpenAPI Generator (https://openapi-generator.tech)
|
||||
|
||||
Do not edit the class manually.
|
||||
""" # noqa: E501
|
||||
|
||||
|
||||
from __future__ import annotations
|
||||
import pprint
|
||||
import re # noqa: F401
|
||||
import json
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictStr
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
|
||||
class H2020EurosciVoc(BaseModel):
|
||||
"""
|
||||
H2020EurosciVoc
|
||||
""" # noqa: E501
|
||||
code: Optional[StrictStr] = None
|
||||
description: Optional[StrictStr] = None
|
||||
id: Optional[StrictStr] = None
|
||||
path: Optional[StrictStr] = None
|
||||
project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
|
||||
title: Optional[StrictStr] = None
|
||||
__properties: ClassVar[List[str]] = ["code", "description", "id", "path", "projectID", "title"]
|
||||
|
||||
model_config = ConfigDict(
|
||||
validate_by_name=True,
|
||||
validate_by_alias=True,
|
||||
validate_assignment=True,
|
||||
protected_namespaces=(),
|
||||
)
|
||||
|
||||
|
||||
def to_str(self) -> str:
|
||||
"""Returns the string representation of the model using alias"""
|
||||
return pprint.pformat(self.model_dump(by_alias=True))
|
||||
|
||||
def to_json(self) -> str:
|
||||
"""Returns the JSON representation of the model using alias"""
|
||||
return json.dumps(to_jsonable_python(self.to_dict()))
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, json_str: str) -> Optional[Self]:
|
||||
"""Create an instance of H2020EurosciVoc from a JSON string"""
|
||||
return cls.from_dict(json.loads(json_str))
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Return the dictionary representation of the model using alias.
|
||||
|
||||
This has the following differences from calling pydantic's
|
||||
`self.model_dump(by_alias=True)`:
|
||||
|
||||
* `None` is only added to the output dict for nullable fields that
|
||||
were set at model initialization. Other fields with value `None`
|
||||
are ignored.
|
||||
"""
|
||||
excluded_fields: Set[str] = set([
|
||||
])
|
||||
|
||||
_dict = self.model_dump(
|
||||
by_alias=True,
|
||||
exclude=excluded_fields,
|
||||
exclude_none=True,
|
||||
)
|
||||
return _dict
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
|
||||
"""Create an instance of H2020EurosciVoc from a dict"""
|
||||
if obj is None:
|
||||
return None
|
||||
|
||||
if not isinstance(obj, dict):
|
||||
return cls.model_validate(obj)
|
||||
|
||||
_obj = cls.model_validate({
|
||||
"code": obj.get("code"),
|
||||
"description": obj.get("description"),
|
||||
"id": obj.get("id"),
|
||||
"path": obj.get("path"),
|
||||
"projectID": obj.get("projectID"),
|
||||
"title": obj.get("title")
|
||||
})
|
||||
return _obj
|
||||
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
CORDIS Horizon 2020 Multi-Index API
|
||||
|
||||
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by OpenAPI Generator (https://openapi-generator.tech)
|
||||
|
||||
Do not edit the class manually.
|
||||
""" # noqa: E501
|
||||
|
||||
|
||||
from __future__ import annotations
|
||||
import pprint
|
||||
import re # noqa: F401
|
||||
import json
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictStr
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
|
||||
class H2020LegalBasis(BaseModel):
|
||||
"""
|
||||
H2020LegalBasis
|
||||
""" # noqa: E501
|
||||
id: Optional[StrictStr] = None
|
||||
legal_basis: Optional[StrictStr] = Field(default=None, alias="legalBasis")
|
||||
project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
|
||||
title: Optional[StrictStr] = None
|
||||
unique_programme_part: Optional[StrictStr] = Field(default=None, alias="uniqueProgrammePart")
|
||||
__properties: ClassVar[List[str]] = ["id", "legalBasis", "projectID", "title", "uniqueProgrammePart"]
|
||||
|
||||
model_config = ConfigDict(
|
||||
validate_by_name=True,
|
||||
validate_by_alias=True,
|
||||
validate_assignment=True,
|
||||
protected_namespaces=(),
|
||||
)
|
||||
|
||||
|
||||
def to_str(self) -> str:
|
||||
"""Returns the string representation of the model using alias"""
|
||||
return pprint.pformat(self.model_dump(by_alias=True))
|
||||
|
||||
def to_json(self) -> str:
|
||||
"""Returns the JSON representation of the model using alias"""
|
||||
return json.dumps(to_jsonable_python(self.to_dict()))
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, json_str: str) -> Optional[Self]:
|
||||
"""Create an instance of H2020LegalBasis from a JSON string"""
|
||||
return cls.from_dict(json.loads(json_str))
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Return the dictionary representation of the model using alias.
|
||||
|
||||
This has the following differences from calling pydantic's
|
||||
`self.model_dump(by_alias=True)`:
|
||||
|
||||
* `None` is only added to the output dict for nullable fields that
|
||||
were set at model initialization. Other fields with value `None`
|
||||
are ignored.
|
||||
"""
|
||||
excluded_fields: Set[str] = set([
|
||||
])
|
||||
|
||||
_dict = self.model_dump(
|
||||
by_alias=True,
|
||||
exclude=excluded_fields,
|
||||
exclude_none=True,
|
||||
)
|
||||
return _dict
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
|
||||
"""Create an instance of H2020LegalBasis from a dict"""
|
||||
if obj is None:
|
||||
return None
|
||||
|
||||
if not isinstance(obj, dict):
|
||||
return cls.model_validate(obj)
|
||||
|
||||
_obj = cls.model_validate({
|
||||
"id": obj.get("id"),
|
||||
"legalBasis": obj.get("legalBasis"),
|
||||
"projectID": obj.get("projectID"),
|
||||
"title": obj.get("title"),
|
||||
"uniqueProgrammePart": obj.get("uniqueProgrammePart")
|
||||
})
|
||||
return _obj
|
||||
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
CORDIS Horizon 2020 Multi-Index API
|
||||
|
||||
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by OpenAPI Generator (https://openapi-generator.tech)
|
||||
|
||||
Do not edit the class manually.
|
||||
""" # noqa: E501
|
||||
|
||||
|
||||
from __future__ import annotations
|
||||
import pprint
|
||||
import re # noqa: F401
|
||||
import json
|
||||
|
||||
from datetime import datetime
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt, StrictStr
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
|
||||
class H2020Organization(BaseModel):
|
||||
"""
|
||||
H2020Organization
|
||||
""" # noqa: E501
|
||||
sme: Optional[StrictBool] = Field(default=None, alias="SME")
|
||||
active: Optional[StrictBool] = None
|
||||
activity_type: Optional[StrictStr] = Field(default=None, alias="activityType")
|
||||
city: Optional[StrictStr] = None
|
||||
contact_form: Optional[StrictStr] = Field(default=None, alias="contactForm")
|
||||
content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate")
|
||||
country: Optional[StrictStr] = None
|
||||
ec_contribution: Optional[StrictFloat] = Field(default=None, alias="ecContribution")
|
||||
end_of_participation: Optional[StrictBool] = Field(default=None, alias="endOfParticipation")
|
||||
geolocation: Optional[StrictStr] = None
|
||||
id: Optional[StrictStr] = None
|
||||
name: Optional[StrictStr] = None
|
||||
net_ec_contribution: Optional[StrictFloat] = Field(default=None, alias="netEcContribution")
|
||||
nuts_code: Optional[StrictStr] = Field(default=None, alias="nutsCode")
|
||||
order: Optional[StrictInt] = None
|
||||
organisation_id: Optional[StrictStr] = Field(default=None, alias="organisationID")
|
||||
organization_url: Optional[StrictStr] = Field(default=None, alias="organizationURL")
|
||||
post_code: Optional[StrictStr] = Field(default=None, alias="postCode")
|
||||
project_acronym: Optional[StrictStr] = Field(default=None, alias="projectAcronym")
|
||||
project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
|
||||
rcn: Optional[StrictStr] = None
|
||||
role: Optional[StrictStr] = None
|
||||
short_name: Optional[StrictStr] = Field(default=None, alias="shortName")
|
||||
street: Optional[StrictStr] = None
|
||||
total_cost: Optional[StrictFloat] = Field(default=None, alias="totalCost")
|
||||
vat_number: Optional[StrictStr] = Field(default=None, alias="vatNumber")
|
||||
__properties: ClassVar[List[str]] = ["SME", "active", "activityType", "city", "contactForm", "contentUpdateDate", "country", "ecContribution", "endOfParticipation", "geolocation", "id", "name", "netEcContribution", "nutsCode", "order", "organisationID", "organizationURL", "postCode", "projectAcronym", "projectID", "rcn", "role", "shortName", "street", "totalCost", "vatNumber"]
|
||||
|
||||
model_config = ConfigDict(
|
||||
validate_by_name=True,
|
||||
validate_by_alias=True,
|
||||
validate_assignment=True,
|
||||
protected_namespaces=(),
|
||||
)
|
||||
|
||||
|
||||
def to_str(self) -> str:
|
||||
"""Returns the string representation of the model using alias"""
|
||||
return pprint.pformat(self.model_dump(by_alias=True))
|
||||
|
||||
def to_json(self) -> str:
|
||||
"""Returns the JSON representation of the model using alias"""
|
||||
return json.dumps(to_jsonable_python(self.to_dict()))
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, json_str: str) -> Optional[Self]:
|
||||
"""Create an instance of H2020Organization from a JSON string"""
|
||||
return cls.from_dict(json.loads(json_str))
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Return the dictionary representation of the model using alias.
|
||||
|
||||
This has the following differences from calling pydantic's
|
||||
`self.model_dump(by_alias=True)`:
|
||||
|
||||
* `None` is only added to the output dict for nullable fields that
|
||||
were set at model initialization. Other fields with value `None`
|
||||
are ignored.
|
||||
"""
|
||||
excluded_fields: Set[str] = set([
|
||||
])
|
||||
|
||||
_dict = self.model_dump(
|
||||
by_alias=True,
|
||||
exclude=excluded_fields,
|
||||
exclude_none=True,
|
||||
)
|
||||
return _dict
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
|
||||
"""Create an instance of H2020Organization from a dict"""
|
||||
if obj is None:
|
||||
return None
|
||||
|
||||
if not isinstance(obj, dict):
|
||||
return cls.model_validate(obj)
|
||||
|
||||
_obj = cls.model_validate({
|
||||
"SME": obj.get("SME"),
|
||||
"active": obj.get("active"),
|
||||
"activityType": obj.get("activityType"),
|
||||
"city": obj.get("city"),
|
||||
"contactForm": obj.get("contactForm"),
|
||||
"contentUpdateDate": obj.get("contentUpdateDate"),
|
||||
"country": obj.get("country"),
|
||||
"ecContribution": obj.get("ecContribution"),
|
||||
"endOfParticipation": obj.get("endOfParticipation"),
|
||||
"geolocation": obj.get("geolocation"),
|
||||
"id": obj.get("id"),
|
||||
"name": obj.get("name"),
|
||||
"netEcContribution": obj.get("netEcContribution"),
|
||||
"nutsCode": obj.get("nutsCode"),
|
||||
"order": obj.get("order"),
|
||||
"organisationID": obj.get("organisationID"),
|
||||
"organizationURL": obj.get("organizationURL"),
|
||||
"postCode": obj.get("postCode"),
|
||||
"projectAcronym": obj.get("projectAcronym"),
|
||||
"projectID": obj.get("projectID"),
|
||||
"rcn": obj.get("rcn"),
|
||||
"role": obj.get("role"),
|
||||
"shortName": obj.get("shortName"),
|
||||
"street": obj.get("street"),
|
||||
"totalCost": obj.get("totalCost"),
|
||||
"vatNumber": obj.get("vatNumber")
|
||||
})
|
||||
return _obj
|
||||
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
CORDIS Horizon 2020 Multi-Index API
|
||||
|
||||
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by OpenAPI Generator (https://openapi-generator.tech)
|
||||
|
||||
Do not edit the class manually.
|
||||
""" # noqa: E501
|
||||
|
||||
|
||||
from __future__ import annotations
|
||||
import pprint
|
||||
import re # noqa: F401
|
||||
import json
|
||||
|
||||
from datetime import date, datetime
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt, StrictStr
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
|
||||
class H2020Project(BaseModel):
|
||||
"""
|
||||
H2020Project
|
||||
""" # noqa: E501
|
||||
acronym: Optional[StrictStr] = None
|
||||
content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate")
|
||||
ec_max_contribution: Optional[StrictFloat] = Field(default=None, alias="ecMaxContribution")
|
||||
ec_signature_date: Optional[date] = Field(default=None, alias="ecSignatureDate")
|
||||
end_date: Optional[date] = Field(default=None, alias="endDate")
|
||||
framework_programme: Optional[StrictStr] = Field(default=None, alias="frameworkProgramme")
|
||||
funding_scheme: Optional[StrictStr] = Field(default=None, alias="fundingScheme")
|
||||
grant_doi: Optional[StrictStr] = Field(default=None, alias="grantDoi")
|
||||
human_validated: Optional[StrictBool] = Field(default=None, alias="humanValidated")
|
||||
id: Optional[StrictStr] = None
|
||||
keywords: Optional[StrictStr] = None
|
||||
legal_basis: Optional[StrictStr] = Field(default=None, alias="legalBasis")
|
||||
master_call: Optional[StrictStr] = Field(default=None, alias="masterCall")
|
||||
nature: Optional[StrictStr] = None
|
||||
objective: Optional[StrictStr] = None
|
||||
rcn: Optional[StrictStr] = None
|
||||
start_date: Optional[date] = Field(default=None, alias="startDate")
|
||||
status: Optional[StrictStr] = None
|
||||
sub_call: Optional[StrictStr] = Field(default=None, alias="subCall")
|
||||
title: Optional[StrictStr] = None
|
||||
topics: Optional[StrictStr] = None
|
||||
total_cost: Optional[StrictFloat] = Field(default=None, alias="totalCost")
|
||||
__properties: ClassVar[List[str]] = ["acronym", "contentUpdateDate", "ecMaxContribution", "ecSignatureDate", "endDate", "frameworkProgramme", "fundingScheme", "grantDoi", "humanValidated", "id", "keywords", "legalBasis", "masterCall", "nature", "objective", "rcn", "startDate", "status", "subCall", "title", "topics", "totalCost"]
|
||||
|
||||
model_config = ConfigDict(
|
||||
validate_by_name=True,
|
||||
validate_by_alias=True,
|
||||
validate_assignment=True,
|
||||
protected_namespaces=(),
|
||||
)
|
||||
|
||||
|
||||
def to_str(self) -> str:
|
||||
"""Returns the string representation of the model using alias"""
|
||||
return pprint.pformat(self.model_dump(by_alias=True))
|
||||
|
||||
def to_json(self) -> str:
|
||||
"""Returns the JSON representation of the model using alias"""
|
||||
return json.dumps(to_jsonable_python(self.to_dict()))
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, json_str: str) -> Optional[Self]:
|
||||
"""Create an instance of H2020Project from a JSON string"""
|
||||
return cls.from_dict(json.loads(json_str))
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Return the dictionary representation of the model using alias.
|
||||
|
||||
This has the following differences from calling pydantic's
|
||||
`self.model_dump(by_alias=True)`:
|
||||
|
||||
* `None` is only added to the output dict for nullable fields that
|
||||
were set at model initialization. Other fields with value `None`
|
||||
are ignored.
|
||||
"""
|
||||
excluded_fields: Set[str] = set([
|
||||
])
|
||||
|
||||
_dict = self.model_dump(
|
||||
by_alias=True,
|
||||
exclude=excluded_fields,
|
||||
exclude_none=True,
|
||||
)
|
||||
return _dict
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
|
||||
"""Create an instance of H2020Project from a dict"""
|
||||
if obj is None:
|
||||
return None
|
||||
|
||||
if not isinstance(obj, dict):
|
||||
return cls.model_validate(obj)
|
||||
|
||||
_obj = cls.model_validate({
|
||||
"acronym": obj.get("acronym"),
|
||||
"contentUpdateDate": obj.get("contentUpdateDate"),
|
||||
"ecMaxContribution": obj.get("ecMaxContribution"),
|
||||
"ecSignatureDate": obj.get("ecSignatureDate"),
|
||||
"endDate": obj.get("endDate"),
|
||||
"frameworkProgramme": obj.get("frameworkProgramme"),
|
||||
"fundingScheme": obj.get("fundingScheme"),
|
||||
"grantDoi": obj.get("grantDoi"),
|
||||
"humanValidated": obj.get("humanValidated"),
|
||||
"id": obj.get("id"),
|
||||
"keywords": obj.get("keywords"),
|
||||
"legalBasis": obj.get("legalBasis"),
|
||||
"masterCall": obj.get("masterCall"),
|
||||
"nature": obj.get("nature"),
|
||||
"objective": obj.get("objective"),
|
||||
"rcn": obj.get("rcn"),
|
||||
"startDate": obj.get("startDate"),
|
||||
"status": obj.get("status"),
|
||||
"subCall": obj.get("subCall"),
|
||||
"title": obj.get("title"),
|
||||
"topics": obj.get("topics"),
|
||||
"totalCost": obj.get("totalCost")
|
||||
})
|
||||
return _obj
|
||||
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
CORDIS Horizon 2020 Multi-Index API - Extended Models
|
||||
""" # noqa: E501
|
||||
|
||||
from __future__ import annotations
|
||||
import pprint
|
||||
import re # noqa: F401
|
||||
import json
|
||||
from datetime import date, datetime
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt, StrictStr
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
|
||||
# Import all the base models
|
||||
from inse.models.projects_eu_cordis.horizon2020.h2020_project import H2020Project
|
||||
from inse.models.projects_eu_cordis.horizon2020.h2020_organization import H2020Organization
|
||||
from inse.models.projects_eu_cordis.horizon2020.h2020_publication import H2020Publication
|
||||
from inse.models.projects_eu_cordis.horizon2020.h2020_deliverable import H2020Deliverable
|
||||
from inse.models.projects_eu_cordis.horizon2020.h2020_report_summary import H2020ReportSummary
|
||||
from inse.models.projects_eu_cordis.horizon2020.h2020_topic import H2020Topic
|
||||
from inse.models.projects_eu_cordis.horizon2020.h2020_web_link import H2020WebLink
|
||||
from inse.models.projects_eu_cordis.horizon2020.h2020_eurosci_voc import H2020EurosciVoc
|
||||
from inse.models.projects_eu_cordis.horizon2020.h2020_legal_basis import H2020LegalBasis
|
||||
from inse.models.projects_eu_cordis.horizon2020.h2020_erc_pi import H2020ErcPI
|
||||
|
||||
|
||||
class H2020ProjectDetails(BaseModel):
|
||||
"""
|
||||
Comprehensive Horizon 2020 Project model combining all related entities.
|
||||
This model extends the base H2020Project with all associated data.
|
||||
"""
|
||||
# Project core information (flattened from H2020Project)
|
||||
acronym: Optional[StrictStr] = None
|
||||
content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate")
|
||||
ec_max_contribution: Optional[StrictFloat] = Field(default=None, alias="ecMaxContribution")
|
||||
ec_signature_date: Optional[date] = Field(default=None, alias="ecSignatureDate")
|
||||
end_date: Optional[date] = Field(default=None, alias="endDate")
|
||||
framework_programme: Optional[StrictStr] = Field(default=None, alias="frameworkProgramme")
|
||||
funding_scheme: Optional[StrictStr] = Field(default=None, alias="fundingScheme")
|
||||
grant_doi: Optional[StrictStr] = Field(default=None, alias="grantDoi")
|
||||
human_validated: Optional[StrictBool] = Field(default=None, alias="humanValidated")
|
||||
id: Optional[StrictStr] = None
|
||||
keywords: Optional[StrictStr] = None
|
||||
legal_basis: Optional[StrictStr] = Field(default=None, alias="legalBasis")
|
||||
master_call: Optional[StrictStr] = Field(default=None, alias="masterCall")
|
||||
nature: Optional[StrictStr] = None
|
||||
objective: Optional[StrictStr] = None
|
||||
rcn: Optional[StrictStr] = None
|
||||
start_date: Optional[date] = Field(default=None, alias="startDate")
|
||||
status: Optional[StrictStr] = None
|
||||
sub_call: Optional[StrictStr] = Field(default=None, alias="subCall")
|
||||
title: Optional[StrictStr] = None
|
||||
topics: Optional[StrictStr] = None
|
||||
total_cost: Optional[StrictFloat] = Field(default=None, alias="totalCost")
|
||||
|
||||
# Related entities (collections)
|
||||
organizations: Optional[List[H2020Organization]] = Field(default=None, description="Organizations participating in the project")
|
||||
publications: Optional[List[H2020Publication]] = Field(default=None, description="Publications related to the project")
|
||||
deliverables: Optional[List[H2020Deliverable]] = Field(default=None, description="Deliverables of the project")
|
||||
report_summaries: Optional[List[H2020ReportSummary]] = Field(default=None, alias="reportSummaries", description="Report summaries for the project")
|
||||
topics_list: Optional[List[H2020Topic]] = Field(default=None, alias="topicsList", description="Topics associated with the project")
|
||||
web_links: Optional[List[H2020WebLink]] = Field(default=None, alias="webLinks", description="Web links related to the project")
|
||||
eurosci_voc: Optional[List[H2020EurosciVoc]] = Field(default=None, alias="eurosciVoc", description="EuroSciVoc classifications")
|
||||
legal_basis_list: Optional[List[H2020LegalBasis]] = Field(default=None, alias="legalBasisList", description="Legal basis information")
|
||||
erc_principal_investigators: Optional[List[H2020ErcPI]] = Field(default=None, alias="ercPrincipalInvestigators", description="ERC Principal Investigators (specific to H2020)")
|
||||
|
||||
# Project statistics (aggregated)
|
||||
organization_count: Optional[int] = Field(default=None, alias="organizationCount")
|
||||
publication_count: Optional[int] = Field(default=None, alias="publicationCount")
|
||||
deliverable_count: Optional[int] = Field(default=None, alias="deliverableCount")
|
||||
erc_pi_count: Optional[int] = Field(default=None, alias="ercPiCount")
|
||||
|
||||
__properties: ClassVar[List[str]] = [
|
||||
"acronym", "contentUpdateDate", "ecMaxContribution", "ecSignatureDate",
|
||||
"endDate", "frameworkProgramme", "fundingScheme", "grantDoi",
|
||||
"humanValidated", "id", "keywords", "legalBasis", "masterCall",
|
||||
"nature", "objective", "rcn", "startDate", "status", "subCall",
|
||||
"title", "topics", "totalCost",
|
||||
"organizations", "publications", "deliverables", "reportSummaries",
|
||||
"topicsList", "webLinks", "eurosciVoc", "legalBasisList",
|
||||
"ercPrincipalInvestigators",
|
||||
"organizationCount", "publicationCount", "deliverableCount", "ercPiCount"
|
||||
]
|
||||
|
||||
model_config = ConfigDict(
|
||||
validate_by_name=True,
|
||||
validate_by_alias=True,
|
||||
validate_assignment=True,
|
||||
protected_namespaces=(),
|
||||
populate_by_name=True,
|
||||
)
|
||||
|
||||
def to_str(self) -> str:
|
||||
"""Returns the string representation of the model using alias"""
|
||||
return pprint.pformat(self.model_dump(by_alias=True))
|
||||
|
||||
def to_json(self) -> str:
|
||||
"""Returns the JSON representation of the model using alias"""
|
||||
return json.dumps(to_jsonable_python(self.to_dict()))
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, json_str: str) -> Optional[Self]:
|
||||
"""Create an instance of H2020ProjectDetailed from a JSON string"""
|
||||
return cls.from_dict(json.loads(json_str))
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Return the dictionary representation of the model using alias."""
|
||||
excluded_fields: Set[str] = set([
|
||||
])
|
||||
|
||||
_dict = self.model_dump(
|
||||
by_alias=True,
|
||||
exclude=excluded_fields,
|
||||
exclude_none=True,
|
||||
)
|
||||
return _dict
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
|
||||
"""Create an instance of H2020ProjectDetailed from a dict"""
|
||||
if obj is None:
|
||||
return None
|
||||
|
||||
if not isinstance(obj, dict):
|
||||
return cls.model_validate(obj)
|
||||
|
||||
_obj = cls.model_validate({
|
||||
# Project core fields
|
||||
"acronym": obj.get("acronym"),
|
||||
"contentUpdateDate": obj.get("contentUpdateDate"),
|
||||
"ecMaxContribution": obj.get("ecMaxContribution"),
|
||||
"ecSignatureDate": obj.get("ecSignatureDate"),
|
||||
"endDate": obj.get("endDate"),
|
||||
"frameworkProgramme": obj.get("frameworkProgramme"),
|
||||
"fundingScheme": obj.get("fundingScheme"),
|
||||
"grantDoi": obj.get("grantDoi"),
|
||||
"humanValidated": obj.get("humanValidated"),
|
||||
"id": obj.get("id"),
|
||||
"keywords": obj.get("keywords"),
|
||||
"legalBasis": obj.get("legalBasis"),
|
||||
"masterCall": obj.get("masterCall"),
|
||||
"nature": obj.get("nature"),
|
||||
"objective": obj.get("objective"),
|
||||
"rcn": obj.get("rcn"),
|
||||
"startDate": obj.get("startDate"),
|
||||
"status": obj.get("status"),
|
||||
"subCall": obj.get("subCall"),
|
||||
"title": obj.get("title"),
|
||||
"topics": obj.get("topics"),
|
||||
"totalCost": obj.get("totalCost"),
|
||||
|
||||
# Related entities
|
||||
"organizations": [H2020Organization.from_dict(org) for org in obj.get("organizations", [])] if obj.get("organizations") else None,
|
||||
"publications": [H2020Publication.from_dict(pub) for pub in obj.get("publications", [])] if obj.get("publications") else None,
|
||||
"deliverables": [H2020Deliverable.from_dict(deliv) for deliv in obj.get("deliverables", [])] if obj.get("deliverables") else None,
|
||||
"reportSummaries": [H2020ReportSummary.from_dict(report) for report in obj.get("reportSummaries", [])] if obj.get("reportSummaries") else None,
|
||||
"topicsList": [H2020Topic.from_dict(topic) for topic in obj.get("topicsList", [])] if obj.get("topicsList") else None,
|
||||
"webLinks": [H2020WebLink.from_dict(link) for link in obj.get("webLinks", [])] if obj.get("webLinks") else None,
|
||||
"eurosciVoc": [H2020EurosciVoc.from_dict(voc) for voc in obj.get("eurosciVoc", [])] if obj.get("eurosciVoc") else None,
|
||||
"legalBasisList": [H2020LegalBasis.from_dict(lb) for lb in obj.get("legalBasisList", [])] if obj.get("legalBasisList") else None,
|
||||
"ercPrincipalInvestigators": [H2020ErcPI.from_dict(pi) for pi in obj.get("ercPrincipalInvestigators", [])] if obj.get("ercPrincipalInvestigators") else None,
|
||||
|
||||
# Statistics
|
||||
"organizationCount": len(obj.get("organizations", [])) if obj.get("organizations") else 0,
|
||||
"publicationCount": len(obj.get("publications", [])) if obj.get("publications") else 0,
|
||||
"deliverableCount": len(obj.get("deliverables", [])) if obj.get("deliverables") else 0,
|
||||
"ercPiCount": len(obj.get("ercPrincipalInvestigators", [])) if obj.get("ercPrincipalInvestigators") else 0,
|
||||
})
|
||||
return _obj
|
||||
|
||||
@classmethod
|
||||
def from_project_with_relations(
|
||||
cls,
|
||||
project: H2020Project,
|
||||
organizations: Optional[List[H2020Organization]] = None,
|
||||
publications: Optional[List[H2020Publication]] = None,
|
||||
deliverables: Optional[List[H2020Deliverable]] = None,
|
||||
report_summaries: Optional[List[H2020ReportSummary]] = None,
|
||||
topics_list: Optional[List[H2020Topic]] = None,
|
||||
web_links: Optional[List[H2020WebLink]] = None,
|
||||
eurosci_voc: Optional[List[H2020EurosciVoc]] = None,
|
||||
legal_basis_list: Optional[List[H2020LegalBasis]] = None,
|
||||
erc_principal_investigators: Optional[List[H2020ErcPI]] = None,
|
||||
) -> Self:
|
||||
"""
|
||||
Factory method to create a detailed project from a base project and its relations.
|
||||
|
||||
Args:
|
||||
project: The base H2020Project object
|
||||
organizations: List of organizations participating in the project
|
||||
publications: List of publications related to the project
|
||||
deliverables: List of deliverables of the project
|
||||
report_summaries: List of report summaries
|
||||
topics_list: List of topics associated with the project
|
||||
web_links: List of web links
|
||||
eurosci_voc: List of EuroSciVoc classifications
|
||||
legal_basis_list: List of legal basis information
|
||||
erc_principal_investigators: List of ERC Principal Investigators
|
||||
|
||||
Returns:
|
||||
H2020ProjectDetailed instance
|
||||
"""
|
||||
project_dict = project.to_dict() if project else {}
|
||||
|
||||
return cls(
|
||||
**project_dict,
|
||||
organizations=organizations or [],
|
||||
publications=publications or [],
|
||||
deliverables=deliverables or [],
|
||||
reportSummaries=report_summaries or [],
|
||||
topicsList=topics_list or [],
|
||||
webLinks=web_links or [],
|
||||
eurosciVoc=eurosci_voc or [],
|
||||
legalBasisList=legal_basis_list or [],
|
||||
ercPrincipalInvestigators=erc_principal_investigators or [],
|
||||
organizationCount=len(organizations) if organizations else 0,
|
||||
publicationCount=len(publications) if publications else 0,
|
||||
deliverableCount=len(deliverables) if deliverables else 0,
|
||||
ercPiCount=len(erc_principal_investigators) if erc_principal_investigators else 0,
|
||||
)
|
||||
@@ -0,0 +1,123 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
CORDIS Horizon 2020 Multi-Index API
|
||||
|
||||
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by OpenAPI Generator (https://openapi-generator.tech)
|
||||
|
||||
Do not edit the class manually.
|
||||
""" # noqa: E501
|
||||
|
||||
|
||||
from __future__ import annotations
|
||||
import pprint
|
||||
import re # noqa: F401
|
||||
import json
|
||||
|
||||
from datetime import datetime
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
|
||||
class H2020Publication(BaseModel):
|
||||
"""
|
||||
H2020Publication
|
||||
""" # noqa: E501
|
||||
authors: Optional[StrictStr] = None
|
||||
collection: Optional[StrictStr] = None
|
||||
content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate")
|
||||
doi: Optional[StrictStr] = None
|
||||
id: Optional[StrictStr] = None
|
||||
is_published_as: Optional[StrictStr] = Field(default=None, alias="isPublishedAs")
|
||||
journal_number: Optional[StrictStr] = Field(default=None, alias="journalNumber")
|
||||
journal_title: Optional[StrictStr] = Field(default=None, alias="journalTitle")
|
||||
project_acronym: Optional[StrictStr] = Field(default=None, alias="projectAcronym")
|
||||
project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
|
||||
published_pages: Optional[StrictStr] = Field(default=None, alias="publishedPages")
|
||||
published_year: Optional[StrictInt] = Field(default=None, alias="publishedYear")
|
||||
publisher: Optional[StrictStr] = None
|
||||
qa_processed_doi: Optional[StrictStr] = Field(default=None, alias="qaProcessedDoi")
|
||||
rcn: Optional[StrictStr] = None
|
||||
repository_url: Optional[StrictStr] = Field(default=None, alias="repositoryUrl")
|
||||
title: Optional[StrictStr] = None
|
||||
volume: Optional[StrictStr] = None
|
||||
__properties: ClassVar[List[str]] = ["authors", "collection", "contentUpdateDate", "doi", "id", "isPublishedAs", "journalNumber", "journalTitle", "projectAcronym", "projectID", "publishedPages", "publishedYear", "publisher", "qaProcessedDoi", "rcn", "repositoryUrl", "title", "volume"]
|
||||
|
||||
model_config = ConfigDict(
|
||||
validate_by_name=True,
|
||||
validate_by_alias=True,
|
||||
validate_assignment=True,
|
||||
protected_namespaces=(),
|
||||
)
|
||||
|
||||
|
||||
def to_str(self) -> str:
|
||||
"""Returns the string representation of the model using alias"""
|
||||
return pprint.pformat(self.model_dump(by_alias=True))
|
||||
|
||||
def to_json(self) -> str:
|
||||
"""Returns the JSON representation of the model using alias"""
|
||||
return json.dumps(to_jsonable_python(self.to_dict()))
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, json_str: str) -> Optional[Self]:
|
||||
"""Create an instance of H2020Publication from a JSON string"""
|
||||
return cls.from_dict(json.loads(json_str))
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Return the dictionary representation of the model using alias.
|
||||
|
||||
This has the following differences from calling pydantic's
|
||||
`self.model_dump(by_alias=True)`:
|
||||
|
||||
* `None` is only added to the output dict for nullable fields that
|
||||
were set at model initialization. Other fields with value `None`
|
||||
are ignored.
|
||||
"""
|
||||
excluded_fields: Set[str] = set([
|
||||
])
|
||||
|
||||
_dict = self.model_dump(
|
||||
by_alias=True,
|
||||
exclude=excluded_fields,
|
||||
exclude_none=True,
|
||||
)
|
||||
return _dict
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
|
||||
"""Create an instance of H2020Publication from a dict"""
|
||||
if obj is None:
|
||||
return None
|
||||
|
||||
if not isinstance(obj, dict):
|
||||
return cls.model_validate(obj)
|
||||
|
||||
_obj = cls.model_validate({
|
||||
"authors": obj.get("authors"),
|
||||
"collection": obj.get("collection"),
|
||||
"contentUpdateDate": obj.get("contentUpdateDate"),
|
||||
"doi": obj.get("doi"),
|
||||
"id": obj.get("id"),
|
||||
"isPublishedAs": obj.get("isPublishedAs"),
|
||||
"journalNumber": obj.get("journalNumber"),
|
||||
"journalTitle": obj.get("journalTitle"),
|
||||
"projectAcronym": obj.get("projectAcronym"),
|
||||
"projectID": obj.get("projectID"),
|
||||
"publishedPages": obj.get("publishedPages"),
|
||||
"publishedYear": obj.get("publishedYear"),
|
||||
"publisher": obj.get("publisher"),
|
||||
"qaProcessedDoi": obj.get("qaProcessedDoi"),
|
||||
"rcn": obj.get("rcn"),
|
||||
"repositoryUrl": obj.get("repositoryUrl"),
|
||||
"title": obj.get("title"),
|
||||
"volume": obj.get("volume")
|
||||
})
|
||||
return _obj
|
||||
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
CORDIS Horizon 2020 Multi-Index API
|
||||
|
||||
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by OpenAPI Generator (https://openapi-generator.tech)
|
||||
|
||||
Do not edit the class manually.
|
||||
""" # noqa: E501
|
||||
|
||||
|
||||
from __future__ import annotations
|
||||
import pprint
|
||||
import re # noqa: F401
|
||||
import json
|
||||
|
||||
from datetime import datetime
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictStr
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
|
||||
class H2020ReportSummary(BaseModel):
|
||||
"""
|
||||
H2020ReportSummary
|
||||
""" # noqa: E501
|
||||
attachments: Optional[StrictStr] = None
|
||||
content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate")
|
||||
id: Optional[StrictStr] = None
|
||||
project_acronym: Optional[StrictStr] = Field(default=None, alias="projectAcronym")
|
||||
project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
|
||||
rcn: Optional[StrictStr] = None
|
||||
title: Optional[StrictStr] = None
|
||||
__properties: ClassVar[List[str]] = ["attachments", "contentUpdateDate", "id", "projectAcronym", "projectID", "rcn", "title"]
|
||||
|
||||
model_config = ConfigDict(
|
||||
validate_by_name=True,
|
||||
validate_by_alias=True,
|
||||
validate_assignment=True,
|
||||
protected_namespaces=(),
|
||||
)
|
||||
|
||||
|
||||
def to_str(self) -> str:
|
||||
"""Returns the string representation of the model using alias"""
|
||||
return pprint.pformat(self.model_dump(by_alias=True))
|
||||
|
||||
def to_json(self) -> str:
|
||||
"""Returns the JSON representation of the model using alias"""
|
||||
return json.dumps(to_jsonable_python(self.to_dict()))
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, json_str: str) -> Optional[Self]:
|
||||
"""Create an instance of H2020ReportSummary from a JSON string"""
|
||||
return cls.from_dict(json.loads(json_str))
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Return the dictionary representation of the model using alias.
|
||||
|
||||
This has the following differences from calling pydantic's
|
||||
`self.model_dump(by_alias=True)`:
|
||||
|
||||
* `None` is only added to the output dict for nullable fields that
|
||||
were set at model initialization. Other fields with value `None`
|
||||
are ignored.
|
||||
"""
|
||||
excluded_fields: Set[str] = set([
|
||||
])
|
||||
|
||||
_dict = self.model_dump(
|
||||
by_alias=True,
|
||||
exclude=excluded_fields,
|
||||
exclude_none=True,
|
||||
)
|
||||
return _dict
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
|
||||
"""Create an instance of H2020ReportSummary from a dict"""
|
||||
if obj is None:
|
||||
return None
|
||||
|
||||
if not isinstance(obj, dict):
|
||||
return cls.model_validate(obj)
|
||||
|
||||
_obj = cls.model_validate({
|
||||
"attachments": obj.get("attachments"),
|
||||
"contentUpdateDate": obj.get("contentUpdateDate"),
|
||||
"id": obj.get("id"),
|
||||
"projectAcronym": obj.get("projectAcronym"),
|
||||
"projectID": obj.get("projectID"),
|
||||
"rcn": obj.get("rcn"),
|
||||
"title": obj.get("title")
|
||||
})
|
||||
return _obj
|
||||
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
CORDIS Horizon 2020 Multi-Index API
|
||||
|
||||
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by OpenAPI Generator (https://openapi-generator.tech)
|
||||
|
||||
Do not edit the class manually.
|
||||
""" # noqa: E501
|
||||
|
||||
|
||||
from __future__ import annotations
|
||||
import pprint
|
||||
import re # noqa: F401
|
||||
import json
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictStr
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
|
||||
class H2020Topic(BaseModel):
|
||||
"""
|
||||
H2020Topic
|
||||
""" # noqa: E501
|
||||
id: Optional[StrictStr] = None
|
||||
project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
|
||||
title: Optional[StrictStr] = None
|
||||
topic: Optional[StrictStr] = None
|
||||
__properties: ClassVar[List[str]] = ["id", "projectID", "title", "topic"]
|
||||
|
||||
model_config = ConfigDict(
|
||||
validate_by_name=True,
|
||||
validate_by_alias=True,
|
||||
validate_assignment=True,
|
||||
protected_namespaces=(),
|
||||
)
|
||||
|
||||
|
||||
def to_str(self) -> str:
|
||||
"""Returns the string representation of the model using alias"""
|
||||
return pprint.pformat(self.model_dump(by_alias=True))
|
||||
|
||||
def to_json(self) -> str:
|
||||
"""Returns the JSON representation of the model using alias"""
|
||||
return json.dumps(to_jsonable_python(self.to_dict()))
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, json_str: str) -> Optional[Self]:
|
||||
"""Create an instance of H2020Topic from a JSON string"""
|
||||
return cls.from_dict(json.loads(json_str))
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Return the dictionary representation of the model using alias.
|
||||
|
||||
This has the following differences from calling pydantic's
|
||||
`self.model_dump(by_alias=True)`:
|
||||
|
||||
* `None` is only added to the output dict for nullable fields that
|
||||
were set at model initialization. Other fields with value `None`
|
||||
are ignored.
|
||||
"""
|
||||
excluded_fields: Set[str] = set([
|
||||
])
|
||||
|
||||
_dict = self.model_dump(
|
||||
by_alias=True,
|
||||
exclude=excluded_fields,
|
||||
exclude_none=True,
|
||||
)
|
||||
return _dict
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
|
||||
"""Create an instance of H2020Topic from a dict"""
|
||||
if obj is None:
|
||||
return None
|
||||
|
||||
if not isinstance(obj, dict):
|
||||
return cls.model_validate(obj)
|
||||
|
||||
_obj = cls.model_validate({
|
||||
"id": obj.get("id"),
|
||||
"projectID": obj.get("projectID"),
|
||||
"title": obj.get("title"),
|
||||
"topic": obj.get("topic")
|
||||
})
|
||||
return _obj
|
||||
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
CORDIS Horizon 2020 Multi-Index API
|
||||
|
||||
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by OpenAPI Generator (https://openapi-generator.tech)
|
||||
|
||||
Do not edit the class manually.
|
||||
""" # noqa: E501
|
||||
|
||||
|
||||
from __future__ import annotations
|
||||
import pprint
|
||||
import re # noqa: F401
|
||||
import json
|
||||
|
||||
from datetime import datetime
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictStr
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
|
||||
class H2020WebLink(BaseModel):
|
||||
"""
|
||||
H2020WebLink
|
||||
""" # noqa: E501
|
||||
archived_date: Optional[datetime] = Field(default=None, alias="archivedDate")
|
||||
available_languages: Optional[StrictStr] = Field(default=None, alias="availableLanguages")
|
||||
id: Optional[StrictStr] = None
|
||||
link_id: Optional[StrictStr] = Field(default=None, alias="linkId")
|
||||
project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
|
||||
represents: Optional[StrictStr] = None
|
||||
source: Optional[StrictStr] = None
|
||||
status: Optional[StrictStr] = None
|
||||
type: Optional[StrictStr] = None
|
||||
url: Optional[StrictStr] = None
|
||||
__properties: ClassVar[List[str]] = ["archivedDate", "availableLanguages", "id", "linkId", "projectID", "represents", "source", "status", "type", "url"]
|
||||
|
||||
model_config = ConfigDict(
|
||||
validate_by_name=True,
|
||||
validate_by_alias=True,
|
||||
validate_assignment=True,
|
||||
protected_namespaces=(),
|
||||
)
|
||||
|
||||
|
||||
def to_str(self) -> str:
|
||||
"""Returns the string representation of the model using alias"""
|
||||
return pprint.pformat(self.model_dump(by_alias=True))
|
||||
|
||||
def to_json(self) -> str:
|
||||
"""Returns the JSON representation of the model using alias"""
|
||||
return json.dumps(to_jsonable_python(self.to_dict()))
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, json_str: str) -> Optional[Self]:
|
||||
"""Create an instance of H2020WebLink from a JSON string"""
|
||||
return cls.from_dict(json.loads(json_str))
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Return the dictionary representation of the model using alias.
|
||||
|
||||
This has the following differences from calling pydantic's
|
||||
`self.model_dump(by_alias=True)`:
|
||||
|
||||
* `None` is only added to the output dict for nullable fields that
|
||||
were set at model initialization. Other fields with value `None`
|
||||
are ignored.
|
||||
"""
|
||||
excluded_fields: Set[str] = set([
|
||||
])
|
||||
|
||||
_dict = self.model_dump(
|
||||
by_alias=True,
|
||||
exclude=excluded_fields,
|
||||
exclude_none=True,
|
||||
)
|
||||
return _dict
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
|
||||
"""Create an instance of H2020WebLink from a dict"""
|
||||
if obj is None:
|
||||
return None
|
||||
|
||||
if not isinstance(obj, dict):
|
||||
return cls.model_validate(obj)
|
||||
|
||||
_obj = cls.model_validate({
|
||||
"archivedDate": obj.get("archivedDate"),
|
||||
"availableLanguages": obj.get("availableLanguages"),
|
||||
"id": obj.get("id"),
|
||||
"linkId": obj.get("linkId"),
|
||||
"projectID": obj.get("projectID"),
|
||||
"represents": obj.get("represents"),
|
||||
"source": obj.get("source"),
|
||||
"status": obj.get("status"),
|
||||
"type": obj.get("type"),
|
||||
"url": obj.get("url")
|
||||
})
|
||||
return _obj
|
||||
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
CORDIS Horizon Europe Multi-Index API
|
||||
|
||||
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by OpenAPI Generator (https://openapi-generator.tech)
|
||||
|
||||
Do not edit the class manually.
|
||||
""" # noqa: E501
|
||||
|
||||
|
||||
from __future__ import annotations
|
||||
import pprint
|
||||
import re # noqa: F401
|
||||
import json
|
||||
|
||||
from datetime import datetime
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictStr
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
|
||||
class HEUDeliverable(BaseModel):
|
||||
"""
|
||||
HEUDeliverable
|
||||
""" # noqa: E501
|
||||
collection: Optional[StrictStr] = None
|
||||
content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate")
|
||||
deliverable_type: Optional[StrictStr] = Field(default=None, alias="deliverableType")
|
||||
description: Optional[StrictStr] = None
|
||||
project_acronym: Optional[StrictStr] = Field(default=None, alias="projectAcronym")
|
||||
project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
|
||||
rcn: Optional[StrictStr] = None
|
||||
url: Optional[StrictStr] = None
|
||||
__properties: ClassVar[List[str]] = ["collection", "contentUpdateDate", "deliverableType", "description", "projectAcronym", "projectID", "rcn", "url"]
|
||||
|
||||
model_config = ConfigDict(
|
||||
validate_by_name=True,
|
||||
validate_by_alias=True,
|
||||
validate_assignment=True,
|
||||
protected_namespaces=(),
|
||||
)
|
||||
|
||||
|
||||
def to_str(self) -> str:
|
||||
"""Returns the string representation of the model using alias"""
|
||||
return pprint.pformat(self.model_dump(by_alias=True))
|
||||
|
||||
def to_json(self) -> str:
|
||||
"""Returns the JSON representation of the model using alias"""
|
||||
return json.dumps(to_jsonable_python(self.to_dict()))
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, json_str: str) -> Optional[Self]:
|
||||
"""Create an instance of HEUDeliverable from a JSON string"""
|
||||
return cls.from_dict(json.loads(json_str))
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Return the dictionary representation of the model using alias.
|
||||
|
||||
This has the following differences from calling pydantic's
|
||||
`self.model_dump(by_alias=True)`:
|
||||
|
||||
* `None` is only added to the output dict for nullable fields that
|
||||
were set at model initialization. Other fields with value `None`
|
||||
are ignored.
|
||||
"""
|
||||
excluded_fields: Set[str] = set([
|
||||
])
|
||||
|
||||
_dict = self.model_dump(
|
||||
by_alias=True,
|
||||
exclude=excluded_fields,
|
||||
exclude_none=True,
|
||||
)
|
||||
return _dict
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
|
||||
"""Create an instance of HEUDeliverable from a dict"""
|
||||
if obj is None:
|
||||
return None
|
||||
|
||||
if not isinstance(obj, dict):
|
||||
return cls.model_validate(obj)
|
||||
|
||||
_obj = cls.model_validate({
|
||||
"collection": obj.get("collection"),
|
||||
"contentUpdateDate": obj.get("contentUpdateDate"),
|
||||
"deliverableType": obj.get("deliverableType"),
|
||||
"description": obj.get("description"),
|
||||
"projectAcronym": obj.get("projectAcronym"),
|
||||
"projectID": obj.get("projectID"),
|
||||
"rcn": obj.get("rcn"),
|
||||
"url": obj.get("url")
|
||||
})
|
||||
return _obj
|
||||
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
CORDIS Horizon Europe Multi-Index API
|
||||
|
||||
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by OpenAPI Generator (https://openapi-generator.tech)
|
||||
|
||||
Do not edit the class manually.
|
||||
""" # noqa: E501
|
||||
|
||||
|
||||
from __future__ import annotations
|
||||
import pprint
|
||||
import re # noqa: F401
|
||||
import json
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictStr
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
|
||||
class HEUEurosciVoc(BaseModel):
|
||||
"""
|
||||
HEUEurosciVoc
|
||||
""" # noqa: E501
|
||||
code: Optional[StrictStr] = None
|
||||
description: Optional[StrictStr] = None
|
||||
id: Optional[StrictStr] = None
|
||||
path: Optional[StrictStr] = None
|
||||
project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
|
||||
title: Optional[StrictStr] = None
|
||||
__properties: ClassVar[List[str]] = ["code", "description", "id", "path", "projectID", "title"]
|
||||
|
||||
model_config = ConfigDict(
|
||||
validate_by_name=True,
|
||||
validate_by_alias=True,
|
||||
validate_assignment=True,
|
||||
protected_namespaces=(),
|
||||
)
|
||||
|
||||
|
||||
def to_str(self) -> str:
|
||||
"""Returns the string representation of the model using alias"""
|
||||
return pprint.pformat(self.model_dump(by_alias=True))
|
||||
|
||||
def to_json(self) -> str:
|
||||
"""Returns the JSON representation of the model using alias"""
|
||||
return json.dumps(to_jsonable_python(self.to_dict()))
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, json_str: str) -> Optional[Self]:
|
||||
"""Create an instance of HEUEurosciVoc from a JSON string"""
|
||||
return cls.from_dict(json.loads(json_str))
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Return the dictionary representation of the model using alias.
|
||||
|
||||
This has the following differences from calling pydantic's
|
||||
`self.model_dump(by_alias=True)`:
|
||||
|
||||
* `None` is only added to the output dict for nullable fields that
|
||||
were set at model initialization. Other fields with value `None`
|
||||
are ignored.
|
||||
"""
|
||||
excluded_fields: Set[str] = set([
|
||||
])
|
||||
|
||||
_dict = self.model_dump(
|
||||
by_alias=True,
|
||||
exclude=excluded_fields,
|
||||
exclude_none=True,
|
||||
)
|
||||
return _dict
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
|
||||
"""Create an instance of HEUEurosciVoc from a dict"""
|
||||
if obj is None:
|
||||
return None
|
||||
|
||||
if not isinstance(obj, dict):
|
||||
return cls.model_validate(obj)
|
||||
|
||||
_obj = cls.model_validate({
|
||||
"code": obj.get("code"),
|
||||
"description": obj.get("description"),
|
||||
"id": obj.get("id"),
|
||||
"path": obj.get("path"),
|
||||
"projectID": obj.get("projectID"),
|
||||
"title": obj.get("title")
|
||||
})
|
||||
return _obj
|
||||
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
CORDIS Horizon Europe Multi-Index API
|
||||
|
||||
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by OpenAPI Generator (https://openapi-generator.tech)
|
||||
|
||||
Do not edit the class manually.
|
||||
""" # noqa: E501
|
||||
|
||||
|
||||
from __future__ import annotations
|
||||
import pprint
|
||||
import re # noqa: F401
|
||||
import json
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictStr
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
|
||||
class HEULegalBasis(BaseModel):
|
||||
"""
|
||||
HEULegalBasis
|
||||
""" # noqa: E501
|
||||
id: Optional[StrictStr] = None
|
||||
legal_basis: Optional[StrictStr] = Field(default=None, alias="legalBasis")
|
||||
project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
|
||||
title: Optional[StrictStr] = None
|
||||
unique_programme_part: Optional[StrictStr] = Field(default=None, alias="uniqueProgrammePart")
|
||||
__properties: ClassVar[List[str]] = ["id", "legalBasis", "projectID", "title", "uniqueProgrammePart"]
|
||||
|
||||
model_config = ConfigDict(
|
||||
validate_by_name=True,
|
||||
validate_by_alias=True,
|
||||
validate_assignment=True,
|
||||
protected_namespaces=(),
|
||||
)
|
||||
|
||||
|
||||
def to_str(self) -> str:
|
||||
"""Returns the string representation of the model using alias"""
|
||||
return pprint.pformat(self.model_dump(by_alias=True))
|
||||
|
||||
def to_json(self) -> str:
|
||||
"""Returns the JSON representation of the model using alias"""
|
||||
return json.dumps(to_jsonable_python(self.to_dict()))
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, json_str: str) -> Optional[Self]:
|
||||
"""Create an instance of HEULegalBasis from a JSON string"""
|
||||
return cls.from_dict(json.loads(json_str))
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Return the dictionary representation of the model using alias.
|
||||
|
||||
This has the following differences from calling pydantic's
|
||||
`self.model_dump(by_alias=True)`:
|
||||
|
||||
* `None` is only added to the output dict for nullable fields that
|
||||
were set at model initialization. Other fields with value `None`
|
||||
are ignored.
|
||||
"""
|
||||
excluded_fields: Set[str] = set([
|
||||
])
|
||||
|
||||
_dict = self.model_dump(
|
||||
by_alias=True,
|
||||
exclude=excluded_fields,
|
||||
exclude_none=True,
|
||||
)
|
||||
return _dict
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
|
||||
"""Create an instance of HEULegalBasis from a dict"""
|
||||
if obj is None:
|
||||
return None
|
||||
|
||||
if not isinstance(obj, dict):
|
||||
return cls.model_validate(obj)
|
||||
|
||||
_obj = cls.model_validate({
|
||||
"id": obj.get("id"),
|
||||
"legalBasis": obj.get("legalBasis"),
|
||||
"projectID": obj.get("projectID"),
|
||||
"title": obj.get("title"),
|
||||
"uniqueProgrammePart": obj.get("uniqueProgrammePart")
|
||||
})
|
||||
return _obj
|
||||
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
CORDIS Horizon Europe Multi-Index API
|
||||
|
||||
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by OpenAPI Generator (https://openapi-generator.tech)
|
||||
|
||||
Do not edit the class manually.
|
||||
""" # noqa: E501
|
||||
|
||||
|
||||
from __future__ import annotations
|
||||
import pprint
|
||||
import re # noqa: F401
|
||||
import json
|
||||
|
||||
from datetime import datetime
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt, StrictStr
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
|
||||
class HEUOrganization(BaseModel):
|
||||
"""
|
||||
HEUOrganization
|
||||
""" # noqa: E501
|
||||
sme: Optional[StrictBool] = Field(default=None, alias="SME")
|
||||
active: Optional[StrictBool] = None
|
||||
activity_type: Optional[StrictStr] = Field(default=None, alias="activityType")
|
||||
city: Optional[StrictStr] = None
|
||||
contact_form: Optional[StrictStr] = Field(default=None, alias="contactForm")
|
||||
content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate")
|
||||
country: Optional[StrictStr] = None
|
||||
ec_contribution: Optional[StrictFloat] = Field(default=None, alias="ecContribution")
|
||||
end_of_participation: Optional[StrictBool] = Field(default=None, alias="endOfParticipation")
|
||||
geolocation: Optional[StrictStr] = None
|
||||
id: Optional[StrictStr] = None
|
||||
name: Optional[StrictStr] = None
|
||||
net_ec_contribution: Optional[StrictFloat] = Field(default=None, alias="netEcContribution")
|
||||
nuts_code: Optional[StrictStr] = Field(default=None, alias="nutsCode")
|
||||
order: Optional[StrictInt] = None
|
||||
organisation_id: Optional[StrictStr] = Field(default=None, alias="organisationID")
|
||||
organization_url: Optional[StrictStr] = Field(default=None, alias="organizationURL")
|
||||
post_code: Optional[StrictStr] = Field(default=None, alias="postCode")
|
||||
project_acronym: Optional[StrictStr] = Field(default=None, alias="projectAcronym")
|
||||
project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
|
||||
rcn: Optional[StrictStr] = None
|
||||
role: Optional[StrictStr] = None
|
||||
short_name: Optional[StrictStr] = Field(default=None, alias="shortName")
|
||||
street: Optional[StrictStr] = None
|
||||
total_cost: Optional[StrictFloat] = Field(default=None, alias="totalCost")
|
||||
vat_number: Optional[StrictStr] = Field(default=None, alias="vatNumber")
|
||||
__properties: ClassVar[List[str]] = ["SME", "active", "activityType", "city", "contactForm", "contentUpdateDate", "country", "ecContribution", "endOfParticipation", "geolocation", "id", "name", "netEcContribution", "nutsCode", "order", "organisationID", "organizationURL", "postCode", "projectAcronym", "projectID", "rcn", "role", "shortName", "street", "totalCost", "vatNumber"]
|
||||
|
||||
model_config = ConfigDict(
|
||||
validate_by_name=True,
|
||||
validate_by_alias=True,
|
||||
validate_assignment=True,
|
||||
protected_namespaces=(),
|
||||
)
|
||||
|
||||
|
||||
def to_str(self) -> str:
|
||||
"""Returns the string representation of the model using alias"""
|
||||
return pprint.pformat(self.model_dump(by_alias=True))
|
||||
|
||||
def to_json(self) -> str:
|
||||
"""Returns the JSON representation of the model using alias"""
|
||||
return json.dumps(to_jsonable_python(self.to_dict()))
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, json_str: str) -> Optional[Self]:
|
||||
"""Create an instance of HEUOrganization from a JSON string"""
|
||||
return cls.from_dict(json.loads(json_str))
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Return the dictionary representation of the model using alias.
|
||||
|
||||
This has the following differences from calling pydantic's
|
||||
`self.model_dump(by_alias=True)`:
|
||||
|
||||
* `None` is only added to the output dict for nullable fields that
|
||||
were set at model initialization. Other fields with value `None`
|
||||
are ignored.
|
||||
"""
|
||||
excluded_fields: Set[str] = set([
|
||||
])
|
||||
|
||||
_dict = self.model_dump(
|
||||
by_alias=True,
|
||||
exclude=excluded_fields,
|
||||
exclude_none=True,
|
||||
)
|
||||
return _dict
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
|
||||
"""Create an instance of HEUOrganization from a dict"""
|
||||
if obj is None:
|
||||
return None
|
||||
|
||||
if not isinstance(obj, dict):
|
||||
return cls.model_validate(obj)
|
||||
|
||||
_obj = cls.model_validate({
|
||||
"SME": obj.get("SME"),
|
||||
"active": obj.get("active"),
|
||||
"activityType": obj.get("activityType"),
|
||||
"city": obj.get("city"),
|
||||
"contactForm": obj.get("contactForm"),
|
||||
"contentUpdateDate": obj.get("contentUpdateDate"),
|
||||
"country": obj.get("country"),
|
||||
"ecContribution": obj.get("ecContribution"),
|
||||
"endOfParticipation": obj.get("endOfParticipation"),
|
||||
"geolocation": obj.get("geolocation"),
|
||||
"id": obj.get("id"),
|
||||
"name": obj.get("name"),
|
||||
"netEcContribution": obj.get("netEcContribution"),
|
||||
"nutsCode": obj.get("nutsCode"),
|
||||
"order": obj.get("order"),
|
||||
"organisationID": obj.get("organisationID"),
|
||||
"organizationURL": obj.get("organizationURL"),
|
||||
"postCode": obj.get("postCode"),
|
||||
"projectAcronym": obj.get("projectAcronym"),
|
||||
"projectID": obj.get("projectID"),
|
||||
"rcn": obj.get("rcn"),
|
||||
"role": obj.get("role"),
|
||||
"shortName": obj.get("shortName"),
|
||||
"street": obj.get("street"),
|
||||
"totalCost": obj.get("totalCost"),
|
||||
"vatNumber": obj.get("vatNumber")
|
||||
})
|
||||
return _obj
|
||||
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
CORDIS Horizon Europe Multi-Index API
|
||||
|
||||
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by OpenAPI Generator (https://openapi-generator.tech)
|
||||
|
||||
Do not edit the class manually.
|
||||
""" # noqa: E501
|
||||
|
||||
|
||||
from __future__ import annotations
|
||||
import pprint
|
||||
import re # noqa: F401
|
||||
import json
|
||||
|
||||
from datetime import date, datetime
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt, StrictStr
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
|
||||
class HEUProject(BaseModel):
|
||||
"""
|
||||
HEUProject
|
||||
""" # noqa: E501
|
||||
acronym: Optional[StrictStr] = None
|
||||
content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate")
|
||||
ec_max_contribution: Optional[StrictFloat] = Field(default=None, alias="ecMaxContribution")
|
||||
ec_signature_date: Optional[date] = Field(default=None, alias="ecSignatureDate")
|
||||
end_date: Optional[date] = Field(default=None, alias="endDate")
|
||||
framework_programme: Optional[StrictStr] = Field(default=None, alias="frameworkProgramme")
|
||||
funding_scheme: Optional[StrictStr] = Field(default=None, alias="fundingScheme")
|
||||
grant_doi: Optional[StrictStr] = Field(default=None, alias="grantDoi")
|
||||
human_validated: Optional[StrictBool] = Field(default=None, alias="humanValidated")
|
||||
id: Optional[StrictStr] = None
|
||||
keywords: Optional[StrictStr] = None
|
||||
legal_basis: Optional[StrictStr] = Field(default=None, alias="legalBasis")
|
||||
master_call: Optional[StrictStr] = Field(default=None, alias="masterCall")
|
||||
nature: Optional[StrictStr] = None
|
||||
objective: Optional[StrictStr] = None
|
||||
rcn: Optional[StrictStr] = None
|
||||
start_date: Optional[date] = Field(default=None, alias="startDate")
|
||||
status: Optional[StrictStr] = None
|
||||
sub_call: Optional[StrictStr] = Field(default=None, alias="subCall")
|
||||
title: Optional[StrictStr] = None
|
||||
topics: Optional[StrictStr] = None
|
||||
total_cost: Optional[StrictFloat] = Field(default=None, alias="totalCost")
|
||||
__properties: ClassVar[List[str]] = ["acronym", "contentUpdateDate", "ecMaxContribution", "ecSignatureDate", "endDate", "frameworkProgramme", "fundingScheme", "grantDoi", "humanValidated", "id", "keywords", "legalBasis", "masterCall", "nature", "objective", "rcn", "startDate", "status", "subCall", "title", "topics", "totalCost"]
|
||||
|
||||
model_config = ConfigDict(
|
||||
validate_by_name=True,
|
||||
validate_by_alias=True,
|
||||
validate_assignment=True,
|
||||
protected_namespaces=(),
|
||||
)
|
||||
|
||||
|
||||
def to_str(self) -> str:
|
||||
"""Returns the string representation of the model using alias"""
|
||||
return pprint.pformat(self.model_dump(by_alias=True))
|
||||
|
||||
def to_json(self) -> str:
|
||||
"""Returns the JSON representation of the model using alias"""
|
||||
return json.dumps(to_jsonable_python(self.to_dict()))
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, json_str: str) -> Optional[Self]:
|
||||
"""Create an instance of HEUProject from a JSON string"""
|
||||
return cls.from_dict(json.loads(json_str))
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Return the dictionary representation of the model using alias.
|
||||
|
||||
This has the following differences from calling pydantic's
|
||||
`self.model_dump(by_alias=True)`:
|
||||
|
||||
* `None` is only added to the output dict for nullable fields that
|
||||
were set at model initialization. Other fields with value `None`
|
||||
are ignored.
|
||||
"""
|
||||
excluded_fields: Set[str] = set([
|
||||
])
|
||||
|
||||
_dict = self.model_dump(
|
||||
by_alias=True,
|
||||
exclude=excluded_fields,
|
||||
exclude_none=True,
|
||||
)
|
||||
return _dict
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
|
||||
"""Create an instance of HEUProject from a dict"""
|
||||
if obj is None:
|
||||
return None
|
||||
|
||||
if not isinstance(obj, dict):
|
||||
return cls.model_validate(obj)
|
||||
|
||||
_obj = cls.model_validate({
|
||||
"acronym": obj.get("acronym"),
|
||||
"contentUpdateDate": obj.get("contentUpdateDate"),
|
||||
"ecMaxContribution": obj.get("ecMaxContribution"),
|
||||
"ecSignatureDate": obj.get("ecSignatureDate"),
|
||||
"endDate": obj.get("endDate"),
|
||||
"frameworkProgramme": obj.get("frameworkProgramme"),
|
||||
"fundingScheme": obj.get("fundingScheme"),
|
||||
"grantDoi": obj.get("grantDoi"),
|
||||
"humanValidated": obj.get("humanValidated"),
|
||||
"id": obj.get("id"),
|
||||
"keywords": obj.get("keywords"),
|
||||
"legalBasis": obj.get("legalBasis"),
|
||||
"masterCall": obj.get("masterCall"),
|
||||
"nature": obj.get("nature"),
|
||||
"objective": obj.get("objective"),
|
||||
"rcn": obj.get("rcn"),
|
||||
"startDate": obj.get("startDate"),
|
||||
"status": obj.get("status"),
|
||||
"subCall": obj.get("subCall"),
|
||||
"title": obj.get("title"),
|
||||
"topics": obj.get("topics"),
|
||||
"totalCost": obj.get("totalCost")
|
||||
})
|
||||
return _obj
|
||||
|
||||
|
||||
+214
@@ -0,0 +1,214 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
CORDIS Horizon Europe Multi-Index API - Extended Models
|
||||
""" # noqa: E501
|
||||
|
||||
from __future__ import annotations
|
||||
import pprint
|
||||
import re # noqa: F401
|
||||
import json
|
||||
from datetime import date, datetime
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt, StrictStr
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
|
||||
# Import all the base models
|
||||
from inse.models.projects_eu_cordis.horizon_europe.heu_project import HEUProject
|
||||
from inse.models.projects_eu_cordis.horizon_europe.heu_organization import HEUOrganization
|
||||
from inse.models.projects_eu_cordis.horizon_europe.heu_publication import HEUPublication
|
||||
from inse.models.projects_eu_cordis.horizon_europe.heu_deliverable import HEUDeliverable
|
||||
from inse.models.projects_eu_cordis.horizon_europe.heu_report_summary import HEUReportSummary
|
||||
from inse.models.projects_eu_cordis.horizon_europe.heu_topic import HEUTopic
|
||||
from inse.models.projects_eu_cordis.horizon_europe.heu_web_link import HEUWebLink
|
||||
from inse.models.projects_eu_cordis.horizon_europe.heu_eurosci_voc import HEUEurosciVoc
|
||||
from inse.models.projects_eu_cordis.horizon_europe.heu_legal_basis import HEULegalBasis
|
||||
|
||||
|
||||
class HEUProjectDetails(BaseModel):
|
||||
"""
|
||||
Comprehensive Horizon Europe Project model combining all related entities.
|
||||
This model extends the base HEUProject with all associated data.
|
||||
"""
|
||||
# Project core information (flattened from HEUProject)
|
||||
acronym: Optional[StrictStr] = None
|
||||
content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate")
|
||||
ec_max_contribution: Optional[StrictFloat] = Field(default=None, alias="ecMaxContribution")
|
||||
ec_signature_date: Optional[date] = Field(default=None, alias="ecSignatureDate")
|
||||
end_date: Optional[date] = Field(default=None, alias="endDate")
|
||||
framework_programme: Optional[StrictStr] = Field(default=None, alias="frameworkProgramme")
|
||||
funding_scheme: Optional[StrictStr] = Field(default=None, alias="fundingScheme")
|
||||
grant_doi: Optional[StrictStr] = Field(default=None, alias="grantDoi")
|
||||
human_validated: Optional[StrictBool] = Field(default=None, alias="humanValidated")
|
||||
id: Optional[StrictStr] = None
|
||||
keywords: Optional[StrictStr] = None
|
||||
legal_basis: Optional[StrictStr] = Field(default=None, alias="legalBasis")
|
||||
master_call: Optional[StrictStr] = Field(default=None, alias="masterCall")
|
||||
nature: Optional[StrictStr] = None
|
||||
objective: Optional[StrictStr] = None
|
||||
rcn: Optional[StrictStr] = None
|
||||
start_date: Optional[date] = Field(default=None, alias="startDate")
|
||||
status: Optional[StrictStr] = None
|
||||
sub_call: Optional[StrictStr] = Field(default=None, alias="subCall")
|
||||
title: Optional[StrictStr] = None
|
||||
topics: Optional[StrictStr] = None
|
||||
total_cost: Optional[StrictFloat] = Field(default=None, alias="totalCost")
|
||||
|
||||
# Related entities (collections)
|
||||
organizations: Optional[List[HEUOrganization]] = Field(default=None, description="Organizations participating in the project")
|
||||
publications: Optional[List[HEUPublication]] = Field(default=None, description="Publications related to the project")
|
||||
deliverables: Optional[List[HEUDeliverable]] = Field(default=None, description="Deliverables of the project")
|
||||
report_summaries: Optional[List[HEUReportSummary]] = Field(default=None, alias="reportSummaries", description="Report summaries for the project")
|
||||
topics_list: Optional[List[HEUTopic]] = Field(default=None, alias="topicsList", description="Topics associated with the project")
|
||||
web_links: Optional[List[HEUWebLink]] = Field(default=None, alias="webLinks", description="Web links related to the project")
|
||||
eurosci_voc: Optional[List[HEUEurosciVoc]] = Field(default=None, alias="eurosciVoc", description="EuroSciVoc classifications")
|
||||
legal_basis_list: Optional[List[HEULegalBasis]] = Field(default=None, alias="legalBasisList", description="Legal basis information")
|
||||
|
||||
# Project statistics (aggregated)
|
||||
organization_count: Optional[int] = Field(default=None, alias="organizationCount")
|
||||
publication_count: Optional[int] = Field(default=None, alias="publicationCount")
|
||||
deliverable_count: Optional[int] = Field(default=None, alias="deliverableCount")
|
||||
|
||||
__properties: ClassVar[List[str]] = [
|
||||
"acronym", "contentUpdateDate", "ecMaxContribution", "ecSignatureDate",
|
||||
"endDate", "frameworkProgramme", "fundingScheme", "grantDoi",
|
||||
"humanValidated", "id", "keywords", "legalBasis", "masterCall",
|
||||
"nature", "objective", "rcn", "startDate", "status", "subCall",
|
||||
"title", "topics", "totalCost",
|
||||
"organizations", "publications", "deliverables", "reportSummaries",
|
||||
"topicsList", "webLinks", "eurosciVoc", "legalBasisList",
|
||||
"organizationCount", "publicationCount", "deliverableCount"
|
||||
]
|
||||
|
||||
model_config = ConfigDict(
|
||||
validate_by_name=True,
|
||||
validate_by_alias=True,
|
||||
validate_assignment=True,
|
||||
protected_namespaces=(),
|
||||
populate_by_name=True,
|
||||
)
|
||||
|
||||
def to_str(self) -> str:
|
||||
"""Returns the string representation of the model using alias"""
|
||||
return pprint.pformat(self.model_dump(by_alias=True))
|
||||
|
||||
def to_json(self) -> str:
|
||||
"""Returns the JSON representation of the model using alias"""
|
||||
return json.dumps(to_jsonable_python(self.to_dict()))
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, json_str: str) -> Optional[Self]:
|
||||
"""Create an instance of HEUProjectDetailed from a JSON string"""
|
||||
return cls.from_dict(json.loads(json_str))
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Return the dictionary representation of the model using alias."""
|
||||
excluded_fields: Set[str] = set([
|
||||
])
|
||||
|
||||
_dict = self.model_dump(
|
||||
by_alias=True,
|
||||
exclude=excluded_fields,
|
||||
exclude_none=True,
|
||||
)
|
||||
return _dict
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
|
||||
"""Create an instance of HEUProjectDetailed from a dict"""
|
||||
if obj is None:
|
||||
return None
|
||||
|
||||
if not isinstance(obj, dict):
|
||||
return cls.model_validate(obj)
|
||||
|
||||
_obj = cls.model_validate({
|
||||
# Project core fields
|
||||
"acronym": obj.get("acronym"),
|
||||
"contentUpdateDate": obj.get("contentUpdateDate"),
|
||||
"ecMaxContribution": obj.get("ecMaxContribution"),
|
||||
"ecSignatureDate": obj.get("ecSignatureDate"),
|
||||
"endDate": obj.get("endDate"),
|
||||
"frameworkProgramme": obj.get("frameworkProgramme"),
|
||||
"fundingScheme": obj.get("fundingScheme"),
|
||||
"grantDoi": obj.get("grantDoi"),
|
||||
"humanValidated": obj.get("humanValidated"),
|
||||
"id": obj.get("id"),
|
||||
"keywords": obj.get("keywords"),
|
||||
"legalBasis": obj.get("legalBasis"),
|
||||
"masterCall": obj.get("masterCall"),
|
||||
"nature": obj.get("nature"),
|
||||
"objective": obj.get("objective"),
|
||||
"rcn": obj.get("rcn"),
|
||||
"startDate": obj.get("startDate"),
|
||||
"status": obj.get("status"),
|
||||
"subCall": obj.get("subCall"),
|
||||
"title": obj.get("title"),
|
||||
"topics": obj.get("topics"),
|
||||
"totalCost": obj.get("totalCost"),
|
||||
|
||||
# Related entities
|
||||
"organizations": [HEUOrganization.from_dict(org) for org in obj.get("organizations", [])] if obj.get("organizations") else None,
|
||||
"publications": [HEUPublication.from_dict(pub) for pub in obj.get("publications", [])] if obj.get("publications") else None,
|
||||
"deliverables": [HEUDeliverable.from_dict(deliv) for deliv in obj.get("deliverables", [])] if obj.get("deliverables") else None,
|
||||
"reportSummaries": [HEUReportSummary.from_dict(report) for report in obj.get("reportSummaries", [])] if obj.get("reportSummaries") else None,
|
||||
"topicsList": [HEUTopic.from_dict(topic) for topic in obj.get("topicsList", [])] if obj.get("topicsList") else None,
|
||||
"webLinks": [HEUWebLink.from_dict(link) for link in obj.get("webLinks", [])] if obj.get("webLinks") else None,
|
||||
"eurosciVoc": [HEUEurosciVoc.from_dict(voc) for voc in obj.get("eurosciVoc", [])] if obj.get("eurosciVoc") else None,
|
||||
"legalBasisList": [HEULegalBasis.from_dict(lb) for lb in obj.get("legalBasisList", [])] if obj.get("legalBasisList") else None,
|
||||
|
||||
# Statistics
|
||||
"organizationCount": len(obj.get("organizations", [])) if obj.get("organizations") else 0,
|
||||
"publicationCount": len(obj.get("publications", [])) if obj.get("publications") else 0,
|
||||
"deliverableCount": len(obj.get("deliverables", [])) if obj.get("deliverables") else 0,
|
||||
})
|
||||
return _obj
|
||||
|
||||
@classmethod
|
||||
def from_project_with_relations(
|
||||
cls,
|
||||
project: HEUProject,
|
||||
organizations: Optional[List[HEUOrganization]] = None,
|
||||
publications: Optional[List[HEUPublication]] = None,
|
||||
deliverables: Optional[List[HEUDeliverable]] = None,
|
||||
report_summaries: Optional[List[HEUReportSummary]] = None,
|
||||
topics_list: Optional[List[HEUTopic]] = None,
|
||||
web_links: Optional[List[HEUWebLink]] = None,
|
||||
eurosci_voc: Optional[List[HEUEurosciVoc]] = None,
|
||||
legal_basis_list: Optional[List[HEULegalBasis]] = None,
|
||||
) -> Self:
|
||||
"""
|
||||
Factory method to create a detailed project from a base project and its relations.
|
||||
|
||||
Args:
|
||||
project: The base HEUProject object
|
||||
organizations: List of organizations participating in the project
|
||||
publications: List of publications related to the project
|
||||
deliverables: List of deliverables of the project
|
||||
report_summaries: List of report summaries
|
||||
topics_list: List of topics associated with the project
|
||||
web_links: List of web links
|
||||
eurosci_voc: List of EuroSciVoc classifications
|
||||
legal_basis_list: List of legal basis information
|
||||
|
||||
Returns:
|
||||
HEUProjectDetailed instance
|
||||
"""
|
||||
project_dict = project.to_dict() if project else {}
|
||||
|
||||
return cls(
|
||||
**project_dict,
|
||||
organizations=organizations or [],
|
||||
publications=publications or [],
|
||||
deliverables=deliverables or [],
|
||||
reportSummaries=report_summaries or [],
|
||||
topicsList=topics_list or [],
|
||||
webLinks=web_links or [],
|
||||
eurosciVoc=eurosci_voc or [],
|
||||
legalBasisList=legal_basis_list or [],
|
||||
organizationCount=len(organizations) if organizations else 0,
|
||||
publicationCount=len(publications) if publications else 0,
|
||||
deliverableCount=len(deliverables) if deliverables else 0,
|
||||
)
|
||||
@@ -0,0 +1,123 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
CORDIS Horizon Europe Multi-Index API
|
||||
|
||||
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by OpenAPI Generator (https://openapi-generator.tech)
|
||||
|
||||
Do not edit the class manually.
|
||||
""" # noqa: E501
|
||||
|
||||
|
||||
from __future__ import annotations
|
||||
import pprint
|
||||
import re # noqa: F401
|
||||
import json
|
||||
|
||||
from datetime import datetime
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
|
||||
class HEUPublication(BaseModel):
|
||||
"""
|
||||
HEUPublication
|
||||
""" # noqa: E501
|
||||
authors: Optional[StrictStr] = None
|
||||
collection: Optional[StrictStr] = None
|
||||
content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate")
|
||||
doi: Optional[StrictStr] = None
|
||||
id: Optional[StrictStr] = None
|
||||
is_published_as: Optional[StrictStr] = Field(default=None, alias="isPublishedAs")
|
||||
journal_number: Optional[StrictStr] = Field(default=None, alias="journalNumber")
|
||||
journal_title: Optional[StrictStr] = Field(default=None, alias="journalTitle")
|
||||
project_acronym: Optional[StrictStr] = Field(default=None, alias="projectAcronym")
|
||||
project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
|
||||
published_pages: Optional[StrictStr] = Field(default=None, alias="publishedPages")
|
||||
published_year: Optional[StrictInt] = Field(default=None, alias="publishedYear")
|
||||
publisher: Optional[StrictStr] = None
|
||||
qa_processed_doi: Optional[StrictStr] = Field(default=None, alias="qaProcessedDoi")
|
||||
rcn: Optional[StrictStr] = None
|
||||
repository_url: Optional[StrictStr] = Field(default=None, alias="repositoryUrl")
|
||||
title: Optional[StrictStr] = None
|
||||
volume: Optional[StrictStr] = None
|
||||
__properties: ClassVar[List[str]] = ["authors", "collection", "contentUpdateDate", "doi", "id", "isPublishedAs", "journalNumber", "journalTitle", "projectAcronym", "projectID", "publishedPages", "publishedYear", "publisher", "qaProcessedDoi", "rcn", "repositoryUrl", "title", "volume"]
|
||||
|
||||
model_config = ConfigDict(
|
||||
validate_by_name=True,
|
||||
validate_by_alias=True,
|
||||
validate_assignment=True,
|
||||
protected_namespaces=(),
|
||||
)
|
||||
|
||||
|
||||
def to_str(self) -> str:
|
||||
"""Returns the string representation of the model using alias"""
|
||||
return pprint.pformat(self.model_dump(by_alias=True))
|
||||
|
||||
def to_json(self) -> str:
|
||||
"""Returns the JSON representation of the model using alias"""
|
||||
return json.dumps(to_jsonable_python(self.to_dict()))
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, json_str: str) -> Optional[Self]:
|
||||
"""Create an instance of HEUPublication from a JSON string"""
|
||||
return cls.from_dict(json.loads(json_str))
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Return the dictionary representation of the model using alias.
|
||||
|
||||
This has the following differences from calling pydantic's
|
||||
`self.model_dump(by_alias=True)`:
|
||||
|
||||
* `None` is only added to the output dict for nullable fields that
|
||||
were set at model initialization. Other fields with value `None`
|
||||
are ignored.
|
||||
"""
|
||||
excluded_fields: Set[str] = set([
|
||||
])
|
||||
|
||||
_dict = self.model_dump(
|
||||
by_alias=True,
|
||||
exclude=excluded_fields,
|
||||
exclude_none=True,
|
||||
)
|
||||
return _dict
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
|
||||
"""Create an instance of HEUPublication from a dict"""
|
||||
if obj is None:
|
||||
return None
|
||||
|
||||
if not isinstance(obj, dict):
|
||||
return cls.model_validate(obj)
|
||||
|
||||
_obj = cls.model_validate({
|
||||
"authors": obj.get("authors"),
|
||||
"collection": obj.get("collection"),
|
||||
"contentUpdateDate": obj.get("contentUpdateDate"),
|
||||
"doi": obj.get("doi"),
|
||||
"id": obj.get("id"),
|
||||
"isPublishedAs": obj.get("isPublishedAs"),
|
||||
"journalNumber": obj.get("journalNumber"),
|
||||
"journalTitle": obj.get("journalTitle"),
|
||||
"projectAcronym": obj.get("projectAcronym"),
|
||||
"projectID": obj.get("projectID"),
|
||||
"publishedPages": obj.get("publishedPages"),
|
||||
"publishedYear": obj.get("publishedYear"),
|
||||
"publisher": obj.get("publisher"),
|
||||
"qaProcessedDoi": obj.get("qaProcessedDoi"),
|
||||
"rcn": obj.get("rcn"),
|
||||
"repositoryUrl": obj.get("repositoryUrl"),
|
||||
"title": obj.get("title"),
|
||||
"volume": obj.get("volume")
|
||||
})
|
||||
return _obj
|
||||
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
CORDIS Horizon Europe Multi-Index API
|
||||
|
||||
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by OpenAPI Generator (https://openapi-generator.tech)
|
||||
|
||||
Do not edit the class manually.
|
||||
""" # noqa: E501
|
||||
|
||||
|
||||
from __future__ import annotations
|
||||
import pprint
|
||||
import re # noqa: F401
|
||||
import json
|
||||
|
||||
from datetime import datetime
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictStr
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
|
||||
class HEUReportSummary(BaseModel):
|
||||
"""
|
||||
HEUReportSummary
|
||||
""" # noqa: E501
|
||||
attachments: Optional[StrictStr] = None
|
||||
content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate")
|
||||
id: Optional[StrictStr] = None
|
||||
project_acronym: Optional[StrictStr] = Field(default=None, alias="projectAcronym")
|
||||
project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
|
||||
rcn: Optional[StrictStr] = None
|
||||
title: Optional[StrictStr] = None
|
||||
__properties: ClassVar[List[str]] = ["attachments", "contentUpdateDate", "id", "projectAcronym", "projectID", "rcn", "title"]
|
||||
|
||||
model_config = ConfigDict(
|
||||
validate_by_name=True,
|
||||
validate_by_alias=True,
|
||||
validate_assignment=True,
|
||||
protected_namespaces=(),
|
||||
)
|
||||
|
||||
|
||||
def to_str(self) -> str:
|
||||
"""Returns the string representation of the model using alias"""
|
||||
return pprint.pformat(self.model_dump(by_alias=True))
|
||||
|
||||
def to_json(self) -> str:
|
||||
"""Returns the JSON representation of the model using alias"""
|
||||
return json.dumps(to_jsonable_python(self.to_dict()))
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, json_str: str) -> Optional[Self]:
|
||||
"""Create an instance of HEUReportSummary from a JSON string"""
|
||||
return cls.from_dict(json.loads(json_str))
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Return the dictionary representation of the model using alias.
|
||||
|
||||
This has the following differences from calling pydantic's
|
||||
`self.model_dump(by_alias=True)`:
|
||||
|
||||
* `None` is only added to the output dict for nullable fields that
|
||||
were set at model initialization. Other fields with value `None`
|
||||
are ignored.
|
||||
"""
|
||||
excluded_fields: Set[str] = set([
|
||||
])
|
||||
|
||||
_dict = self.model_dump(
|
||||
by_alias=True,
|
||||
exclude=excluded_fields,
|
||||
exclude_none=True,
|
||||
)
|
||||
return _dict
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
|
||||
"""Create an instance of HEUReportSummary from a dict"""
|
||||
if obj is None:
|
||||
return None
|
||||
|
||||
if not isinstance(obj, dict):
|
||||
return cls.model_validate(obj)
|
||||
|
||||
_obj = cls.model_validate({
|
||||
"attachments": obj.get("attachments"),
|
||||
"contentUpdateDate": obj.get("contentUpdateDate"),
|
||||
"id": obj.get("id"),
|
||||
"projectAcronym": obj.get("projectAcronym"),
|
||||
"projectID": obj.get("projectID"),
|
||||
"rcn": obj.get("rcn"),
|
||||
"title": obj.get("title")
|
||||
})
|
||||
return _obj
|
||||
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
CORDIS Horizon Europe Multi-Index API
|
||||
|
||||
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by OpenAPI Generator (https://openapi-generator.tech)
|
||||
|
||||
Do not edit the class manually.
|
||||
""" # noqa: E501
|
||||
|
||||
|
||||
from __future__ import annotations
|
||||
import pprint
|
||||
import re # noqa: F401
|
||||
import json
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictStr
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
|
||||
class HEUTopic(BaseModel):
|
||||
"""
|
||||
HEUTopic
|
||||
""" # noqa: E501
|
||||
id: Optional[StrictStr] = None
|
||||
project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
|
||||
title: Optional[StrictStr] = None
|
||||
topic: Optional[StrictStr] = None
|
||||
__properties: ClassVar[List[str]] = ["id", "projectID", "title", "topic"]
|
||||
|
||||
model_config = ConfigDict(
|
||||
validate_by_name=True,
|
||||
validate_by_alias=True,
|
||||
validate_assignment=True,
|
||||
protected_namespaces=(),
|
||||
)
|
||||
|
||||
|
||||
def to_str(self) -> str:
|
||||
"""Returns the string representation of the model using alias"""
|
||||
return pprint.pformat(self.model_dump(by_alias=True))
|
||||
|
||||
def to_json(self) -> str:
|
||||
"""Returns the JSON representation of the model using alias"""
|
||||
return json.dumps(to_jsonable_python(self.to_dict()))
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, json_str: str) -> Optional[Self]:
|
||||
"""Create an instance of HEUTopic from a JSON string"""
|
||||
return cls.from_dict(json.loads(json_str))
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Return the dictionary representation of the model using alias.
|
||||
|
||||
This has the following differences from calling pydantic's
|
||||
`self.model_dump(by_alias=True)`:
|
||||
|
||||
* `None` is only added to the output dict for nullable fields that
|
||||
were set at model initialization. Other fields with value `None`
|
||||
are ignored.
|
||||
"""
|
||||
excluded_fields: Set[str] = set([
|
||||
])
|
||||
|
||||
_dict = self.model_dump(
|
||||
by_alias=True,
|
||||
exclude=excluded_fields,
|
||||
exclude_none=True,
|
||||
)
|
||||
return _dict
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
|
||||
"""Create an instance of HEUTopic from a dict"""
|
||||
if obj is None:
|
||||
return None
|
||||
|
||||
if not isinstance(obj, dict):
|
||||
return cls.model_validate(obj)
|
||||
|
||||
_obj = cls.model_validate({
|
||||
"id": obj.get("id"),
|
||||
"projectID": obj.get("projectID"),
|
||||
"title": obj.get("title"),
|
||||
"topic": obj.get("topic")
|
||||
})
|
||||
return _obj
|
||||
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
CORDIS Horizon Europe Multi-Index API
|
||||
|
||||
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by OpenAPI Generator (https://openapi-generator.tech)
|
||||
|
||||
Do not edit the class manually.
|
||||
""" # noqa: E501
|
||||
|
||||
|
||||
from __future__ import annotations
|
||||
import pprint
|
||||
import re # noqa: F401
|
||||
import json
|
||||
|
||||
from datetime import datetime
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictStr
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
|
||||
class HEUWebLink(BaseModel):
|
||||
"""
|
||||
HEUWebLink
|
||||
""" # noqa: E501
|
||||
archived_date: Optional[datetime] = Field(default=None, alias="archivedDate")
|
||||
available_languages: Optional[StrictStr] = Field(default=None, alias="availableLanguages")
|
||||
id: Optional[StrictStr] = None
|
||||
link_id: Optional[StrictStr] = Field(default=None, alias="linkId")
|
||||
project_id: Optional[StrictStr] = Field(default=None, alias="projectID")
|
||||
represents: Optional[StrictStr] = None
|
||||
source: Optional[StrictStr] = None
|
||||
status: Optional[StrictStr] = None
|
||||
type: Optional[StrictStr] = None
|
||||
url: Optional[StrictStr] = None
|
||||
__properties: ClassVar[List[str]] = ["archivedDate", "availableLanguages", "id", "linkId", "projectID", "represents", "source", "status", "type", "url"]
|
||||
|
||||
model_config = ConfigDict(
|
||||
validate_by_name=True,
|
||||
validate_by_alias=True,
|
||||
validate_assignment=True,
|
||||
protected_namespaces=(),
|
||||
)
|
||||
|
||||
|
||||
def to_str(self) -> str:
|
||||
"""Returns the string representation of the model using alias"""
|
||||
return pprint.pformat(self.model_dump(by_alias=True))
|
||||
|
||||
def to_json(self) -> str:
|
||||
"""Returns the JSON representation of the model using alias"""
|
||||
return json.dumps(to_jsonable_python(self.to_dict()))
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, json_str: str) -> Optional[Self]:
|
||||
"""Create an instance of HEUWebLink from a JSON string"""
|
||||
return cls.from_dict(json.loads(json_str))
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Return the dictionary representation of the model using alias.
|
||||
|
||||
This has the following differences from calling pydantic's
|
||||
`self.model_dump(by_alias=True)`:
|
||||
|
||||
* `None` is only added to the output dict for nullable fields that
|
||||
were set at model initialization. Other fields with value `None`
|
||||
are ignored.
|
||||
"""
|
||||
excluded_fields: Set[str] = set([
|
||||
])
|
||||
|
||||
_dict = self.model_dump(
|
||||
by_alias=True,
|
||||
exclude=excluded_fields,
|
||||
exclude_none=True,
|
||||
)
|
||||
return _dict
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
|
||||
"""Create an instance of HEUWebLink from a dict"""
|
||||
if obj is None:
|
||||
return None
|
||||
|
||||
if not isinstance(obj, dict):
|
||||
return cls.model_validate(obj)
|
||||
|
||||
_obj = cls.model_validate({
|
||||
"archivedDate": obj.get("archivedDate"),
|
||||
"availableLanguages": obj.get("availableLanguages"),
|
||||
"id": obj.get("id"),
|
||||
"linkId": obj.get("linkId"),
|
||||
"projectID": obj.get("projectID"),
|
||||
"represents": obj.get("represents"),
|
||||
"source": obj.get("source"),
|
||||
"status": obj.get("status"),
|
||||
"type": obj.get("type"),
|
||||
"url": obj.get("url")
|
||||
})
|
||||
return _obj
|
||||
|
||||
|
||||
@@ -4,33 +4,69 @@
|
||||
Business logic for the "aktuell" news index on the INSE cluster.
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
|
||||
from fastapi import HTTPException
|
||||
from starlette.status import HTTP_500_INTERNAL_SERVER_ERROR
|
||||
from inse.exceptions import ElasticsearchException
|
||||
|
||||
from ..integrations import elasticsearch
|
||||
from ..integrations import elasticsearch, llm
|
||||
from ..persons.logic import find_ude_author_by_name, get_author_name_by_id
|
||||
from .model import MentionedPerson, NewsArticle, NewsArticleDetail, NewsPage
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
TOPIC_LIMIT = 4
|
||||
TOPIC_QUERY_CONTENT_CHARS = 300
|
||||
TOPIC_NUM_CANDIDATES = 100
|
||||
TOPIC_SIMILARITY = 0.5
|
||||
|
||||
def get_news_page(page: int, page_size: int, sort_order: str = "desc") -> NewsPage:
|
||||
KEYWORD_LIMIT = 6
|
||||
KEYWORD_CONTENT_CHARS = 4000
|
||||
KEYWORD_SYSTEM_PROMPT = """\
|
||||
Extrahiere aus dem folgenden Nachrichtenartikel die wichtigsten Schlagwörter (Keywords).
|
||||
Gib maximal sechs prägnante Begriffe oder kurze Phrasen zurück, die den inhaltlichen Kern
|
||||
des Artikels erfassen. Antworte ausschließlich mit einem JSON-Array von Strings, ohne
|
||||
weiteren Text, zum Beispiel ["Künstliche Intelligenz", "Klimaforschung"].
|
||||
"""
|
||||
|
||||
RELATED_BLOCK_SIZE = 5
|
||||
RELATED_TOPIC_K = 1
|
||||
EXACT_ID_CAP = 1000
|
||||
|
||||
|
||||
async def get_news_page(
|
||||
page: int,
|
||||
page_size: int,
|
||||
sort_order: str = "desc",
|
||||
year_from: int | None = None,
|
||||
year_to: int | None = None,
|
||||
relevance_values: list | None = None,
|
||||
) -> NewsPage:
|
||||
offset = (page - 1) * page_size
|
||||
|
||||
response = _run_search(
|
||||
query={"match_all": {}},
|
||||
source=["date", "maintitle", "author", "url"],
|
||||
clauses = await _filter_clauses(year_from, year_to, relevance_values)
|
||||
query = {"bool": {"filter": clauses}} if clauses else {"match_all": {}}
|
||||
|
||||
response = await _run_search(
|
||||
query=query,
|
||||
source=["date", "maintitle", "author", "url", "intro_content", "full_content"],
|
||||
size=page_size,
|
||||
offset=offset,
|
||||
sort=[{"date_full": sort_order}],
|
||||
)
|
||||
|
||||
return _build_page(response, page, page_size)
|
||||
return await _build_page(response, page, page_size)
|
||||
|
||||
|
||||
def search_news(query_text: str, page: int, page_size: int) -> NewsPage:
|
||||
async def search_news(
|
||||
query_text: str,
|
||||
page: int,
|
||||
page_size: int,
|
||||
year_from: int | None = None,
|
||||
year_to: int | None = None,
|
||||
relevance_values: list | None = None,
|
||||
) -> NewsPage:
|
||||
offset = (page - 1) * page_size
|
||||
|
||||
highlight = {
|
||||
@@ -40,8 +76,16 @@ def search_news(query_text: str, page: int, page_size: int) -> NewsPage:
|
||||
"encoder": "html",
|
||||
}
|
||||
|
||||
response = _run_search(
|
||||
query={"match": {"full_content": query_text}},
|
||||
# Filter einmal berechnen (der Relevanz-Filter macht eine ES-Abfrage).
|
||||
clauses = await _filter_clauses(year_from, year_to, relevance_values)
|
||||
exact_query = {
|
||||
"bool": {
|
||||
"must": [{"match": {"full_content": query_text}}],
|
||||
"filter": clauses,
|
||||
}
|
||||
}
|
||||
response = await _run_search(
|
||||
query=exact_query,
|
||||
source=["date", "maintitle", "author", "url"],
|
||||
size=page_size,
|
||||
offset=offset,
|
||||
@@ -49,9 +93,20 @@ def search_news(query_text: str, page: int, page_size: int) -> NewsPage:
|
||||
highlight=highlight,
|
||||
)
|
||||
|
||||
return _build_page(response, page, page_size)
|
||||
news_page = await _build_page(response, page, page_size)
|
||||
|
||||
def get_news_by_author(
|
||||
if _is_last_page(page, page_size, news_page.total):
|
||||
exclude_ids = await _exact_match_ids(exact_query)
|
||||
news_page.results.extend(
|
||||
await _related_articles(
|
||||
query_text, exclude_ids=exclude_ids, extra_filters=clauses
|
||||
)
|
||||
)
|
||||
|
||||
return news_page
|
||||
|
||||
|
||||
async def get_news_by_author(
|
||||
author_id: str,
|
||||
page: int = 1,
|
||||
page_size: int = 10,
|
||||
@@ -59,11 +114,11 @@ def get_news_by_author(
|
||||
query_text: str | None = None,
|
||||
) -> NewsPage:
|
||||
|
||||
author_name = get_author_name_by_id(author_id)
|
||||
author_name = await get_author_name_by_id(author_id)
|
||||
if not author_name:
|
||||
return _empty_page(page, page_size)
|
||||
|
||||
news_ids = _find_news_ids_for_author(author_name)
|
||||
news_ids = await _find_news_ids_for_author(author_name)
|
||||
if not news_ids:
|
||||
return _empty_page(page, page_size)
|
||||
|
||||
@@ -74,7 +129,7 @@ def get_news_by_author(
|
||||
]
|
||||
|
||||
offset = (page - 1) * page_size
|
||||
response = _run_search(
|
||||
response = await _run_search(
|
||||
query=es_query,
|
||||
source=["date", "maintitle", "author", "url"],
|
||||
size=page_size,
|
||||
@@ -82,13 +137,71 @@ def get_news_by_author(
|
||||
sort=[{"date_full": sort_order}],
|
||||
)
|
||||
|
||||
return _build_page(response, page, page_size)
|
||||
news_page = await _build_page(response, page, page_size)
|
||||
|
||||
if query_text and _is_last_page(page, page_size, news_page.total):
|
||||
exclude_ids = await _exact_match_ids(es_query)
|
||||
news_page.results.extend(
|
||||
await _related_articles(
|
||||
query_text, exclude_ids=exclude_ids, filter_news_ids=news_ids
|
||||
)
|
||||
)
|
||||
|
||||
return news_page
|
||||
|
||||
|
||||
def _find_news_ids_for_author(author_name: str) -> list:
|
||||
async def _filter_clauses(
|
||||
year_from: int | None,
|
||||
year_to: int | None,
|
||||
relevance_values: list | None,
|
||||
) -> list:
|
||||
clauses = []
|
||||
|
||||
if year_from is not None or year_to is not None:
|
||||
date_range = {}
|
||||
if year_from is not None:
|
||||
date_range["gte"] = year_from
|
||||
if year_to is not None:
|
||||
date_range["lte"] = year_to
|
||||
clauses.append({"range": {"date_year": date_range}})
|
||||
|
||||
relevant_ids = await _relevance_news_ids(relevance_values)
|
||||
if relevant_ids is not None:
|
||||
clauses.append({"ids": {"values": relevant_ids}})
|
||||
|
||||
return clauses
|
||||
|
||||
|
||||
async def _relevance_news_ids(relevance_values: list | None) -> list | None:
|
||||
selected = set(relevance_values or [])
|
||||
|
||||
if not selected or {"relevant", "not_relevant"} <= selected:
|
||||
return None
|
||||
|
||||
relevant_value = 1 if "relevant" in selected else 0
|
||||
|
||||
news_ids = []
|
||||
try:
|
||||
async for hit in elasticsearch.scan(
|
||||
index="aktuell_postproc",
|
||||
query={"term": {"relevant": relevant_value}},
|
||||
source=["news_id"],
|
||||
cluster="inse",
|
||||
):
|
||||
news_id = hit.get("_source", {}).get("news_id")
|
||||
if news_id:
|
||||
news_ids.append(news_id)
|
||||
except Exception:
|
||||
logger.exception("Relevanz-IDs aus aktuell_postproc konnten nicht geladen werden.")
|
||||
return []
|
||||
|
||||
return news_ids
|
||||
|
||||
|
||||
async def _find_news_ids_for_author(author_name: str) -> list:
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index="aktuell_postproc",
|
||||
query={"term": {"authors.keyword": author_name}},
|
||||
source=["news_id"],
|
||||
@@ -112,24 +225,29 @@ def _empty_page(page: int = 1, page_size: int = 0) -> NewsPage:
|
||||
return NewsPage(total=0, page=page, page_size=page_size, results=[])
|
||||
|
||||
|
||||
def get_news_by_id(news_id: str) -> NewsArticleDetail:
|
||||
async def get_news_by_id(news_id: str) -> NewsArticleDetail:
|
||||
try:
|
||||
response = elasticsearch.get(
|
||||
response = await elasticsearch.get(
|
||||
index="aktuell",
|
||||
doc_id=news_id,
|
||||
source=["date", "maintitle", "author", "url", "full_content"],
|
||||
cluster="inse",
|
||||
)
|
||||
except Exception as exc:
|
||||
except ElasticsearchException as exc:
|
||||
logger.exception("Abruf des News-Artikels fehlgeschlagen.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail="Etwas ist schiefgelaufen.",
|
||||
) from exc
|
||||
raise
|
||||
|
||||
source = response.get("_source", {})
|
||||
|
||||
relevant, authors = _get_postproc_labels(news_id)
|
||||
relevant, authors, cached_keywords, postproc_id = await _get_postproc_labels(news_id)
|
||||
topics = await _get_article_topics(source.get("maintitle"), source.get("full_content"))
|
||||
keywords = await _get_article_keywords(
|
||||
news_id,
|
||||
postproc_id,
|
||||
cached_keywords,
|
||||
source.get("maintitle"),
|
||||
source.get("full_content"),
|
||||
)
|
||||
|
||||
return NewsArticleDetail(
|
||||
id=response.get("_id"),
|
||||
@@ -139,17 +257,131 @@ def get_news_by_id(news_id: str) -> NewsArticleDetail:
|
||||
url=source.get("url"),
|
||||
full_content=source.get("full_content"),
|
||||
relevant=relevant,
|
||||
authors=_build_mentioned_persons(authors),
|
||||
authors=await _build_mentioned_persons(authors),
|
||||
topics=topics,
|
||||
keywords=keywords,
|
||||
)
|
||||
|
||||
|
||||
def _build_mentioned_persons(author_names: list) -> list:
|
||||
async def _get_article_topics(maintitle: str | None, full_content: str | None) -> list:
|
||||
query = " ".join(
|
||||
part for part in (maintitle, (full_content or "")[:TOPIC_QUERY_CONTENT_CHARS]) if part
|
||||
).strip()
|
||||
if not query:
|
||||
return []
|
||||
|
||||
topics = await _topic_vector_search(query, TOPIC_LIMIT, ["display_name"])
|
||||
return [topic["display_name"] for topic in topics if topic.get("display_name")]
|
||||
|
||||
|
||||
async def _get_article_keywords(
|
||||
news_id: str,
|
||||
postproc_id: str | None,
|
||||
cached_keywords: list,
|
||||
maintitle: str | None,
|
||||
full_content: str | None,
|
||||
) -> list:
|
||||
if cached_keywords:
|
||||
return cached_keywords
|
||||
|
||||
text = " ".join(
|
||||
part for part in (maintitle, (full_content or "")[:KEYWORD_CONTENT_CHARS]) if part
|
||||
).strip()
|
||||
if not text:
|
||||
return []
|
||||
|
||||
raw = llm.call(
|
||||
system_prompt=KEYWORD_SYSTEM_PROMPT,
|
||||
user_prompt=f"Artikel:\n{text}",
|
||||
temperature=0.3,
|
||||
)
|
||||
keywords = _parse_keywords(raw)
|
||||
|
||||
if keywords:
|
||||
await _store_keywords(news_id, postproc_id, keywords)
|
||||
|
||||
return keywords
|
||||
|
||||
|
||||
def _parse_keywords(raw: str) -> list:
|
||||
raw = (raw or "").strip()
|
||||
|
||||
try:
|
||||
parsed = json.loads(raw)
|
||||
candidates = parsed if isinstance(parsed, list) else []
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
candidates = re.split(r"[,\n]", raw)
|
||||
|
||||
seen = set()
|
||||
keywords = []
|
||||
for item in candidates:
|
||||
term = str(item).strip().strip('"').strip()
|
||||
if term and term.lower() not in seen:
|
||||
seen.add(term.lower())
|
||||
keywords.append(term)
|
||||
|
||||
return keywords[:KEYWORD_LIMIT]
|
||||
|
||||
|
||||
async def _store_keywords(news_id: str, postproc_id: str | None, keywords: list) -> None:
|
||||
try:
|
||||
if postproc_id:
|
||||
await elasticsearch.update(
|
||||
index="aktuell_postproc",
|
||||
doc_id=postproc_id,
|
||||
doc={"keywords": keywords},
|
||||
cluster="inse",
|
||||
)
|
||||
else:
|
||||
await elasticsearch.index_doc(
|
||||
index="aktuell_postproc",
|
||||
doc_id=news_id,
|
||||
document={"news_id": news_id, "keywords": keywords},
|
||||
cluster="inse",
|
||||
)
|
||||
except Exception:
|
||||
logger.exception(f"Failed to cache keywords for {news_id}.")
|
||||
|
||||
|
||||
async def _topic_vector_search(query_text: str, k: int, source_fields: list) -> list:
|
||||
try:
|
||||
from ..util import get_model
|
||||
|
||||
query_vector = get_model().encode(query_text).tolist()
|
||||
except Exception:
|
||||
logger.exception("Failed to encode text for topic vector search.")
|
||||
return []
|
||||
|
||||
try:
|
||||
response = await elasticsearch.search(
|
||||
index="topicvectors",
|
||||
body={
|
||||
"knn": {
|
||||
"field": "display_name_vector",
|
||||
"query_vector": query_vector,
|
||||
"k": k,
|
||||
"num_candidates": TOPIC_NUM_CANDIDATES,
|
||||
"similarity": TOPIC_SIMILARITY,
|
||||
},
|
||||
"_source": source_fields,
|
||||
"size": k,
|
||||
},
|
||||
cluster="nes",
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Topic vector search failed.")
|
||||
return []
|
||||
|
||||
return [hit.get("_source", {}) for hit in response.get("hits", {}).get("hits", [])]
|
||||
|
||||
|
||||
async def _build_mentioned_persons(author_names: list) -> list:
|
||||
|
||||
ude_persons = []
|
||||
other_persons = []
|
||||
|
||||
for name in author_names:
|
||||
match = find_ude_author_by_name(name)
|
||||
match = await find_ude_author_by_name(name)
|
||||
if match:
|
||||
ude_persons.append(
|
||||
MentionedPerson(name=name, is_ude=True, person_id=match["id"])
|
||||
@@ -160,33 +392,35 @@ def _build_mentioned_persons(author_names: list) -> list:
|
||||
return ude_persons + other_persons
|
||||
|
||||
|
||||
def _get_postproc_labels(news_id: str) -> tuple[bool | None, list]:
|
||||
async def _get_postproc_labels(news_id: str) -> tuple[bool | None, list, list, str | None]:
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index="aktuell_postproc",
|
||||
query={"term": {"news_id.keyword": news_id}},
|
||||
source=["relevant", "authors"],
|
||||
source=["relevant", "authors", "keywords"],
|
||||
size=1,
|
||||
cluster="inse",
|
||||
)
|
||||
except Exception:
|
||||
logger.exception(f"Postproc-Lookup for {news_id} failed.")
|
||||
return None, []
|
||||
return None, [], [], None
|
||||
|
||||
hits = response.get("hits", {}).get("hits", [])
|
||||
if not hits:
|
||||
return None, []
|
||||
return None, [], [], None
|
||||
|
||||
postproc_source = hits[0].get("_source", {})
|
||||
hit = hits[0]
|
||||
postproc_source = hit.get("_source", {})
|
||||
relevant = bool(postproc_source.get("relevant", 0))
|
||||
authors = postproc_source.get("authors") or []
|
||||
keywords = postproc_source.get("keywords") or []
|
||||
|
||||
return relevant, authors
|
||||
return relevant, authors, keywords, hit.get("_id")
|
||||
|
||||
|
||||
def _run_search(query: dict, source: list, size: int, offset: int, sort, highlight: dict = None) -> dict:
|
||||
async def _run_search(query: dict, source: list, size: int, offset: int, sort, highlight: dict = None) -> dict:
|
||||
try:
|
||||
return elasticsearch.search(
|
||||
return await elasticsearch.search(
|
||||
index="aktuell",
|
||||
query=query,
|
||||
source=source,
|
||||
@@ -197,15 +431,12 @@ def _run_search(query: dict, source: list, size: int, offset: int, sort, highlig
|
||||
highlight=highlight,
|
||||
cluster="inse",
|
||||
)
|
||||
except Exception as exc:
|
||||
except ElasticsearchException as exc:
|
||||
logger.exception("Elasticsearch-Anfrage an Index 'aktuell' fehlgeschlagen.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail="Etwas ist schiefgelaufen.",
|
||||
) from exc
|
||||
raise
|
||||
|
||||
|
||||
def _build_page(response: dict, page: int, page_size: int) -> NewsPage:
|
||||
async def _build_page(response: dict, page: int, page_size: int) -> NewsPage:
|
||||
hits_section = response.get("hits", {})
|
||||
total = hits_section.get("total", {}).get("value", 0)
|
||||
hits = hits_section.get("hits", [])
|
||||
@@ -216,7 +447,7 @@ def _build_page(response: dict, page: int, page_size: int) -> NewsPage:
|
||||
if news_id:
|
||||
news_ids.append(news_id)
|
||||
|
||||
relevance_map = _get_relevance_map(news_ids)
|
||||
relevance_map = await _get_relevance_map(news_ids)
|
||||
|
||||
articles = []
|
||||
for hit in hits:
|
||||
@@ -232,12 +463,12 @@ def _build_page(response: dict, page: int, page_size: int) -> NewsPage:
|
||||
)
|
||||
|
||||
|
||||
def _get_relevance_map(news_ids: list) -> dict:
|
||||
async def _get_relevance_map(news_ids: list) -> dict:
|
||||
if not news_ids:
|
||||
return {}
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index="aktuell_postproc",
|
||||
query={"terms": {"news_id.keyword": news_ids}},
|
||||
source=["news_id", "relevant"],
|
||||
@@ -262,7 +493,11 @@ def _parse_hit(hit: dict) -> NewsArticle:
|
||||
source = hit.get("_source", {})
|
||||
|
||||
fragments = hit.get("highlight", {}).get("full_content")
|
||||
snippet = fragments[0] if fragments else None
|
||||
|
||||
if fragments:
|
||||
snippet = fragments[0]
|
||||
else:
|
||||
snippet = _make_preview(source)
|
||||
|
||||
return NewsArticle(
|
||||
id=hit.get("_id"),
|
||||
@@ -272,3 +507,104 @@ def _parse_hit(hit: dict) -> NewsArticle:
|
||||
url=source.get("url"),
|
||||
snippet=snippet,
|
||||
)
|
||||
|
||||
|
||||
def _make_preview(source: dict) -> str | None:
|
||||
text = source.get("intro_content") or source.get("full_content")
|
||||
|
||||
if not text:
|
||||
return None
|
||||
|
||||
words = text.split()
|
||||
|
||||
PREVIEW_WORD_COUNT = 10
|
||||
preview = " ".join(words[:PREVIEW_WORD_COUNT])
|
||||
if len(words) > PREVIEW_WORD_COUNT:
|
||||
preview = preview + " …"
|
||||
return preview
|
||||
|
||||
|
||||
def _is_last_page(page: int, page_size: int, total: int) -> bool:
|
||||
return page * page_size >= total
|
||||
|
||||
|
||||
async def _exact_match_ids(query: dict) -> list:
|
||||
try:
|
||||
response = await _run_search(
|
||||
query=query,
|
||||
source=[],
|
||||
size=EXACT_ID_CAP,
|
||||
offset=0,
|
||||
sort=None,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Failed to collect exact-match ids for dedup.")
|
||||
return []
|
||||
|
||||
return [
|
||||
hit.get("_id")
|
||||
for hit in response.get("hits", {}).get("hits", [])
|
||||
if hit.get("_id")
|
||||
]
|
||||
|
||||
|
||||
async def _related_articles(
|
||||
query_text: str,
|
||||
exclude_ids: list | None = None,
|
||||
filter_news_ids: list | None = None,
|
||||
extra_filters: list | None = None,
|
||||
k: int = RELATED_BLOCK_SIZE,
|
||||
) -> list:
|
||||
related_terms = await _related_search_terms(query_text)
|
||||
if not related_terms:
|
||||
return []
|
||||
|
||||
bool_query = {
|
||||
"should": [{"match": {"full_content": term}} for term in related_terms],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
if exclude_ids:
|
||||
bool_query["must_not"] = [{"ids": {"values": exclude_ids}}]
|
||||
if filter_news_ids is not None:
|
||||
bool_query["filter"] = [{"ids": {"values": filter_news_ids}}]
|
||||
if extra_filters:
|
||||
bool_query.setdefault("filter", []).extend(extra_filters)
|
||||
|
||||
try:
|
||||
response = await elasticsearch.search(
|
||||
index="aktuell",
|
||||
query={"bool": bool_query},
|
||||
source=["date", "maintitle", "author", "url", "intro_content", "full_content"],
|
||||
size=k,
|
||||
offset=0,
|
||||
cluster="inse",
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Related-articles search failed.")
|
||||
return []
|
||||
|
||||
articles = []
|
||||
for hit in response.get("hits", {}).get("hits", []):
|
||||
article = _parse_hit(hit)
|
||||
article.related = True
|
||||
articles.append(article)
|
||||
|
||||
relevance_map = await _get_relevance_map([article.id for article in articles])
|
||||
for article in articles:
|
||||
article.relevant = relevance_map.get(article.id)
|
||||
|
||||
return articles
|
||||
|
||||
|
||||
async def _related_search_terms(query_text: str) -> list:
|
||||
topics = await _topic_vector_search(query_text, RELATED_TOPIC_K, ["display_name", "keywords"])
|
||||
|
||||
seen = {query_text.lower()}
|
||||
terms = []
|
||||
for topic in topics:
|
||||
for term in [topic.get("display_name"), *(topic.get("keywords") or [])]:
|
||||
if term and term.lower() not in seen:
|
||||
seen.add(term.lower())
|
||||
terms.append(term)
|
||||
|
||||
return terms
|
||||
|
||||
@@ -14,6 +14,7 @@ class NewsArticle(BaseModel):
|
||||
url: Optional[str] = None
|
||||
relevant: Optional[bool] = None
|
||||
snippet: Optional[str] = None
|
||||
related: Optional[bool] = None
|
||||
|
||||
|
||||
class MentionedPerson(BaseModel):
|
||||
@@ -26,6 +27,8 @@ class NewsArticleDetail(NewsArticle):
|
||||
full_content: Optional[str] = None
|
||||
relevant: Optional[bool] = None
|
||||
authors: List[MentionedPerson] = []
|
||||
topics: List[str] = []
|
||||
keywords: List[str] = []
|
||||
|
||||
|
||||
class NewsPage(BaseModel):
|
||||
|
||||
@@ -16,6 +16,15 @@ from .model import NewsArticleDetail, NewsPage
|
||||
|
||||
router = APIRouter(prefix="/api/news", tags=[Tags.NEWS])
|
||||
|
||||
ALLOWED_RELEVANCE_VALUES = {"relevant", "not_relevant"}
|
||||
|
||||
|
||||
def _parse_relevance(relevance: str | None) -> list:
|
||||
if not relevance:
|
||||
return []
|
||||
values = [entry.strip() for entry in relevance.split(",")]
|
||||
return [value for value in values if value in ALLOWED_RELEVANCE_VALUES]
|
||||
|
||||
|
||||
@router.get(
|
||||
"",
|
||||
@@ -25,7 +34,7 @@ router = APIRouter(prefix="/api/news", tags=[Tags.NEWS])
|
||||
summary="Returns a page of news articles, newest first.",
|
||||
tags=[Tags.NEWS],
|
||||
)
|
||||
def list_news(
|
||||
async def list_news(
|
||||
page: Annotated[
|
||||
int, Query(description="Page number (1-based).", ge=1)
|
||||
] = 1,
|
||||
@@ -35,8 +44,24 @@ def list_news(
|
||||
sort_order: Annotated[
|
||||
str, Query(alias="sortOrder", description="Sort order: 'desc' (newest first) or 'asc' (oldest first).", pattern="^(asc|desc)$")
|
||||
] = "desc",
|
||||
relevance: Annotated[
|
||||
str | None, Query(description="Comma-separated relevance filter: 'relevant', 'not_relevant'.")
|
||||
] = None,
|
||||
year_from: Annotated[
|
||||
int | None, Query(alias="yearFrom", description="Earliest publication year (inclusive).", ge=0)
|
||||
] = None,
|
||||
year_to: Annotated[
|
||||
int | None, Query(alias="yearTo", description="Latest publication year (inclusive).", ge=0)
|
||||
] = None,
|
||||
):
|
||||
return logic.get_news_page(page, page_size, sort_order)
|
||||
return await logic.get_news_page(
|
||||
page,
|
||||
page_size,
|
||||
sort_order,
|
||||
year_from=year_from,
|
||||
year_to=year_to,
|
||||
relevance_values=_parse_relevance(relevance),
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
@@ -47,7 +72,7 @@ def list_news(
|
||||
summary="Searches news articles by full text (full_content).",
|
||||
tags=[Tags.NEWS],
|
||||
)
|
||||
def search_news(
|
||||
async def search_news(
|
||||
query: Annotated[
|
||||
str, Query(description="Search term, matched against the full text (full_content).", min_length=1)
|
||||
],
|
||||
@@ -57,8 +82,24 @@ def search_news(
|
||||
page_size: Annotated[
|
||||
int, Query(alias="pageSize", description="Articles per page.", ge=1, le=100)
|
||||
] = 10,
|
||||
relevance: Annotated[
|
||||
str | None, Query(description="Comma-separated relevance filter: 'relevant', 'not_relevant'.")
|
||||
] = None,
|
||||
year_from: Annotated[
|
||||
int | None, Query(alias="yearFrom", description="Earliest publication year (inclusive).", ge=0)
|
||||
] = None,
|
||||
year_to: Annotated[
|
||||
int | None, Query(alias="yearTo", description="Latest publication year (inclusive).", ge=0)
|
||||
] = None,
|
||||
):
|
||||
return logic.search_news(query, page, page_size)
|
||||
return await logic.search_news(
|
||||
query,
|
||||
page,
|
||||
page_size,
|
||||
year_from=year_from,
|
||||
year_to=year_to,
|
||||
relevance_values=_parse_relevance(relevance),
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
@@ -69,7 +110,7 @@ def search_news(
|
||||
summary="Returns news articles in which the given person is mentioned.",
|
||||
tags=[Tags.NEWS],
|
||||
)
|
||||
def get_news_by_author(
|
||||
async def get_news_by_author(
|
||||
author_id: Annotated[
|
||||
str, Query(alias="authorId", description="OpenAlex author id, e.g. A5034365278.")
|
||||
],
|
||||
@@ -86,7 +127,7 @@ def get_news_by_author(
|
||||
str | None, Query(description="Optional search term, matched against title/author.")
|
||||
] = None,
|
||||
):
|
||||
return logic.get_news_by_author(author_id, page, page_size, sort_order, query)
|
||||
return await logic.get_news_by_author(author_id, page, page_size, sort_order, query)
|
||||
|
||||
|
||||
@router.get(
|
||||
@@ -97,9 +138,9 @@ def get_news_by_author(
|
||||
summary="Returns a single news article including its full content.",
|
||||
tags=[Tags.NEWS],
|
||||
)
|
||||
def get_news_by_id(
|
||||
async def get_news_by_id(
|
||||
news_id: Annotated[
|
||||
str, Path(description="The unique id of the news article (Elasticsearch _id).")
|
||||
],
|
||||
):
|
||||
return logic.get_news_by_id(news_id)
|
||||
return await logic.get_news_by_id(news_id)
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
HTTP client for fetching all patents from EPO and USPTO Elasticsearch indices.
|
||||
"""
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from .. import config
|
||||
from inse.exceptions import MissingApiKeyError
|
||||
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster
|
||||
|
||||
EPO_INDEX = "epo_index_1.0"
|
||||
USPTO_INDEX = "uspto_patents_3.0"
|
||||
|
||||
|
||||
class AllPatentsSearchClient:
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str | None = None,
|
||||
api_key: str | None = None,
|
||||
timeout: float = 30.0,
|
||||
transport: httpx.AsyncBaseTransport | None = None,
|
||||
):
|
||||
self.base_url = (base_url or config.settings.patent_elasticsearch_url).rstrip("/")
|
||||
self.api_key = api_key if api_key is not None else config.settings.patent_elasticsearch_api_key
|
||||
self.timeout = timeout
|
||||
self.transport = transport
|
||||
|
||||
def _headers(self) -> dict[str, str]:
|
||||
if not self.api_key:
|
||||
raise MissingApiKeyError("Patent Elasticsearch API key is not configured.")
|
||||
return {
|
||||
"Authorization": f"ApiKey {self.api_key}",
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
def epo_query(
|
||||
self,
|
||||
page: int = 0,
|
||||
size: int = 10,
|
||||
search: str | None = None,
|
||||
sort_direction: str = "desc",
|
||||
) -> dict[str, Any]:
|
||||
sort = [{"date_publication": {"order": sort_direction, "missing": "_last"}}, "_doc"]
|
||||
|
||||
if search and search.strip():
|
||||
term = search.strip()
|
||||
doc_number = term.upper().removeprefix("EP")
|
||||
query: dict[str, Any] = {
|
||||
"bool": {
|
||||
"should": [
|
||||
{"match_phrase": {"title_en": {"query": term}}},
|
||||
{"match_phrase": {"title_de": {"query": term}}},
|
||||
{"term": {"doc_number": doc_number}},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
else:
|
||||
query = {"match_all": {}}
|
||||
|
||||
return {
|
||||
"from": page * size,
|
||||
"size": size,
|
||||
"track_total_hits": True,
|
||||
"sort": sort,
|
||||
"_source": [
|
||||
"doc_number", "country", "kind", "date_publication",
|
||||
"date_publication_year", "application_number",
|
||||
"application_filing_date", "title_en", "title_de",
|
||||
"abstract", "inventors_name", "applicants_name", "ipc", "cpc",
|
||||
],
|
||||
"query": query,
|
||||
}
|
||||
|
||||
def uspto_query(
|
||||
self,
|
||||
page: int = 0,
|
||||
size: int = 10,
|
||||
search: str | None = None,
|
||||
sort_direction: str = "desc",
|
||||
) -> dict[str, Any]:
|
||||
sort = [{"publication_date": {"order": sort_direction, "missing": "_last"}}, "_doc"]
|
||||
|
||||
if search and search.strip():
|
||||
term = search.strip()
|
||||
pub_number = term.upper().removeprefix("US")
|
||||
query: dict[str, Any] = {
|
||||
"bool": {
|
||||
"should": [
|
||||
{"match_phrase": {"title": {"query": term}}},
|
||||
{"term": {"publication_number": pub_number}},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
else:
|
||||
query = {"match_all": {}}
|
||||
|
||||
return {
|
||||
"from": page * size,
|
||||
"size": size,
|
||||
"track_total_hits": True,
|
||||
"sort": sort,
|
||||
"_source": [
|
||||
"publication_number", "country", "publication_date",
|
||||
"publication_year", "application_number", "application_date",
|
||||
"application_type", "title", "abstract", "inventors_names",
|
||||
"assignees_orgs", "ipcr", "cpc", "number_of_claims", "status",
|
||||
],
|
||||
"query": query,
|
||||
}
|
||||
|
||||
async def search_epo(self, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return await self._search(EPO_INDEX, payload)
|
||||
|
||||
async def search_uspto(self, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return await self._search(USPTO_INDEX, payload)
|
||||
|
||||
async def _search(self, index: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return await elasticsearch.search(index=index, body=payload, cluster=ESCluster.INSE)
|
||||
@@ -4,15 +4,13 @@
|
||||
HTTP client for patent searches in EPO and USPTO Elasticsearch indices.
|
||||
"""
|
||||
from typing import Any
|
||||
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster, ESIndex
|
||||
import httpx
|
||||
|
||||
import asyncio
|
||||
from .. import config
|
||||
from .name_matching import search_name_variants
|
||||
|
||||
EPO_INDEX = "epo_index_1.0"
|
||||
USPTO_INDEX = "uspto_patents_3.0"
|
||||
|
||||
DEFAULT_SEARCH_SIZE = 100
|
||||
|
||||
|
||||
@@ -29,8 +27,7 @@ def _match_name_field(field: str, name: str) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
class MissingApiKeyError(Exception):
|
||||
pass
|
||||
from inse.exceptions import MissingApiKeyError
|
||||
|
||||
|
||||
class PatentSearchClient:
|
||||
@@ -97,13 +94,15 @@ class PatentSearchClient:
|
||||
"kind",
|
||||
"date_publication",
|
||||
"date_publication_year",
|
||||
"application_number",
|
||||
"application_filing_date",
|
||||
"title_en",
|
||||
"title_de",
|
||||
"abstract",
|
||||
"inventors_name",
|
||||
"applicants_name",
|
||||
"ipc",
|
||||
"ipc_text",
|
||||
"cpc",
|
||||
],
|
||||
"query": query,
|
||||
}
|
||||
@@ -150,33 +149,133 @@ class PatentSearchClient:
|
||||
"country",
|
||||
"publication_date",
|
||||
"publication_year",
|
||||
"application_number",
|
||||
"application_date",
|
||||
"application_type",
|
||||
"title",
|
||||
"abstract",
|
||||
"inventors_names",
|
||||
"inventors_names_text",
|
||||
"assignees_orgs",
|
||||
"ipcr",
|
||||
"ipcr_text",
|
||||
"cpc",
|
||||
"number_of_claims",
|
||||
"status",
|
||||
],
|
||||
"query": query,
|
||||
}
|
||||
|
||||
async def search_epo(self, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return await self._search(EPO_INDEX, payload)
|
||||
return await self._search(ESIndex.EPO_INDEX, payload)
|
||||
|
||||
async def search_uspto(self, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return await self._search(USPTO_INDEX, payload)
|
||||
return await self._search(ESIndex.USPTO_INDEX, payload)
|
||||
|
||||
async def _search(self, index: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
async with httpx.AsyncClient(
|
||||
base_url=self.base_url,
|
||||
timeout=self.timeout,
|
||||
transport=self.transport,
|
||||
) as client:
|
||||
response = await client.post(
|
||||
f"/{index}/_search",
|
||||
headers=self._headers(),
|
||||
json=payload,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
response = await elasticsearch.search(index=index, body=payload, cluster=ESCluster.INSE)
|
||||
return response
|
||||
|
||||
async def get_by_id_or_title(
|
||||
self,
|
||||
patent_id: str,
|
||||
prefix: str,
|
||||
title: str,
|
||||
size: int = 1,
|
||||
) -> dict[str, Any]:
|
||||
"""Search EPO and USPTO by ID; fall back to match_phrase on title if no hits.
|
||||
|
||||
Args:
|
||||
patent_id: The raw document/publication number (e.g. "1234567", "US1234567A").
|
||||
prefix: "EP" routes the title fallback to EPO; "US" routes it to USPTO.
|
||||
Both indices are always queried for the ID lookup.
|
||||
title: Used only when the ID lookup returns zero hits.
|
||||
size: Maximum number of results to return.
|
||||
"""
|
||||
epo_id_payload = self._epo_query_by_id(patent_id, size)
|
||||
uspto_id_payload = self._uspto_query_by_id(patent_id, size)
|
||||
|
||||
epo_result, uspto_result = await asyncio.gather(
|
||||
self.search_epo(epo_id_payload),
|
||||
self.search_uspto(uspto_id_payload),
|
||||
)
|
||||
|
||||
epo_hits = epo_result.get("hits", {}).get("total", {}).get("value", 0)
|
||||
uspto_hits = uspto_result.get("hits", {}).get("total", {}).get("value", 0)
|
||||
|
||||
if epo_hits > 0 or uspto_hits > 0:
|
||||
if prefix.upper() == "EP" and epo_hits > 0:
|
||||
return epo_result
|
||||
if prefix.upper() == "US" and uspto_hits > 0:
|
||||
return uspto_result
|
||||
return epo_result if epo_hits > 0 else uspto_result
|
||||
|
||||
if prefix.upper() == "US":
|
||||
payload = self._uspto_query_by_title(title, size)
|
||||
return await self.search_uspto(payload)
|
||||
|
||||
payload = self._epo_query_by_title(title, size)
|
||||
return await self.search_epo(payload)
|
||||
#query builders
|
||||
|
||||
def _epo_query_by_id(self, patent_id: str, size: int) -> dict[str, Any]:
|
||||
"""Term query against doc_number; strips a leading 'EP' prefix if present."""
|
||||
raw_id = patent_id.upper().removeprefix("EP")
|
||||
return {
|
||||
"size": size,
|
||||
"_source": [
|
||||
"doc_number", "country", "kind", "date_publication",
|
||||
"date_publication_year", "application_number",
|
||||
"application_filing_date", "title_en", "title_de", "abstract",
|
||||
"inventors_name", "applicants_name", "ipc", "cpc",
|
||||
],
|
||||
"query": {"term": {"doc_number": raw_id}},
|
||||
}
|
||||
|
||||
def _uspto_query_by_id(self, patent_id: str, size: int) -> dict[str, Any]:
|
||||
"""Term query against publication_number; tries the ID as-is."""
|
||||
return {
|
||||
"size": size,
|
||||
"track_total_hits": True,
|
||||
"sort": [{"publication_date": {"order": "desc", "missing": "_last"}}, "_doc"],
|
||||
"_source": [
|
||||
"publication_number", "country", "publication_date",
|
||||
"publication_year", "application_number", "application_date",
|
||||
"application_type", "title", "abstract", "inventors_names",
|
||||
"assignees_orgs", "ipcr", "cpc", "number_of_claims", "status",
|
||||
],
|
||||
"query": {"term": {"publication_number": patent_id}},
|
||||
}
|
||||
|
||||
def _epo_query_by_title(self, title: str, size: int) -> dict[str, Any]:
|
||||
"""match_phrase fallback on title_en (and title_de as a should clause)."""
|
||||
return {
|
||||
"size": size,
|
||||
"_source": [
|
||||
"doc_number", "country", "kind", "date_publication",
|
||||
"date_publication_year", "application_number",
|
||||
"application_filing_date", "title_en", "title_de", "abstract",
|
||||
"inventors_name", "applicants_name", "ipc", "cpc",
|
||||
],
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{"match_phrase": {"title_en": title}},
|
||||
{"match_phrase": {"title_de": title}},
|
||||
{"match_phrase": {"title_fr": title}},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
def _uspto_query_by_title(self, title: str, size: int) -> dict[str, Any]:
|
||||
"""match_phrase fallback on title."""
|
||||
return {
|
||||
"size": size,
|
||||
"_source": [
|
||||
"publication_number", "country", "publication_date",
|
||||
"publication_year", "application_number", "application_date",
|
||||
"application_type", "title", "abstract", "inventors_names",
|
||||
"assignees_orgs", "ipcr", "cpc", "number_of_claims", "status",
|
||||
],
|
||||
"query": {"match_phrase": {"title": title}},
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Parse IPC/CPC symbols and assemble enriched classification objects.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
|
||||
from . import model
|
||||
|
||||
IPC_SYMBOL_RE = re.compile(
|
||||
r"^(?P<section>[A-HY])"
|
||||
r"(?P<class_num>\d{2})"
|
||||
r"(?P<subclass_letter>[A-Z])"
|
||||
r"\s*"
|
||||
r"(?:(?P<main_group>\d+))?"
|
||||
r"(?:/(?P<subgroup>\d+))?"
|
||||
r"\s*$",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
# EPO strings append metadata after the symbol, e.g.
|
||||
# "G01S 5/02 20100101AFI20140127BHEP"
|
||||
IPC_CODE_EXTRACT_RE = re.compile(
|
||||
r"^([A-HY]\d{2}[A-Z]\s*\d+(?:/\d+)?)",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
# Legacy EPO spacing and trailing classification value, e.g.
|
||||
# "C 07C 405/00 A" or "C 07D 317/20 B"
|
||||
EPO_LEGACY_IPC_RE = re.compile(
|
||||
r"^(?P<section>[A-HY])\s+"
|
||||
r"(?P<class_num>\d{2})\s*"
|
||||
r"(?P<subclass_letter>[A-Z])\s+"
|
||||
r"(?P<main_group>\d+)"
|
||||
r"(?:/(?P<subgroup>\d+))?"
|
||||
r"(?:\s+(?P<classification_value>[A-Z]))?"
|
||||
r"(?:\s|$)",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
IPC_SUBCLASS_ONLY_RE = re.compile(
|
||||
r"^([A-HY]\d{2}[A-Z])(?:\s|$)",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class IpcHierarchyKeys:
|
||||
symbol: str
|
||||
normalized: str
|
||||
section: str | None
|
||||
ipc_class: str | None
|
||||
subclass: str | None
|
||||
main_group: str | None
|
||||
subgroup: str | None
|
||||
|
||||
|
||||
def extract_ipc_symbol(raw: str) -> str:
|
||||
"""
|
||||
Extract the classification code from a raw patent IPC string.
|
||||
|
||||
Supports:
|
||||
- 'G01S 5/02 20100101AFI20140127BHEP'
|
||||
- 'C 07C 405/00 A' (legacy EPO spacing)
|
||||
"""
|
||||
cleaned = raw.strip()
|
||||
if not cleaned:
|
||||
return cleaned
|
||||
|
||||
legacy = EPO_LEGACY_IPC_RE.match(cleaned)
|
||||
if legacy:
|
||||
section = legacy.group("section").upper()
|
||||
class_num = legacy.group("class_num")
|
||||
subclass_letter = legacy.group("subclass_letter").upper()
|
||||
prefix = f"{section}{class_num}{subclass_letter}"
|
||||
main_group = legacy.group("main_group")
|
||||
subgroup = legacy.group("subgroup")
|
||||
if subgroup is not None:
|
||||
normalized = f"{prefix}{main_group}/{subgroup}"
|
||||
else:
|
||||
normalized = f"{prefix}{main_group}"
|
||||
return display_ipc_symbol(normalized)
|
||||
|
||||
match = IPC_CODE_EXTRACT_RE.match(cleaned)
|
||||
if match:
|
||||
return display_ipc_symbol(normalize_ipc_symbol(match.group(1)))
|
||||
|
||||
match = IPC_SUBCLASS_ONLY_RE.match(cleaned)
|
||||
if match:
|
||||
return match.group(1).upper()
|
||||
|
||||
return cleaned
|
||||
|
||||
|
||||
def normalize_ipc_symbol(symbol: str) -> str:
|
||||
"""Remove whitespace, e.g. 'H01L 21/02' -> 'H01L21/02'."""
|
||||
return re.sub(r"\s+", "", symbol.strip().upper())
|
||||
|
||||
|
||||
def display_ipc_symbol(normalized: str) -> str:
|
||||
"""Format for display, e.g. 'H01L21/02' -> 'H01L 21/02'."""
|
||||
match = re.match(r"^([A-HY]\d{2}[A-Z])(\d+)(/\d+)$", normalized, re.IGNORECASE)
|
||||
if match:
|
||||
return f"{match.group(1)} {match.group(2)}{match.group(3)}"
|
||||
match = re.match(r"^([A-HY]\d{2}[A-Z])$", normalized, re.IGNORECASE)
|
||||
if match:
|
||||
return match.group(1)
|
||||
return normalized
|
||||
|
||||
|
||||
def parse_ipc_symbol(symbol: str) -> IpcHierarchyKeys:
|
||||
"""Derive lookup keys for each hierarchy level from a patent IPC symbol."""
|
||||
cleaned = extract_ipc_symbol(symbol.strip())
|
||||
normalized = normalize_ipc_symbol(cleaned)
|
||||
match = IPC_SYMBOL_RE.match(cleaned) or IPC_SYMBOL_RE.match(normalized)
|
||||
|
||||
if not match:
|
||||
return IpcHierarchyKeys(
|
||||
symbol=cleaned,
|
||||
normalized=normalized,
|
||||
section=None,
|
||||
ipc_class=None,
|
||||
subclass=None,
|
||||
main_group=None,
|
||||
subgroup=None,
|
||||
)
|
||||
|
||||
section = match.group("section").upper()
|
||||
class_num = match.group("class_num")
|
||||
subclass_letter = match.group("subclass_letter").upper()
|
||||
subclass = f"{section}{class_num}{subclass_letter}"
|
||||
ipc_class = f"{section}{class_num}"
|
||||
|
||||
main_group_digits = match.group("main_group")
|
||||
subgroup_digits = match.group("subgroup")
|
||||
|
||||
main_group = None
|
||||
subgroup = None
|
||||
if main_group_digits:
|
||||
base = f"{subclass}{main_group_digits}"
|
||||
if subgroup_digits:
|
||||
full = f"{base}/{subgroup_digits}"
|
||||
if len(subgroup_digits) > 2:
|
||||
subgroup = full
|
||||
main_group = f"{base}/{subgroup_digits[:2]}"
|
||||
else:
|
||||
main_group = full
|
||||
else:
|
||||
main_group = base
|
||||
|
||||
return IpcHierarchyKeys(
|
||||
symbol=cleaned,
|
||||
normalized=normalized,
|
||||
section=section,
|
||||
ipc_class=ipc_class,
|
||||
subclass=subclass,
|
||||
main_group=main_group,
|
||||
subgroup=subgroup,
|
||||
)
|
||||
|
||||
|
||||
def _format_level(number: str | None, name: str | None) -> str | None:
|
||||
if not number or not name:
|
||||
return None
|
||||
label = display_ipc_symbol(number)
|
||||
return f"{label} - {name.strip()}"
|
||||
|
||||
|
||||
def _lookup_name(level_names: dict[str, str | None], *keys: str | None) -> str | None:
|
||||
for key in keys:
|
||||
if not key:
|
||||
continue
|
||||
if key in level_names and level_names[key]:
|
||||
return level_names[key]
|
||||
normalized = normalize_ipc_symbol(key)
|
||||
if normalized in level_names and level_names[normalized]:
|
||||
return level_names[normalized]
|
||||
return None
|
||||
|
||||
|
||||
def build_ipc_classification(
|
||||
keys: IpcHierarchyKeys,
|
||||
names: dict[str, dict[str, str | None]],
|
||||
) -> model.IpcClassification:
|
||||
"""Combine parsed keys with lookup results from the ipc index."""
|
||||
section_name = _lookup_name(names.get("section", {}), keys.section)
|
||||
class_name = _lookup_name(names.get("class", {}), keys.ipc_class)
|
||||
subclass_name = _lookup_name(names.get("class", {}), keys.subclass)
|
||||
group_name = _lookup_name(
|
||||
names.get("group", {}),
|
||||
keys.main_group,
|
||||
keys.normalized,
|
||||
)
|
||||
subgroup_name = _lookup_name(
|
||||
names.get("subgroup", {}),
|
||||
keys.subgroup,
|
||||
keys.normalized,
|
||||
)
|
||||
|
||||
if not subgroup_name and group_name and keys.subgroup:
|
||||
subgroup_name = group_name
|
||||
|
||||
main_group = None
|
||||
if group_name:
|
||||
main_group = _format_level(keys.main_group or keys.normalized, group_name)
|
||||
|
||||
subgroup = None
|
||||
if subgroup_name:
|
||||
subgroup = _format_level(keys.subgroup or keys.normalized, subgroup_name)
|
||||
|
||||
return model.IpcClassification(
|
||||
symbol=keys.symbol,
|
||||
section=_format_level(keys.section, section_name),
|
||||
ipc_class=_format_level(keys.ipc_class, class_name)
|
||||
if class_name
|
||||
else (display_ipc_symbol(keys.ipc_class) if keys.ipc_class else None),
|
||||
subclass=_format_level(keys.subclass, subclass_name),
|
||||
main_group=main_group,
|
||||
subgroup=subgroup,
|
||||
)
|
||||
@@ -0,0 +1,142 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
HTTP client for IPC/CPC classification lookups in the ipc Elasticsearch index.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from .. import config
|
||||
from . import model
|
||||
from inse.exceptions import MissingApiKeyError
|
||||
from .ipc_lookup import IpcHierarchyKeys
|
||||
from .ipc_lookup import build_ipc_classification
|
||||
from .ipc_lookup import parse_ipc_symbol
|
||||
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster
|
||||
|
||||
IPC_INDEX = "ipc"
|
||||
|
||||
_LEVELS: tuple[tuple[str, str, str], ...] = (
|
||||
("section", "cpc_section_number", "cpc_section_name"),
|
||||
("class", "cpc_class_number", "cpc_class_name"),
|
||||
("group", "cpc_group_number", "cpc_group_name"),
|
||||
("subgroup", "cpc_subgroup_number", "cpc_subgroup_name"),
|
||||
)
|
||||
|
||||
|
||||
class IpcSearchClient:
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str | None = None,
|
||||
api_key: str | None = None,
|
||||
timeout: float = 30.0,
|
||||
transport: httpx.AsyncBaseTransport | None = None,
|
||||
):
|
||||
self.base_url = (base_url or config.settings.patent_elasticsearch_url).rstrip("/")
|
||||
self.api_key = api_key if api_key is not None else config.settings.patent_elasticsearch_api_key
|
||||
self.timeout = timeout
|
||||
self.transport = transport
|
||||
|
||||
def _headers(self) -> dict[str, str]:
|
||||
if not self.api_key:
|
||||
raise MissingApiKeyError("Patent Elasticsearch API key is not configured.")
|
||||
return {
|
||||
"Authorization": f"ApiKey {self.api_key}",
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
async def resolve_symbols(self, symbols: list[str]) -> dict[str, model.IpcClassification]:
|
||||
"""Resolve patent IPC symbols to enriched classification objects."""
|
||||
unique_symbols = list(dict.fromkeys(s.strip() for s in symbols if s and s.strip()))
|
||||
if not unique_symbols:
|
||||
return {}
|
||||
|
||||
parsed = {symbol: parse_ipc_symbol(symbol) for symbol in unique_symbols}
|
||||
names = await self._lookup_all_levels(parsed.values())
|
||||
|
||||
return {
|
||||
symbol: build_ipc_classification(keys, names)
|
||||
for symbol, keys in parsed.items()
|
||||
}
|
||||
|
||||
async def _lookup_all_levels(
|
||||
self,
|
||||
keys_list: list[IpcHierarchyKeys],
|
||||
) -> dict[str, dict[str, str | None]]:
|
||||
symbols_by_level: dict[str, set[str]] = {
|
||||
"section": set(),
|
||||
"class": set(),
|
||||
"group": set(),
|
||||
"subgroup": set(),
|
||||
}
|
||||
|
||||
for keys in keys_list:
|
||||
if keys.section:
|
||||
symbols_by_level["section"].add(keys.section)
|
||||
if keys.ipc_class:
|
||||
symbols_by_level["class"].add(keys.ipc_class)
|
||||
if keys.subclass:
|
||||
symbols_by_level["class"].add(keys.subclass)
|
||||
if keys.main_group:
|
||||
symbols_by_level["group"].add(keys.main_group)
|
||||
if keys.subgroup:
|
||||
symbols_by_level["subgroup"].add(keys.subgroup)
|
||||
if "/" in keys.normalized:
|
||||
symbols_by_level["group"].add(keys.normalized)
|
||||
symbols_by_level["subgroup"].add(keys.normalized)
|
||||
|
||||
results: dict[str, dict[str, str | None]] = {
|
||||
level: {} for level in symbols_by_level
|
||||
}
|
||||
|
||||
for level, number_field, name_field in _LEVELS:
|
||||
level_symbols = {s for s in symbols_by_level[level] if s}
|
||||
if level_symbols:
|
||||
results[level] = await self._lookup_level(number_field, name_field, level_symbols)
|
||||
|
||||
return results
|
||||
|
||||
async def _lookup_level(
|
||||
self,
|
||||
number_field: str,
|
||||
name_field: str,
|
||||
symbols: set[str],
|
||||
) -> dict[str, str | None]:
|
||||
if not symbols:
|
||||
return {}
|
||||
|
||||
payload: dict[str, Any] = {
|
||||
"size": min(len(symbols), 100),
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{"bool": {"filter": [{"match_phrase": {number_field: symbol}}]}}
|
||||
for symbol in sorted(symbols)
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
},
|
||||
"_source": [number_field, name_field],
|
||||
}
|
||||
|
||||
data = await self._search(payload)
|
||||
found: dict[str, str | None] = {}
|
||||
|
||||
for hit in data.get("hits", {}).get("hits", []):
|
||||
source = hit.get("_source", {})
|
||||
number = source.get(number_field)
|
||||
if not number:
|
||||
continue
|
||||
normalized_number = number.strip().upper()
|
||||
found[normalized_number] = source.get(name_field)
|
||||
found[number.strip()] = source.get(name_field)
|
||||
|
||||
return found
|
||||
|
||||
async def _search(self, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return await elasticsearch.search(index=IPC_INDEX, body=payload, cluster=ESCluster.INSE)
|
||||
@@ -1,156 +1,313 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Business logic for patent matching by author name.
|
||||
"""
|
||||
import logging
|
||||
|
||||
import httpx
|
||||
from fastapi import HTTPException
|
||||
from starlette.status import HTTP_502_BAD_GATEWAY
|
||||
from starlette.status import HTTP_503_SERVICE_UNAVAILABLE
|
||||
|
||||
from ..persons import logic as person_logic
|
||||
from ..models.openalex.author import Author
|
||||
from . import model
|
||||
from .elastic_search_client import MissingApiKeyError
|
||||
from .elastic_search_client import PatentSearchClient
|
||||
from .name_matching import name_matches
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def get_patents_by_author_id(
|
||||
author_id: str,
|
||||
client: PatentSearchClient | None = None,
|
||||
) -> model.PatentsByAuthorResponse:
|
||||
search_client = client or PatentSearchClient()
|
||||
|
||||
author = _get_author(author_id)
|
||||
if not author:
|
||||
return model.PatentsByAuthorResponse(
|
||||
author_id=author_id,
|
||||
author_name=None,
|
||||
patent_count=0,
|
||||
patents=[],
|
||||
)
|
||||
|
||||
author_name = author.display_name
|
||||
last_name = _extract_last_name(author_name)
|
||||
first_name = _extract_first_name(author_name)
|
||||
|
||||
if not last_name:
|
||||
return model.PatentsByAuthorResponse(
|
||||
author_id=author_id,
|
||||
author_name=author_name,
|
||||
patent_count=0,
|
||||
patents=[],
|
||||
)
|
||||
|
||||
try:
|
||||
epo_data, uspto_data = await _search_both_indices(
|
||||
search_client, last_name, first_name
|
||||
)
|
||||
except MissingApiKeyError as exc:
|
||||
raise HTTPException(status_code=HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Patent search is not configured.") from exc
|
||||
except httpx.HTTPError as exc:
|
||||
raise HTTPException(status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="Patent search request failed.") from exc
|
||||
|
||||
all_patents = _parse_epo_hits(epo_data) + _parse_uspto_hits(uspto_data)
|
||||
|
||||
if first_name and last_name:
|
||||
all_patents = _filter_patents_by_name(all_patents, first_name, last_name)
|
||||
|
||||
return model.PatentsByAuthorResponse(
|
||||
author_id=author_id,
|
||||
author_name=author_name,
|
||||
patent_count=len(all_patents),
|
||||
patents=all_patents,
|
||||
)
|
||||
|
||||
|
||||
async def _search_both_indices(client, last_name, first_name):
|
||||
import asyncio
|
||||
epo_result, uspto_result = await asyncio.gather(
|
||||
client.search_epo(client.epo_query_by_inventor(last_name, first_name)),
|
||||
client.search_uspto(client.uspto_query_by_inventor(last_name, first_name)),
|
||||
)
|
||||
return epo_result, uspto_result
|
||||
|
||||
|
||||
def _parse_epo_hits(data: dict) -> list[model.PatentEntry]:
|
||||
patents = []
|
||||
for hit in data.get("hits", {}).get("hits", []):
|
||||
src = hit.get("_source", {})
|
||||
inventors = src.get("inventors_name") or []
|
||||
applicants = src.get("applicants_name") or []
|
||||
ipc = src.get("ipc") or []
|
||||
patents.append(model.PatentEntry(
|
||||
patent_id=f"EP{src.get('doc_number', hit.get('_id', ''))}",
|
||||
source="EPO",
|
||||
title=src.get("title_en") or src.get("title_de"),
|
||||
abstract=src.get("abstract"),
|
||||
publication_date=str(src.get("date_publication")) if src.get("date_publication") else None,
|
||||
publication_year=str(src.get("date_publication_year")) if src.get("date_publication_year") else None,
|
||||
inventors=inventors if isinstance(inventors, list) else [inventors],
|
||||
assignees=applicants if isinstance(applicants, list) else [applicants],
|
||||
ipc=ipc if isinstance(ipc, list) else [ipc],
|
||||
country=src.get("country", "EP"),
|
||||
))
|
||||
return patents
|
||||
|
||||
|
||||
def _parse_uspto_hits(data: dict) -> list[model.PatentEntry]:
|
||||
patents = []
|
||||
for hit in data.get("hits", {}).get("hits", []):
|
||||
src = hit.get("_source", {})
|
||||
inventors = src.get("inventors_names") or []
|
||||
assignees = src.get("assignees_orgs") or []
|
||||
ipc = src.get("ipcr") or []
|
||||
patents.append(model.PatentEntry(
|
||||
patent_id=f"US{src.get('publication_number', hit.get('_id', ''))}",
|
||||
source="USPTO",
|
||||
title=src.get("title"),
|
||||
abstract=src.get("abstract"),
|
||||
publication_date=str(src.get("publication_date")) if src.get("publication_date") else None,
|
||||
publication_year=str(src.get("publication_year")) if src.get("publication_year") else None,
|
||||
inventors=inventors if isinstance(inventors, list) else [inventors],
|
||||
assignees=assignees if isinstance(assignees, list) else [assignees],
|
||||
ipc=ipc if isinstance(ipc, list) else [ipc],
|
||||
country=src.get("country", "US"),
|
||||
))
|
||||
return patents
|
||||
|
||||
|
||||
def _filter_patents_by_name(
|
||||
patents: list[model.PatentEntry],
|
||||
first_name: str,
|
||||
last_name: str,
|
||||
) -> list[model.PatentEntry]:
|
||||
"""Keep patents where at least one inventor matches the author name."""
|
||||
return [
|
||||
patent for patent in patents
|
||||
if any(name_matches(inventor, first_name, last_name) for inventor in patent.inventors)
|
||||
]
|
||||
|
||||
|
||||
def _get_author(author_id: str) -> Author | None:
|
||||
short_id = author_id.replace("https://openalex.org/", "")
|
||||
result = person_logic.search_persons(author_id=short_id)
|
||||
return result.results[0] if result.results else None
|
||||
|
||||
|
||||
def _extract_last_name(name: str | None) -> str | None:
|
||||
if not name:
|
||||
return None
|
||||
parts = name.strip().split()
|
||||
return parts[-1] if parts else None
|
||||
|
||||
|
||||
def _extract_first_name(name: str | None) -> str | None:
|
||||
if not name:
|
||||
return None
|
||||
parts = name.strip().split()
|
||||
return parts[0] if len(parts) > 1 else None
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Business logic for patent matching by author name.
|
||||
"""
|
||||
import logging
|
||||
import asyncio
|
||||
|
||||
import httpx
|
||||
|
||||
from ..persons import logic as person_logic
|
||||
from ..models.openalex.author import Author
|
||||
from . import model
|
||||
from inse.exceptions import MissingApiKeyError, ElasticsearchException
|
||||
from .elastic_search_client import PatentSearchClient
|
||||
from .elastic_search_all_patents_client import AllPatentsSearchClient
|
||||
from .ipc_search_client import IpcSearchClient
|
||||
from .ipc_lookup import extract_ipc_symbol
|
||||
from .name_matching import name_matches
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def get_patent(
|
||||
patent_id: str,
|
||||
title: str,
|
||||
prefix: str,
|
||||
client: PatentSearchClient | None = None,
|
||||
) -> model.PatentEntry:
|
||||
search_client = client or PatentSearchClient()
|
||||
|
||||
data = await search_client.get_by_id_or_title(
|
||||
patent_id=patent_id,
|
||||
prefix=prefix,
|
||||
title=title,
|
||||
)
|
||||
|
||||
parse = _parse_uspto_hits if prefix.upper() == "US" else _parse_epo_hits
|
||||
elements = parse(data)
|
||||
|
||||
if not elements:
|
||||
return None
|
||||
return elements[0]
|
||||
|
||||
|
||||
async def get_patents_by_author_id(
|
||||
author_id: str,
|
||||
client: PatentSearchClient | None = None,
|
||||
ipc_client: IpcSearchClient | None = None,
|
||||
) -> model.PatentsByAuthorResponse:
|
||||
search_client = client or PatentSearchClient()
|
||||
ipc_search_client = ipc_client or IpcSearchClient()
|
||||
|
||||
author = await _get_author(author_id)
|
||||
if not author:
|
||||
return model.PatentsByAuthorResponse(
|
||||
author_id=author_id,
|
||||
author_name=None,
|
||||
patent_count=0,
|
||||
patents=[],
|
||||
)
|
||||
|
||||
author_name = author.display_name
|
||||
last_name = _extract_last_name(author_name)
|
||||
first_name = _extract_first_name(author_name)
|
||||
|
||||
if not last_name:
|
||||
return model.PatentsByAuthorResponse(
|
||||
author_id=author_id,
|
||||
author_name=author_name,
|
||||
patent_count=0,
|
||||
patents=[],
|
||||
)
|
||||
|
||||
epo_data, uspto_data = await _search_both_indices(
|
||||
search_client, last_name, first_name
|
||||
)
|
||||
|
||||
all_patents = _parse_epo_hits(epo_data) + _parse_uspto_hits(uspto_data)
|
||||
|
||||
if first_name and last_name:
|
||||
all_patents = _filter_patents_by_name(all_patents, first_name, last_name)
|
||||
|
||||
all_patents = _deduplicate_patents(all_patents)
|
||||
|
||||
await _enrich_patents_classifications(all_patents, ipc_search_client)
|
||||
|
||||
return model.PatentsByAuthorResponse(
|
||||
author_id=author_id,
|
||||
author_name=author_name,
|
||||
patent_count=len(all_patents),
|
||||
patents=all_patents,
|
||||
)
|
||||
|
||||
|
||||
async def _search_both_indices(client, last_name, first_name):
|
||||
epo_result, uspto_result = await asyncio.gather(
|
||||
client.search_epo(client.epo_query_by_inventor(last_name, first_name)),
|
||||
client.search_uspto(client.uspto_query_by_inventor(last_name, first_name)),
|
||||
)
|
||||
return epo_result, uspto_result
|
||||
|
||||
|
||||
def _parse_epo_hits(data: dict) -> list[model.PatentEntry]:
|
||||
patents = []
|
||||
for hit in data.get("hits", {}).get("hits", []):
|
||||
src = hit.get("_source", {})
|
||||
inventors = src.get("inventors_name") or []
|
||||
applicants = src.get("applicants_name") or []
|
||||
ipc = src.get("ipc") or []
|
||||
cpc = src.get("cpc") or []
|
||||
patents.append(model.PatentEntry(
|
||||
patent_id=f"EP{src.get('doc_number', hit.get('_id', ''))}",
|
||||
source="EPO",
|
||||
title=src.get("title_en") or src.get("title_de"),
|
||||
abstract=src.get("abstract"),
|
||||
publication_date=str(src.get("date_publication")) if src.get("date_publication") else None,
|
||||
publication_year=str(src.get("date_publication_year")) if src.get("date_publication_year") else None,
|
||||
application_number=src.get("application_number"),
|
||||
application_date=src.get("application_filing_date"),
|
||||
kind=src.get("kind"),
|
||||
inventors=[i for i in (inventors if isinstance(inventors, list) else [inventors]) if i is not None],
|
||||
assignees=[a for a in (applicants if isinstance(applicants, list) else [applicants]) if a is not None],
|
||||
ipc=_to_classification_strings(ipc),
|
||||
cpc=_to_classification_strings(cpc),
|
||||
country=src.get("country", "EP"),
|
||||
))
|
||||
return patents
|
||||
|
||||
|
||||
def _parse_uspto_hits(data: dict) -> list[model.PatentEntry]:
|
||||
patents = []
|
||||
for hit in data.get("hits", {}).get("hits", []):
|
||||
src = hit.get("_source", {})
|
||||
inventors = src.get("inventors_names") or []
|
||||
assignees = src.get("assignees_orgs") or []
|
||||
ipc = src.get("ipcr") or []
|
||||
cpc = src.get("cpc") or []
|
||||
patents.append(model.PatentEntry(
|
||||
patent_id=f"US{src.get('publication_number', hit.get('_id', ''))}",
|
||||
source="USPTO",
|
||||
title=src.get("title"),
|
||||
abstract=src.get("abstract"),
|
||||
publication_date=str(src.get("publication_date")) if src.get("publication_date") else None,
|
||||
publication_year=str(src.get("publication_year")) if src.get("publication_year") else None,
|
||||
application_number=src.get("application_number"),
|
||||
application_date=str(src.get("application_date")) if src.get("application_date") else None,
|
||||
application_type=src.get("application_type"),
|
||||
number_of_claims=src.get("number_of_claims"),
|
||||
status=src.get("status"),
|
||||
inventors=[i for i in (inventors if isinstance(inventors, list) else [inventors]) if i is not None],
|
||||
assignees=[a for a in (assignees if isinstance(assignees, list) else [assignees]) if a is not None],
|
||||
ipc=_to_classification_strings(ipc),
|
||||
cpc=_to_classification_strings(cpc),
|
||||
country=src.get("country", "US"),
|
||||
))
|
||||
return patents
|
||||
|
||||
|
||||
def _to_classification_strings(value) -> list[str]:
|
||||
if not value:
|
||||
return []
|
||||
items = value if isinstance(value, list) else [value]
|
||||
return [str(item).strip() for item in items if item and str(item).strip()]
|
||||
|
||||
|
||||
def _descriptions_for_raw_codes(
|
||||
raw_codes: list[str],
|
||||
resolved: dict[str, model.IpcClassification],
|
||||
) -> list[model.IpcClassification]:
|
||||
return [
|
||||
resolved[extract_ipc_symbol(raw)]
|
||||
for raw in raw_codes
|
||||
if extract_ipc_symbol(raw) in resolved
|
||||
]
|
||||
|
||||
|
||||
async def _enrich_patents_classifications(
|
||||
patents: list[model.PatentEntry],
|
||||
ipc_client: IpcSearchClient,
|
||||
) -> None:
|
||||
symbols = list(dict.fromkeys(
|
||||
extract_ipc_symbol(raw)
|
||||
for patent in patents
|
||||
for raw in (*patent.ipc, *patent.cpc)
|
||||
))
|
||||
if not symbols:
|
||||
return
|
||||
|
||||
try:
|
||||
resolved = await ipc_client.resolve_symbols(symbols)
|
||||
except MissingApiKeyError:
|
||||
logger.warning("Classification enrichment skipped: Elasticsearch API key not configured.")
|
||||
return
|
||||
except ElasticsearchException as exc:
|
||||
logger.warning("Classification enrichment failed: %s", exc)
|
||||
return
|
||||
except Exception as exc:
|
||||
logger.exception("Classification enrichment failed unexpectedly: %s", exc)
|
||||
return
|
||||
|
||||
for patent in patents:
|
||||
patent.ipc_descriptions = _descriptions_for_raw_codes(patent.ipc, resolved)
|
||||
patent.cpc_descriptions = _descriptions_for_raw_codes(patent.cpc, resolved)
|
||||
|
||||
|
||||
def _filter_patents_by_name(
|
||||
patents: list[model.PatentEntry],
|
||||
first_name: str,
|
||||
last_name: str,
|
||||
) -> list[model.PatentEntry]:
|
||||
return [
|
||||
patent for patent in patents
|
||||
if any(name_matches(inventor, first_name, last_name) for inventor in patent.inventors)
|
||||
]
|
||||
|
||||
|
||||
def _deduplicate_patents(patents: list[model.PatentEntry]) -> list[model.PatentEntry]:
|
||||
seen: set[tuple[str, str, str, str]] = set()
|
||||
deduplicated: list[model.PatentEntry] = []
|
||||
|
||||
for patent in patents:
|
||||
key = _patent_dedup_key(patent)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
deduplicated.append(patent)
|
||||
|
||||
return deduplicated
|
||||
|
||||
|
||||
def _patent_dedup_key(patent: model.PatentEntry) -> tuple[str, str, str, str]:
|
||||
stage = patent.kind or patent.application_type or ""
|
||||
return (
|
||||
patent.source,
|
||||
patent.patent_id,
|
||||
patent.publication_date or "",
|
||||
stage,
|
||||
)
|
||||
|
||||
|
||||
async def _get_author(author_id: str) -> Author | None:
|
||||
short_id = author_id.replace("https://openalex.org/", "")
|
||||
result = await person_logic.search_persons(author_id=short_id)
|
||||
return result.results[0] if result.results else None
|
||||
|
||||
|
||||
def _extract_last_name(name: str | None) -> str | None:
|
||||
if not name:
|
||||
return None
|
||||
parts = name.strip().split()
|
||||
return parts[-1] if parts else None
|
||||
|
||||
|
||||
def _extract_first_name(name: str | None) -> str | None:
|
||||
if not name:
|
||||
return None
|
||||
parts = name.strip().split()
|
||||
return parts[0] if len(parts) > 1 else None
|
||||
|
||||
|
||||
async def get_all_patents(
|
||||
page: int = 0,
|
||||
size: int = 10,
|
||||
search: str | None = None,
|
||||
source: str | None = None,
|
||||
sort_by: str = "date",
|
||||
sort_direction: str = "desc",
|
||||
client: PatentSearchClient | None = None,
|
||||
ipc_client: IpcSearchClient | None = None,
|
||||
) -> model.AllPatentsResponse:
|
||||
all_patents_client = AllPatentsSearchClient()
|
||||
ipc_search_client = ipc_client or IpcSearchClient()
|
||||
|
||||
if source == "EPO":
|
||||
epo_data = await all_patents_client.search_epo(
|
||||
all_patents_client.epo_query(page, size, search, sort_direction)
|
||||
)
|
||||
patents = _parse_epo_hits(epo_data)
|
||||
total = epo_data.get("hits", {}).get("total", {}).get("value", 0)
|
||||
|
||||
elif source == "USPTO":
|
||||
uspto_data = await all_patents_client.search_uspto(
|
||||
all_patents_client.uspto_query(page, size, search, sort_direction)
|
||||
)
|
||||
patents = _parse_uspto_hits(uspto_data)
|
||||
total = uspto_data.get("hits", {}).get("total", {}).get("value", 0)
|
||||
|
||||
else:
|
||||
half = size // 2
|
||||
epo_data, uspto_data = await asyncio.gather(
|
||||
all_patents_client.search_epo(
|
||||
all_patents_client.epo_query(page, half, search, sort_direction)
|
||||
),
|
||||
all_patents_client.search_uspto(
|
||||
all_patents_client.uspto_query(page, half, search, sort_direction)
|
||||
),
|
||||
)
|
||||
patents = _parse_epo_hits(epo_data) + _parse_uspto_hits(uspto_data)
|
||||
total = (
|
||||
epo_data.get("hits", {}).get("total", {}).get("value", 0) +
|
||||
uspto_data.get("hits", {}).get("total", {}).get("value", 0)
|
||||
)
|
||||
|
||||
|
||||
await _enrich_patents_classifications(patents, ipc_search_client)
|
||||
|
||||
return model.AllPatentsResponse(
|
||||
total=total,
|
||||
page=page,
|
||||
size=size,
|
||||
patents=patents,
|
||||
)
|
||||
@@ -1,4 +1,15 @@
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
|
||||
class IpcClassification(BaseModel):
|
||||
symbol: str
|
||||
section: str | None = None
|
||||
ipc_class: str | None = Field(default=None, serialization_alias="class")
|
||||
subclass: str | None = None
|
||||
main_group: str | None = None
|
||||
subgroup: str | None = None
|
||||
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
|
||||
class PatentEntry(BaseModel):
|
||||
@@ -8,13 +19,29 @@ class PatentEntry(BaseModel):
|
||||
abstract: str | None = None
|
||||
publication_date: str | None = None
|
||||
publication_year: str | None = None
|
||||
application_number: str | None = None
|
||||
application_date: str | None = None
|
||||
kind: str | None = None # EPO only
|
||||
application_type: str | None = None # USPTO only
|
||||
number_of_claims: int | None = None # USPTO only
|
||||
status: str | None = None # USPTO only
|
||||
inventors: list[str] = Field(default_factory=list)
|
||||
assignees: list[str] = Field(default_factory=list)
|
||||
ipc: list[str] = Field(default_factory=list)
|
||||
ipc_descriptions: list[IpcClassification] = Field(default_factory=list)
|
||||
cpc: list[str] = Field(default_factory=list)
|
||||
cpc_descriptions: list[IpcClassification] = Field(default_factory=list)
|
||||
country: str | None = None
|
||||
|
||||
|
||||
class PatentsByAuthorResponse(BaseModel):
|
||||
author_id: str
|
||||
author_name: str | None = None
|
||||
patent_count: int
|
||||
patents: list[PatentEntry]
|
||||
|
||||
class AllPatentsResponse(BaseModel):
|
||||
total: int
|
||||
page: int
|
||||
size: int
|
||||
patents: list[PatentEntry]
|
||||
@@ -1,14 +1,15 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
REST API for patent matching by author.
|
||||
"""
|
||||
from fastapi import APIRouter
|
||||
from . import logic
|
||||
from . import model
|
||||
|
||||
from typing import Annotated, Optional
|
||||
from fastapi import Path
|
||||
from fastapi import Query
|
||||
router = APIRouter(prefix="/api/inse-service/authors", tags=["Patents"])
|
||||
|
||||
patents_router = APIRouter(prefix="/api/inse-service", tags=["Patents"])
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{author_id}/patents",
|
||||
@@ -18,3 +19,46 @@ router = APIRouter(prefix="/api/inse-service/authors", tags=["Patents"])
|
||||
)
|
||||
async def get_patents_by_author(author_id: str):
|
||||
return await logic.get_patents_by_author_id(author_id)
|
||||
|
||||
@patents_router.get(
|
||||
"/patents/{identifier}",
|
||||
operation_id="getPatentByIdOrTitle",
|
||||
response_model=model.PatentEntry | None,
|
||||
summary="Returns one publication by OpenAlex ID or DOI.",
|
||||
)
|
||||
async def get_patent_by_identifier(
|
||||
identifier: Annotated[
|
||||
str, Path(description="")
|
||||
],
|
||||
prefix: Annotated[
|
||||
Optional[str], Query(description="Application Prefix (EP or US)")
|
||||
] = "",
|
||||
title: Annotated[
|
||||
Optional[str], Query(description="Do we want to fallback to title search if ID and DOI dont work?")
|
||||
] = "",
|
||||
):
|
||||
return await logic.get_patent(patent_id=identifier,prefix=prefix,title=title)
|
||||
|
||||
|
||||
@patents_router.get(
|
||||
"/patents",
|
||||
operation_id="getAllPatents",
|
||||
response_model=model.AllPatentsResponse,
|
||||
summary="Get all patents with pagination and search.",
|
||||
)
|
||||
async def get_all_patents(
|
||||
page: int = 0,
|
||||
size: int = 10,
|
||||
search: str | None = None,
|
||||
source: str | None = None,
|
||||
sort_by: str = "date",
|
||||
sort_direction: str = "desc",
|
||||
):
|
||||
return await logic.get_all_patents(
|
||||
page=page,
|
||||
size=size,
|
||||
search=search,
|
||||
source=source,
|
||||
sort_by=sort_by,
|
||||
sort_direction=sort_direction,
|
||||
)
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from unittest.mock import patch, MagicMock
|
||||
from inse.model import ESIndex
|
||||
from inse.patents.elastic_search_client import (
|
||||
DEFAULT_SEARCH_SIZE,
|
||||
EPO_INDEX,
|
||||
PatentSearchClient,
|
||||
USPTO_INDEX,
|
||||
)
|
||||
|
||||
|
||||
@@ -28,22 +26,21 @@ def test_epo_query_uses_nested_search_and_name_variants():
|
||||
|
||||
|
||||
def test_uspto_index_is_3_0():
|
||||
assert USPTO_INDEX == "uspto_patents_3.0"
|
||||
assert EPO_INDEX == "epo_index_1.0"
|
||||
assert ESIndex.USPTO_INDEX == "uspto_patents_3.0"
|
||||
assert ESIndex.EPO_INDEX == "epo_index_1.0"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_search_epo_posts_to_correct_index():
|
||||
requests: list[str] = []
|
||||
captured: list[dict] = []
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
requests.append(request.url.path)
|
||||
return httpx.Response(200, json={"hits": {"hits": []}})
|
||||
def fake_search(index: str, body: dict, cluster=None):
|
||||
captured.append({"index": index, "body": body})
|
||||
return {"hits": {"hits": []}}
|
||||
|
||||
transport = httpx.MockTransport(handler)
|
||||
client = PatentSearchClient(api_key="test-key", transport=transport)
|
||||
with patch("inse.integrations.elasticsearch.search", side_effect=fake_search):
|
||||
client = PatentSearchClient(api_key="test-key")
|
||||
await client.search_epo(client.epo_query_by_inventor("Weber", "Christian"))
|
||||
|
||||
await client.search_epo(client.epo_query_by_inventor("Weber", "Christian"))
|
||||
|
||||
assert len(requests) == 1
|
||||
assert requests[0].endswith(f"/{EPO_INDEX}/_search")
|
||||
assert len(captured) == 1
|
||||
assert captured[0]["index"] == ESIndex.EPO_INDEX
|
||||
@@ -0,0 +1,129 @@
|
||||
import pytest
|
||||
|
||||
from inse.patents.ipc_lookup import (
|
||||
build_ipc_classification,
|
||||
display_ipc_symbol,
|
||||
extract_ipc_symbol,
|
||||
normalize_ipc_symbol,
|
||||
parse_ipc_symbol,
|
||||
)
|
||||
from inse.patents.model import IpcClassification
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("raw", "normalized"),
|
||||
[
|
||||
("H01L 21/02", "H01L21/02"),
|
||||
("h01l21/02", "H01L21/02"),
|
||||
("H04L 29/08", "H04L29/08"),
|
||||
],
|
||||
)
|
||||
def test_normalize_ipc_symbol(raw: str, normalized: str) -> None:
|
||||
assert normalize_ipc_symbol(raw) == normalized
|
||||
|
||||
|
||||
def test_display_ipc_symbol() -> None:
|
||||
assert display_ipc_symbol("H01L21/02") == "H01L 21/02"
|
||||
|
||||
|
||||
def test_parse_ipc_symbol_main_group() -> None:
|
||||
keys = parse_ipc_symbol("H01L 21/02")
|
||||
assert keys.section == "H"
|
||||
assert keys.ipc_class == "H01"
|
||||
assert keys.subclass == "H01L"
|
||||
assert keys.main_group == "H01L21/02"
|
||||
assert keys.subgroup is None
|
||||
|
||||
|
||||
def test_parse_ipc_symbol_subgroup() -> None:
|
||||
keys = parse_ipc_symbol("H01L 21/0262")
|
||||
assert keys.main_group == "H01L21/02"
|
||||
assert keys.subgroup == "H01L21/0262"
|
||||
|
||||
|
||||
def test_extract_ipc_symbol_from_epo_string() -> None:
|
||||
raw = "G01S 5/02 20100101AFI20140127BHEP"
|
||||
assert extract_ipc_symbol(raw) == "G01S 5/02"
|
||||
|
||||
|
||||
def test_extract_ipc_symbol_from_cpc_string() -> None:
|
||||
raw = "A61B 5/0713 20130101AFI20140127BHEP"
|
||||
assert extract_ipc_symbol(raw) == "A61B 5/0713"
|
||||
|
||||
|
||||
def test_parse_ipc_symbol_from_epo_string() -> None:
|
||||
keys = parse_ipc_symbol("G01S 5/02 20100101AFI20140127BHEP")
|
||||
assert keys.symbol == "G01S 5/02"
|
||||
assert keys.section == "G"
|
||||
assert keys.subclass == "G01S"
|
||||
assert keys.main_group == "G01S5/02"
|
||||
|
||||
|
||||
def test_extract_ipc_symbol_subclass_only() -> None:
|
||||
assert extract_ipc_symbol("H01L extra") == "H01L"
|
||||
|
||||
|
||||
def test_build_ipc_classification_uses_index_names() -> None:
|
||||
keys = parse_ipc_symbol("H01L 21/02")
|
||||
names = {
|
||||
"section": {"H": "ELECTRICITY"},
|
||||
"class": {"H01L": "SEMICONDUCTOR DEVICES"},
|
||||
"group": {"H01L21/02": "Manufacture or treatment of semiconductor devices"},
|
||||
"subgroup": {},
|
||||
}
|
||||
|
||||
result = build_ipc_classification(keys, names)
|
||||
|
||||
assert result.symbol == "H01L 21/02"
|
||||
assert result.section == "H - ELECTRICITY"
|
||||
assert result.subclass == "H01L - SEMICONDUCTOR DEVICES"
|
||||
assert result.main_group == "H01L 21/02 - Manufacture or treatment of semiconductor devices"
|
||||
|
||||
|
||||
def test_extract_ipc_symbol_from_legacy_epo_string() -> None:
|
||||
assert extract_ipc_symbol("C 07C 405/00 A") == "C07C 405/00"
|
||||
assert extract_ipc_symbol("C 07D 317/20 B") == "C07D 317/20"
|
||||
|
||||
|
||||
def test_parse_ipc_symbol_from_legacy_epo_string() -> None:
|
||||
keys = parse_ipc_symbol("C 07D 319/06 B")
|
||||
assert keys.symbol == "C07D 319/06"
|
||||
assert keys.section == "C"
|
||||
assert keys.subclass == "C07D"
|
||||
assert keys.main_group == "C07D319/06"
|
||||
|
||||
|
||||
def test_build_ipc_classification_uses_subgroup_when_only_subgroup_indexed() -> None:
|
||||
keys = parse_ipc_symbol("G02B 6/42")
|
||||
names = {
|
||||
"section": {"G": "PHYSICS"},
|
||||
"class": {"G02B": "OPTICAL ELEMENTS, SYSTEMS OR APPARATUS"},
|
||||
"group": {},
|
||||
"subgroup": {
|
||||
"G02B6/42": "Coupling light guides with opto-electronic elements",
|
||||
},
|
||||
}
|
||||
|
||||
result = build_ipc_classification(keys, names)
|
||||
|
||||
assert result.main_group is None
|
||||
assert result.subgroup == (
|
||||
"G02B 6/42 - Coupling light guides with opto-electronic elements"
|
||||
)
|
||||
|
||||
|
||||
def test_build_ipc_classification_omits_levels_without_index_names() -> None:
|
||||
keys = parse_ipc_symbol("G02B 6/44")
|
||||
result = build_ipc_classification(keys, {})
|
||||
|
||||
assert result.symbol == "G02B 6/44"
|
||||
assert result.section is None
|
||||
assert result.main_group is None
|
||||
assert result.subgroup is None
|
||||
|
||||
|
||||
def test_build_ipc_classification_falls_back_to_symbol_only() -> None:
|
||||
keys = parse_ipc_symbol("INVALID")
|
||||
result = build_ipc_classification(keys, {})
|
||||
|
||||
assert result == IpcClassification(symbol="INVALID")
|
||||
@@ -0,0 +1,50 @@
|
||||
import pytest
|
||||
|
||||
from inse.patents import model
|
||||
|
||||
|
||||
def test_patent_entry_keeps_raw_ipc_and_separate_descriptions() -> None:
|
||||
entry = model.PatentEntry(
|
||||
patent_id="US123456",
|
||||
source="USPTO",
|
||||
ipc=["H01L 21/02 20100101AFI20140127BHEP"],
|
||||
ipc_descriptions=[
|
||||
model.IpcClassification(
|
||||
symbol="H01L 21/02",
|
||||
section="H - ELECTRICITY",
|
||||
subclass="H01L - SEMICONDUCTOR DEVICES",
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
assert entry.ipc == ["H01L 21/02 20100101AFI20140127BHEP"]
|
||||
assert len(entry.ipc_descriptions) == 1
|
||||
assert entry.ipc_descriptions[0].symbol == "H01L 21/02"
|
||||
|
||||
|
||||
def test_patent_entry_ipc_defaults_to_empty_lists() -> None:
|
||||
entry = model.PatentEntry(patent_id="EP1", source="EPO")
|
||||
|
||||
assert entry.ipc == []
|
||||
assert entry.ipc_descriptions == []
|
||||
assert entry.cpc == []
|
||||
assert entry.cpc_descriptions == []
|
||||
|
||||
|
||||
def test_patent_entry_keeps_raw_cpc_and_separate_descriptions() -> None:
|
||||
entry = model.PatentEntry(
|
||||
patent_id="US123456",
|
||||
source="USPTO",
|
||||
cpc=["A61B 5/0713 20130101AFI20140127BHEP"],
|
||||
cpc_descriptions=[
|
||||
model.IpcClassification(
|
||||
symbol="A61B 5/0713",
|
||||
section="A - HUMAN NECESSITIES",
|
||||
subclass="A61B - DIAGNOSIS",
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
assert entry.cpc == ["A61B 5/0713 20130101AFI20140127BHEP"]
|
||||
assert len(entry.cpc_descriptions) == 1
|
||||
assert entry.cpc_descriptions[0].symbol == "A61B 5/0713"
|
||||
@@ -0,0 +1,61 @@
|
||||
from unittest.mock import AsyncMock, patch
|
||||
import pytest
|
||||
|
||||
from inse.patents.ipc_search_client import IPC_INDEX, IpcSearchClient
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def anyio_backend():
|
||||
return "asyncio"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_resolve_symbols_posts_to_ipc_index():
|
||||
mock_response = {
|
||||
"hits": {
|
||||
"hits": [
|
||||
{
|
||||
"_source": {
|
||||
"cpc_section_number": "H",
|
||||
"cpc_section_name": "ELECTRICITY",
|
||||
}
|
||||
},
|
||||
{
|
||||
"_source": {
|
||||
"cpc_class_number": "H01L",
|
||||
"cpc_class_name": "SEMICONDUCTOR DEVICES",
|
||||
}
|
||||
},
|
||||
{
|
||||
"_source": {
|
||||
"cpc_group_number": "H01L21/02",
|
||||
"cpc_group_name": "Manufacture or treatment of semiconductor devices",
|
||||
}
|
||||
},
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search:
|
||||
mock_search.return_value = mock_response
|
||||
client = IpcSearchClient()
|
||||
|
||||
result = await client.resolve_symbols(["H01L 21/02"])
|
||||
|
||||
assert mock_search.call_count >= 1
|
||||
_, kwargs = mock_search.call_args
|
||||
assert kwargs.get("index") == IPC_INDEX
|
||||
assert "H01L 21/02" in result
|
||||
assert result["H01L 21/02"].section == "H - ELECTRICITY"
|
||||
assert result["H01L 21/02"].subclass == "H01L - SEMICONDUCTOR DEVICES"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_resolve_symbols_does_not_crash_for_subclass_codes():
|
||||
with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search:
|
||||
mock_search.return_value = {"hits": {"hits": []}}
|
||||
client = IpcSearchClient()
|
||||
result = await client.resolve_symbols(["A61J 1/14", "C07D 319/06"])
|
||||
|
||||
assert "A61J 1/14" in result
|
||||
assert "C07D 319/06" in result
|
||||
@@ -0,0 +1,91 @@
|
||||
from inse.patents import logic, model
|
||||
|
||||
|
||||
def _uspto_patent(
|
||||
patent_id: str = "US12508845",
|
||||
publication_date: str = "20251230",
|
||||
application_type: str | None = None,
|
||||
) -> model.PatentEntry:
|
||||
return model.PatentEntry(
|
||||
patent_id=patent_id,
|
||||
source="USPTO",
|
||||
title="Vehicle pneumatic tyre and rubber mixture for a tread",
|
||||
publication_date=publication_date,
|
||||
publication_year="2025",
|
||||
application_type=application_type,
|
||||
)
|
||||
|
||||
|
||||
def _epo_patent(
|
||||
patent_id: str = "EP2867692",
|
||||
publication_date: str = "20180411",
|
||||
kind: str | None = None,
|
||||
) -> model.PatentEntry:
|
||||
return model.PatentEntry(
|
||||
patent_id=patent_id,
|
||||
source="EPO",
|
||||
title="METHOD FOR GENERATING AND USING A MAP",
|
||||
publication_date=publication_date,
|
||||
publication_year="2018",
|
||||
kind=kind,
|
||||
)
|
||||
|
||||
|
||||
def test_deduplicate_patents_removes_exact_duplicates() -> None:
|
||||
patents = [_uspto_patent(), _uspto_patent(), _uspto_patent()]
|
||||
|
||||
result = logic._deduplicate_patents(patents)
|
||||
|
||||
assert len(result) == 1
|
||||
assert result[0].patent_id == "US12508845"
|
||||
|
||||
|
||||
def test_deduplicate_patents_keeps_distinct_publication_numbers() -> None:
|
||||
patents = [_uspto_patent("US12508845"), _uspto_patent("US12303461")]
|
||||
|
||||
result = logic._deduplicate_patents(patents)
|
||||
|
||||
assert len(result) == 2
|
||||
assert [patent.patent_id for patent in result] == ["US12508845", "US12303461"]
|
||||
|
||||
|
||||
def test_deduplicate_patents_keeps_first_occurrence_of_exact_duplicate() -> None:
|
||||
first = _uspto_patent()
|
||||
first.abstract = "First abstract"
|
||||
duplicate = _uspto_patent()
|
||||
duplicate.abstract = "Second abstract"
|
||||
|
||||
result = logic._deduplicate_patents([first, duplicate])
|
||||
|
||||
assert len(result) == 1
|
||||
assert result[0].abstract == "First abstract"
|
||||
|
||||
|
||||
def test_deduplicate_patents_keeps_epo_application_and_grant_stages() -> None:
|
||||
application = _epo_patent(publication_date="20161005", kind="A1")
|
||||
grant = _epo_patent(publication_date="20180411", kind="B1")
|
||||
|
||||
result = logic._deduplicate_patents([application, grant])
|
||||
|
||||
assert len(result) == 2
|
||||
assert [patent.kind for patent in result] == ["A1", "B1"]
|
||||
|
||||
|
||||
def test_deduplicate_patents_keeps_same_patent_number_with_different_dates() -> None:
|
||||
earlier = _uspto_patent(publication_date="20241230")
|
||||
later = _uspto_patent(publication_date="20251230")
|
||||
|
||||
result = logic._deduplicate_patents([earlier, later])
|
||||
|
||||
assert len(result) == 2
|
||||
assert [patent.publication_date for patent in result] == ["20241230", "20251230"]
|
||||
|
||||
|
||||
def test_deduplicate_patents_keeps_same_patent_number_with_different_uspto_types() -> None:
|
||||
utility = _uspto_patent(application_type="utility")
|
||||
reissue = _uspto_patent(application_type="reissue")
|
||||
|
||||
result = logic._deduplicate_patents([utility, reissue])
|
||||
|
||||
assert len(result) == 2
|
||||
assert [patent.application_type for patent in result] == ["utility", "reissue"]
|
||||
@@ -9,10 +9,15 @@ import logging
|
||||
import time
|
||||
from datetime import datetime
|
||||
from typing import Optional, Callable, Any, List
|
||||
from elasticsearch import ApiError, NotFoundError
|
||||
import hashlib
|
||||
import httpx
|
||||
from fastapi import HTTPException
|
||||
from inse.exceptions import (
|
||||
NotFoundException,
|
||||
ElasticsearchException,
|
||||
ElasticsearchNotFoundException,
|
||||
ElasticsearchConnectionException,
|
||||
BadRequestException,
|
||||
)
|
||||
|
||||
from inse.model import ESIndex
|
||||
from .. import config
|
||||
@@ -35,7 +40,7 @@ logger = logging.getLogger(__name__)
|
||||
INDEX_NAME = "openalex-authors"
|
||||
UDE_INSTITUTION_ID = "https://openalex.org/I62318514" # Universität Duisburg-Essen
|
||||
|
||||
def find_ude_author_by_name(display_name: str) -> Optional[dict]:
|
||||
async def find_ude_author_by_name(display_name: str) -> Optional[dict]:
|
||||
query = {
|
||||
"_source": ["display_name"],
|
||||
"query": {
|
||||
@@ -63,7 +68,7 @@ def find_ude_author_by_name(display_name: str) -> Optional[dict]:
|
||||
}
|
||||
|
||||
try:
|
||||
data = elasticsearch.search(index=INDEX_NAME, body=query)
|
||||
data = await elasticsearch.search(index=INDEX_NAME, body=query)
|
||||
except Exception:
|
||||
logger.exception(f"UDE-Lookup für '{display_name}' fehlgeschlagen.")
|
||||
return None
|
||||
@@ -89,7 +94,7 @@ def find_ude_author_by_name(display_name: str) -> Optional[dict]:
|
||||
}
|
||||
|
||||
|
||||
def get_author_name_by_id(author_id: str) -> Optional[str]:
|
||||
async def get_author_name_by_id(author_id: str) -> Optional[str]:
|
||||
try:
|
||||
query = {
|
||||
"_source": ["id", "display_name"],
|
||||
@@ -99,7 +104,7 @@ def get_author_name_by_id(author_id: str) -> Optional[str]:
|
||||
"size": 1,
|
||||
}
|
||||
|
||||
data = elasticsearch.search(index=INDEX_NAME, body=query)
|
||||
data = await elasticsearch.search(index=INDEX_NAME, body=query)
|
||||
hits = data.get("hits", {}).get("hits", [])
|
||||
if not hits:
|
||||
return None
|
||||
@@ -109,7 +114,7 @@ def get_author_name_by_id(author_id: str) -> Optional[str]:
|
||||
return None
|
||||
|
||||
|
||||
def search_persons(
|
||||
async def search_persons(
|
||||
author_id: Optional[str] = None,
|
||||
query: Optional[str] = None,
|
||||
) -> AuthorsListResponse:
|
||||
@@ -131,7 +136,7 @@ def search_persons(
|
||||
else:
|
||||
return AuthorsListResponse(results=[], meta=Meta(count=0))
|
||||
|
||||
data = elasticsearch.search(index=ESIndex.OPENALEX_AUTHORS, query=query_)
|
||||
data = await elasticsearch.search(index=ESIndex.OPENALEX_AUTHORS, query=query_)
|
||||
|
||||
authors = []
|
||||
for hit in data.get("hits", {}).get("hits", []):
|
||||
@@ -155,7 +160,7 @@ def search_persons(
|
||||
return AuthorsListResponse(results=authors, meta=Meta(count=len(authors)))
|
||||
|
||||
|
||||
def _fetch_author_display_name(author_id: str) -> Optional[str]:
|
||||
async def _fetch_author_display_name(author_id: str) -> Optional[str]:
|
||||
|
||||
query = {
|
||||
"query_string": {
|
||||
@@ -164,7 +169,7 @@ def _fetch_author_display_name(author_id: str) -> Optional[str]:
|
||||
}
|
||||
}
|
||||
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=INDEX_NAME,
|
||||
query=query,
|
||||
source=["display_name"],
|
||||
@@ -178,7 +183,7 @@ def _fetch_author_display_name(author_id: str) -> Optional[str]:
|
||||
return hits[0].get("_source", {}).get("display_name")
|
||||
|
||||
|
||||
def _fetch_works_and_topics(author_id: str) -> tuple[list, list]:
|
||||
async def _fetch_works_and_topics(author_id: str) -> tuple[list, list]:
|
||||
|
||||
WORK_SOURCE_FIELDS = [
|
||||
"title",
|
||||
@@ -221,7 +226,7 @@ def _fetch_works_and_topics(author_id: str) -> tuple[list, list]:
|
||||
},
|
||||
}
|
||||
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=config.settings.openalex_works_search_index,
|
||||
body=body,
|
||||
)
|
||||
@@ -251,7 +256,7 @@ def _fetch_works_and_topics(author_id: str) -> tuple[list, list]:
|
||||
return works, topics
|
||||
|
||||
|
||||
def _get_publication_years_for_author(author_id: str) -> list[int]:
|
||||
async def _get_publication_years_for_author(author_id: str) -> list[int]:
|
||||
author_url = f"https://openalex.org/{author_id.strip()}"
|
||||
|
||||
body = {
|
||||
@@ -278,7 +283,7 @@ def _get_publication_years_for_author(author_id: str) -> list[int]:
|
||||
},
|
||||
}
|
||||
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=config.settings.openalex_works_search_index,
|
||||
body=body,
|
||||
)
|
||||
@@ -359,8 +364,8 @@ def _compute_career_metrics(publication_years: list[int]) -> CareerMetrics:
|
||||
)
|
||||
|
||||
|
||||
def get_career_metrics_for_author(author_id: str) -> CareerMetrics:
|
||||
publication_years = _get_publication_years_for_author(author_id)
|
||||
async def get_career_metrics_for_author(author_id: str) -> CareerMetrics:
|
||||
publication_years = await _get_publication_years_for_author(author_id)
|
||||
return _compute_career_metrics(publication_years)
|
||||
|
||||
|
||||
@@ -382,13 +387,13 @@ def _build_papers(works: list) -> list:
|
||||
return papers
|
||||
|
||||
|
||||
def get_data_for_bio(author_id: str) -> Optional[dict]:
|
||||
async def get_data_for_bio(author_id: str) -> Optional[dict]:
|
||||
|
||||
display_name = _fetch_author_display_name(author_id)
|
||||
display_name = await _fetch_author_display_name(author_id)
|
||||
if display_name is None:
|
||||
return None
|
||||
|
||||
works, top_topics = _fetch_works_and_topics(author_id)
|
||||
works, top_topics = await _fetch_works_and_topics(author_id)
|
||||
papers = _build_papers(works)
|
||||
|
||||
author_data = {
|
||||
@@ -399,9 +404,9 @@ def get_data_for_bio(author_id: str) -> Optional[dict]:
|
||||
return author_data
|
||||
|
||||
|
||||
def generate_person_bio(author_id: str, include: Optional[set[str]] = None) -> str:
|
||||
async def generate_person_bio(author_id: str, include: Optional[set[str]] = None) -> str:
|
||||
start_time = time.time()
|
||||
author_data = get_data_for_bio(author_id)
|
||||
author_data = await get_data_for_bio(author_id)
|
||||
if author_data is None:
|
||||
return "No person found."
|
||||
|
||||
@@ -430,27 +435,23 @@ def generate_person_bio(author_id: str, include: Optional[set[str]] = None) -> s
|
||||
return bio
|
||||
|
||||
|
||||
def get_person_by_id(
|
||||
async def get_person_by_id(
|
||||
author_id: str, include: Optional[str] = None
|
||||
) -> CustomAuthorsListResponse:
|
||||
source = include.split(",") if include else None
|
||||
|
||||
try:
|
||||
hit = elasticsearch.get(
|
||||
hit = await elasticsearch.get(
|
||||
index="openalex-authors",
|
||||
doc_id=author_id,
|
||||
source=source,
|
||||
)
|
||||
except NotFoundError:
|
||||
raise HTTPException(
|
||||
status_code=404, detail=f"Person with id {author_id} not found"
|
||||
)
|
||||
except ApiError as e:
|
||||
raise HTTPException(status_code=500, detail=f"Elasticsearch error: {str(e)}")
|
||||
except NotFoundException as e:
|
||||
raise NotFoundException(f"Person with id {author_id} not found") from e
|
||||
|
||||
author = util.get_persons_data(hit)
|
||||
start_time = time.time()
|
||||
career_metrics = get_career_metrics_for_author(author_id)
|
||||
career_metrics = await get_career_metrics_for_author(author_id)
|
||||
elapsed_time = time.time() - start_time
|
||||
|
||||
logger.info(
|
||||
@@ -465,14 +466,14 @@ def get_person_by_id(
|
||||
return CustomAuthorsListResponse(results=[custom_author])
|
||||
|
||||
|
||||
def search_persons_by_name(
|
||||
async def search_persons_by_name(
|
||||
author_name: str,
|
||||
limit: Optional[int] = 10,
|
||||
page_offset: Optional[int] = 0,
|
||||
include: Optional[str] = None,
|
||||
) -> AuthorsListResponse:
|
||||
if not author_name:
|
||||
raise HTTPException(status_code=400, detail="name must be provided")
|
||||
raise BadRequestException("name must be provided")
|
||||
search_query = {
|
||||
"bool": {
|
||||
"should": [
|
||||
@@ -495,7 +496,7 @@ def search_persons_by_name(
|
||||
}
|
||||
}
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index="openalex-authors",
|
||||
query=search_query,
|
||||
offset=page_offset,
|
||||
@@ -504,10 +505,8 @@ def search_persons_by_name(
|
||||
track_total_hits=True,
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=500, detail=f"Elasticsearch search failed: {str(e)}"
|
||||
)
|
||||
except ElasticsearchException as e:
|
||||
raise ElasticsearchException(f"Elasticsearch search failed: {str(e)}") from e
|
||||
total_count = response.get("hits", {}).get("total", {}).get("value", 0)
|
||||
hits = response.get("hits", {}).get("hits", [])
|
||||
|
||||
@@ -518,11 +517,11 @@ def search_persons_by_name(
|
||||
)
|
||||
|
||||
|
||||
def search_persons_autocomplete(
|
||||
async def search_persons_autocomplete(
|
||||
author_name: str, limit: Optional[int] = 5, include: Optional[str] = None
|
||||
) -> AuthorsListResponse:
|
||||
if not author_name:
|
||||
raise HTTPException(status_code=400, detail="name must be provided")
|
||||
raise BadRequestException("name must be provided")
|
||||
search_query = {
|
||||
"function_score": {
|
||||
"query": {
|
||||
@@ -555,11 +554,9 @@ def search_persons_autocomplete(
|
||||
"collapse": collapse,
|
||||
}
|
||||
try:
|
||||
response = elasticsearch.search(index="openalex-authors", body=body)
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=500, detail=f"Elasticsearch search failed: {str(e)}"
|
||||
)
|
||||
response = await elasticsearch.search(index="openalex-authors", body=body)
|
||||
except ElasticsearchException as e:
|
||||
raise ElasticsearchException(f"Elasticsearch search failed: {str(e)}") from e
|
||||
|
||||
hits = response.get("hits", {}).get("hits", [])
|
||||
|
||||
@@ -587,7 +584,7 @@ def search_persons_autocomplete(
|
||||
return AuthorsListResponse(results=persons)
|
||||
|
||||
|
||||
def search_persons_by_institution(
|
||||
async def search_persons_by_institution(
|
||||
institution_name: str,
|
||||
limit: Optional[int] = 10,
|
||||
page_offset: Optional[int] = 0,
|
||||
@@ -595,7 +592,7 @@ def search_persons_by_institution(
|
||||
) -> AuthorsListResponse:
|
||||
|
||||
if not institution_name:
|
||||
raise HTTPException(status_code=400, detail="institution_name must be provided")
|
||||
raise BadRequestException("institution_name must be provided")
|
||||
|
||||
search_query = {
|
||||
"nested": {
|
||||
@@ -614,7 +611,7 @@ def search_persons_by_institution(
|
||||
}
|
||||
}
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index="openalex-authors",
|
||||
query=search_query,
|
||||
source=include.split(",") if include else True,
|
||||
@@ -624,10 +621,8 @@ def search_persons_by_institution(
|
||||
track_total_hits=True,
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=500, detail=f"Elasticsearch search failed: {str(e)}"
|
||||
)
|
||||
except ElasticsearchException as e:
|
||||
raise ElasticsearchException(f"Elasticsearch search failed: {str(e)}") from e
|
||||
total_count = response.get("hits", {}).get("total", {}).get("value", 0)
|
||||
hits = response.get("hits", {}).get("hits", [])
|
||||
persons = [util.get_persons_data(hit) for hit in hits]
|
||||
@@ -679,7 +674,7 @@ def _enrich_author_data(author_data) -> Optional[CustomAuthor]:
|
||||
return author
|
||||
|
||||
|
||||
def advanced_search_persons(
|
||||
async def advanced_search_persons(
|
||||
query: Optional[str] = None,
|
||||
institution_name: Optional[str] = None,
|
||||
sort_by: Optional[str] = None,
|
||||
@@ -707,39 +702,20 @@ def advanced_search_persons(
|
||||
filter_mode=filter_mode,
|
||||
filter_year=filter_year,
|
||||
)
|
||||
response_dict = elasticsearch.search(
|
||||
response_dict = await elasticsearch.search(
|
||||
index=INDEX_NAME,
|
||||
body=query_body,
|
||||
)
|
||||
except httpx.HTTPStatusError as e:
|
||||
if e.response.status_code == 404:
|
||||
logger.warning(f"Elasticsearch index '{INDEX_NAME}' not found.")
|
||||
return CustomAuthorsListResponse(
|
||||
results=[], meta=Meta(count=0, page=page, per_page=page_size)
|
||||
)
|
||||
elif e.response.status_code == 400:
|
||||
logger.error(f"Elasticsearch request error: {str(e)}")
|
||||
raise HTTPException(
|
||||
status_code=400, detail=f"Elasticsearch request error: {str(e)}"
|
||||
)
|
||||
else:
|
||||
logger.error(f"Elasticsearch API error: {str(e)}")
|
||||
raise HTTPException(
|
||||
status_code=500, detail=f"Elasticsearch API error: {str(e)}"
|
||||
)
|
||||
except httpx.RequestError as e:
|
||||
logger.error(f"Elasticsearch connection/request error: {str(e)}")
|
||||
raise HTTPException(
|
||||
status_code=500, detail=f"Elasticsearch connection/request error: {str(e)}"
|
||||
except ElasticsearchNotFoundException:
|
||||
logger.warning(f"Elasticsearch index '{INDEX_NAME}' not found.")
|
||||
return CustomAuthorsListResponse(
|
||||
results=[], meta=Meta(count=0, page=page, per_page=page_size)
|
||||
)
|
||||
except Exception as e:
|
||||
except ElasticsearchException as e:
|
||||
logger.error(f"Elasticsearch search failed: {str(e)}")
|
||||
raise HTTPException(
|
||||
status_code=500, detail=f"Elasticsearch search failed: {str(e)}"
|
||||
)
|
||||
raise
|
||||
total_count = response_dict.get("hits", {}).get("total", {}).get("value", 0)
|
||||
hits = response_dict.get("hits", {}).get("hits", [])
|
||||
total_count = response_dict.get("hits", {}).get("total", {}).get("value", 0)
|
||||
|
||||
include_career_metrics = include is None or "career_metrics" in include
|
||||
results = []
|
||||
@@ -749,7 +725,7 @@ def advanced_search_persons(
|
||||
if custom_author:
|
||||
if include_career_metrics:
|
||||
start_time = time.time()
|
||||
custom_author.career_metrics = get_career_metrics_for_author(
|
||||
custom_author.career_metrics = await get_career_metrics_for_author(
|
||||
custom_author.id
|
||||
)
|
||||
elapsed_time = time.time() - start_time
|
||||
|
||||
@@ -29,7 +29,7 @@ router = APIRouter(
|
||||
summary="Searches for persons by ID or name.",
|
||||
response_model_exclude_none=True,
|
||||
)
|
||||
def search_persons(
|
||||
async def search_persons(
|
||||
author_id: Annotated[
|
||||
str, Query(description="OpenAlex author ID (e.g., A5093075883)")
|
||||
] = None,
|
||||
@@ -53,7 +53,7 @@ def search_persons(
|
||||
if include
|
||||
else None
|
||||
)
|
||||
return logic.search_persons(author_id, query)
|
||||
return await logic.search_persons(author_id, query)
|
||||
|
||||
|
||||
@router.get(
|
||||
@@ -62,7 +62,7 @@ def search_persons(
|
||||
response_model=model.PersonBio,
|
||||
summary="Generates a bio for a person by author ID.",
|
||||
)
|
||||
def generate_person_bio(
|
||||
async def generate_person_bio(
|
||||
author_id: Annotated[
|
||||
str, Query(description="OpenAlex author ID (e.g., A5093075883)")
|
||||
],
|
||||
@@ -79,7 +79,7 @@ def generate_person_bio(
|
||||
if include
|
||||
else None
|
||||
)
|
||||
bio = logic.generate_person_bio(author_id, include_set)
|
||||
bio = await logic.generate_person_bio(author_id, include_set)
|
||||
return model.PersonBio(bio=bio)
|
||||
|
||||
@router.get(
|
||||
@@ -89,7 +89,7 @@ def generate_person_bio(
|
||||
summary="Searches for person by ID.",
|
||||
tags=["Persons"],
|
||||
)
|
||||
def get_person_by_id(
|
||||
async def get_person_by_id(
|
||||
id: Annotated[
|
||||
str, Path(description="OpenAlex author ID", examples=["A5093075883"])
|
||||
],
|
||||
@@ -104,7 +104,7 @@ def get_person_by_id(
|
||||
),
|
||||
] = None,
|
||||
):
|
||||
return logic.get_person_by_id(author_id=id, include=include)
|
||||
return await logic.get_person_by_id(author_id=id, include=include)
|
||||
|
||||
|
||||
@router.get(
|
||||
@@ -114,7 +114,7 @@ def get_person_by_id(
|
||||
summary="Searches for person by name.",
|
||||
tags=["Persons"],
|
||||
)
|
||||
def search_persons_by_name(
|
||||
async def search_persons_by_name(
|
||||
author_name: Annotated[str, Query(description="Authors name (e.g., Arman Arzani)")],
|
||||
include: Annotated[
|
||||
Optional[str],
|
||||
@@ -129,24 +129,25 @@ def search_persons_by_name(
|
||||
limit:Annotated[Optional[int], Query(description=("Limit of search page results"),example ="2")]= None,
|
||||
page_offset : Annotated[Optional[int], Query(description=("Offset of the result page"),example="2")] = None,
|
||||
):
|
||||
return logic.search_persons_by_name(author_name=author_name, include=include,page_offset=page_offset,limit=limit)
|
||||
return await logic.search_persons_by_name(author_name=author_name, include=include, page_offset=page_offset, limit=limit)
|
||||
|
||||
|
||||
@router.get(
|
||||
'/persons/autocomplete',
|
||||
operation_id='searchPersonsAutocomplete',
|
||||
response_model=AuthorsListResponse,
|
||||
summary='Searches for person by name.',
|
||||
tags=[ 'Persons' ])
|
||||
def search_persons_autocomplete(
|
||||
tags=['Persons'])
|
||||
async def search_persons_autocomplete(
|
||||
author_name: Annotated[str, Query(description="Authors name (e.g., Arman Arzani)")],
|
||||
include : Annotated[Optional[str], Query(
|
||||
description=(
|
||||
"Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, "
|
||||
"last_known_institutions, ..."
|
||||
),
|
||||
example="topics_full,topic_share"
|
||||
)]):
|
||||
return logic.search_persons_autocomplete(author_name=author_name,include=include)
|
||||
description=(
|
||||
"Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, "
|
||||
"last_known_institutions, ..."
|
||||
),
|
||||
example="topics_full,topic_share"
|
||||
)]):
|
||||
return await logic.search_persons_autocomplete(author_name=author_name, include=include)
|
||||
|
||||
|
||||
@router.get(
|
||||
@@ -156,7 +157,7 @@ def search_persons_autocomplete(
|
||||
summary="Searches for persons by institution name.",
|
||||
tags=["Persons"],
|
||||
)
|
||||
def search_persons_by_institution(
|
||||
async def search_persons_by_institution(
|
||||
institution_name: Annotated[
|
||||
str, Query(description="Institution name (e.g., MIT, Oxford University)")
|
||||
],
|
||||
@@ -173,7 +174,8 @@ def search_persons_by_institution(
|
||||
limit:Annotated[Optional[int], Query(description=("Limit of search page results"),example ="2")]= None,
|
||||
page_offset : Annotated[Optional[int], Query(description=("Offset of the result page"),example="2")] = None,
|
||||
):
|
||||
return logic.search_persons_by_institution(institution_name, include=include,page_offset=page_offset,limit=limit)
|
||||
return await logic.search_persons_by_institution(institution_name, include=include, page_offset=page_offset, limit=limit)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/persons/search-list",
|
||||
@@ -183,7 +185,7 @@ def search_persons_by_institution(
|
||||
response_model_exclude_none=True,
|
||||
tags=["Persons"],
|
||||
)
|
||||
def search_persons_list(
|
||||
async def search_persons_list(
|
||||
query: Annotated[
|
||||
Optional[str], Query(description="Search query (e.g., Arman AND Arzani)")
|
||||
] = None,
|
||||
@@ -227,7 +229,7 @@ def search_persons_list(
|
||||
if include
|
||||
else None
|
||||
)
|
||||
return logic.advanced_search_persons(
|
||||
return await logic.advanced_search_persons(
|
||||
query=query,
|
||||
institution_name=institution_name,
|
||||
sort_by=sort_by,
|
||||
|
||||
@@ -0,0 +1,281 @@
|
||||
import logging
|
||||
import asyncio
|
||||
from typing import Any, Dict, List, Optional, Union
|
||||
|
||||
from inse.config import get_settings
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster, ESIndex
|
||||
|
||||
# Import base models
|
||||
from inse.models.cordis_eu_project import CordisEuProject
|
||||
|
||||
# Import FP7 models
|
||||
from inse.models.projects_eu_cordis.fp7.fp7_project import Fp7Project
|
||||
from inse.models.projects_eu_cordis.fp7.fp7_organization import Fp7Organization
|
||||
from inse.models.projects_eu_cordis.fp7.fp7_publication import Fp7Publication
|
||||
from inse.models.projects_eu_cordis.fp7.fp7_project_ipr import Fp7ProjectIPR
|
||||
from inse.models.projects_eu_cordis.fp7.fp7_report_summary import Fp7ReportSummary
|
||||
from inse.models.projects_eu_cordis.fp7.fp7_topic import Fp7Topic
|
||||
from inse.models.projects_eu_cordis.fp7.fp7_web_link import Fp7WebLink
|
||||
from inse.models.projects_eu_cordis.fp7.fp7_eurosci_voc import Fp7EurosciVoc
|
||||
from inse.models.projects_eu_cordis.fp7.fp7_legal_basis import Fp7LegalBasis
|
||||
from inse.models.projects_eu_cordis.fp7.fp7_project_details import Fp7ProjectDetails
|
||||
|
||||
# Import H2020 models
|
||||
from inse.models.projects_eu_cordis.horizon2020.h2020_project import H2020Project
|
||||
from inse.models.projects_eu_cordis.horizon2020.h2020_organization import H2020Organization
|
||||
from inse.models.projects_eu_cordis.horizon2020.h2020_publication import H2020Publication
|
||||
from inse.models.projects_eu_cordis.horizon2020.h2020_deliverable import H2020Deliverable
|
||||
from inse.models.projects_eu_cordis.horizon2020.h2020_report_summary import H2020ReportSummary
|
||||
from inse.models.projects_eu_cordis.horizon2020.h2020_topic import H2020Topic
|
||||
from inse.models.projects_eu_cordis.horizon2020.h2020_web_link import H2020WebLink
|
||||
from inse.models.projects_eu_cordis.horizon2020.h2020_eurosci_voc import H2020EurosciVoc
|
||||
from inse.models.projects_eu_cordis.horizon2020.h2020_legal_basis import H2020LegalBasis
|
||||
from inse.models.projects_eu_cordis.horizon2020.h2020_erc_pi import H2020ErcPI
|
||||
from inse.models.projects_eu_cordis.horizon2020.h2020_project_details import H2020ProjectDetails
|
||||
|
||||
# Import Horizon Europe models
|
||||
from inse.models.projects_eu_cordis.horizon_europe.heu_project import HEUProject
|
||||
from inse.models.projects_eu_cordis.horizon_europe.heu_organization import HEUOrganization
|
||||
from inse.models.projects_eu_cordis.horizon_europe.heu_publication import HEUPublication
|
||||
from inse.models.projects_eu_cordis.horizon_europe.heu_deliverable import HEUDeliverable
|
||||
from inse.models.projects_eu_cordis.horizon_europe.heu_report_summary import HEUReportSummary
|
||||
from inse.models.projects_eu_cordis.horizon_europe.heu_topic import HEUTopic
|
||||
from inse.models.projects_eu_cordis.horizon_europe.heu_web_link import HEUWebLink
|
||||
from inse.models.projects_eu_cordis.horizon_europe.heu_eurosci_voc import HEUEurosciVoc
|
||||
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
|
||||
|
||||
settings = get_settings()
|
||||
logger = logging.getLogger(__name__)
|
||||
logger.setLevel(settings.logging_level)
|
||||
|
||||
# Entity config
|
||||
_FP7_ENTITY_CONFIGS = [
|
||||
{"key": "organizations", "index_pattern": ESIndex.CORDIS_EU_FP7_ORGANIZATIONS, "model_class": Fp7Organization},
|
||||
{"key": "publications", "index_pattern": ESIndex.CORDIS_EU_FP7_PUBLICATIONS, "model_class": Fp7Publication},
|
||||
{"key": "iprs", "index_pattern": ESIndex.CORDIS_EU_FP7_PROJECT_IPRS, "model_class": Fp7ProjectIPR},
|
||||
{"key": "report_summaries", "index_pattern": ESIndex.CORDIS_EU_FP7_REPORT_SUMMARIES, "model_class": Fp7ReportSummary},
|
||||
{"key": "topics_list", "index_pattern": ESIndex.CORDIS_EU_FP7_TOPICS, "model_class": Fp7Topic},
|
||||
{"key": "web_links", "index_pattern": ESIndex.CORDIS_EU_FP7_WEB_LINKS, "model_class": Fp7WebLink},
|
||||
{"key": "eurosci_voc", "index_pattern": ESIndex.CORDIS_EU_FP7_EUROSCIVOC, "model_class": Fp7EurosciVoc},
|
||||
{"key": "legal_basis_list", "index_pattern": ESIndex.CORDIS_EU_FP7_LEGAL_BASIS, "model_class": Fp7LegalBasis},
|
||||
]
|
||||
|
||||
_H2020_ENTITY_CONFIGS = [
|
||||
{"key": "organizations", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_ORGANIZATIONS, "model_class": H2020Organization},
|
||||
{"key": "publications", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_PUBLICATIONS, "model_class": H2020Publication},
|
||||
{"key": "deliverables", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_DELIVERABLES, "model_class": H2020Deliverable},
|
||||
{"key": "report_summaries", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_REPORT_SUMMARIES, "model_class": H2020ReportSummary},
|
||||
{"key": "topics_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_TOPICS, "model_class": H2020Topic},
|
||||
{"key": "web_links", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_WEB_LINKS, "model_class": H2020WebLink},
|
||||
{"key": "eurosci_voc", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_EUROSCIVOC, "model_class": H2020EurosciVoc},
|
||||
{"key": "legal_basis_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_LEGAL_BASIS, "model_class": H2020LegalBasis},
|
||||
{"key": "erc_principal_investigators", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_ERC_PIS, "model_class": H2020ErcPI},
|
||||
]
|
||||
|
||||
_HEU_ENTITY_CONFIGS = [
|
||||
{"key": "organizations", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS, "model_class": HEUOrganization},
|
||||
{"key": "publications", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_PUBLICATIONS, "model_class": HEUPublication},
|
||||
{"key": "deliverables", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_DELIVERABLES, "model_class": HEUDeliverable},
|
||||
{"key": "report_summaries", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_REPORT_SUMMARIES, "model_class": HEUReportSummary},
|
||||
{"key": "topics_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_TOPICS, "model_class": HEUTopic},
|
||||
{"key": "web_links", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_WEB_LINKS, "model_class": HEUWebLink},
|
||||
{"key": "eurosci_voc", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_EUROSCIVOC, "model_class": HEUEurosciVoc},
|
||||
{"key": "legal_basis_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_LEGAL_BASIS, "model_class": HEULegalBasis},
|
||||
]
|
||||
|
||||
async def get_enriched_cordis_project_by_id(
|
||||
project_id: str,
|
||||
) -> Optional[Union[Fp7ProjectDetails, H2020ProjectDetails, HEUProjectDetails]]:
|
||||
"""
|
||||
Fetches and enriches a single Cordis EU project by its ID across all programme types.
|
||||
|
||||
Args:
|
||||
project_id: The project ID to fetch.
|
||||
|
||||
Returns:
|
||||
The enriched detailed project model, or None if not found.
|
||||
"""
|
||||
if not project_id:
|
||||
return None
|
||||
|
||||
query = {"bool": {"filter": [{"term": {"id": project_id}}]}}
|
||||
|
||||
response = await elasticsearch.search(
|
||||
query=query,
|
||||
index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
|
||||
cluster=ESCluster.INSE,
|
||||
size=1,
|
||||
)
|
||||
|
||||
hits = response.get("hits", {}).get("hits", [])
|
||||
if not hits:
|
||||
logger.info(f"No project found with ID: {project_id}")
|
||||
return None
|
||||
|
||||
hit = hits[0]
|
||||
index = hit.get("_index", "")
|
||||
source = hit.get("_source", {})
|
||||
|
||||
program_type = _determine_program_type_from_index(index)
|
||||
|
||||
enrichers = {
|
||||
"fp7": _enrich_fp7_project,
|
||||
"h2020": _enrich_h2020_project,
|
||||
"heu": _enrich_heu_project,
|
||||
}
|
||||
|
||||
enricher = enrichers.get(program_type)
|
||||
if enricher is None:
|
||||
logger.warning(f"Unknown programme type for index: {index}")
|
||||
return CordisEuProject.model_validate(source)
|
||||
|
||||
return await enricher(project_id, source)
|
||||
|
||||
# helpers
|
||||
def _determine_program_type_from_index(index: str) -> str:
|
||||
"""Determines the programme type from the Elasticsearch index name."""
|
||||
index_lower = index.lower()
|
||||
if "fp7" in index_lower:
|
||||
return "fp7"
|
||||
if "horizon_2020" in index_lower:
|
||||
return "h2020"
|
||||
if "heu" in index_lower or "horizon_europe" in index_lower:
|
||||
return "heu"
|
||||
return "unknown"
|
||||
|
||||
|
||||
async def _fetch_related_entities_parallel(
|
||||
project_id: str,
|
||||
entity_configs: List[Dict[str, Any]],
|
||||
) -> Dict[str, List[Any]]:
|
||||
"""
|
||||
Fetches all related entity types for a project in parallel.
|
||||
|
||||
Args:
|
||||
project_id: The project ID to fetch entities for.
|
||||
entity_configs: List of dicts with keys 'key', 'index_pattern', 'model_class'.
|
||||
|
||||
Returns:
|
||||
Dictionary mapping each config 'key' to a list of validated entities.
|
||||
"""
|
||||
async def _fetch_one(config: Dict[str, Any]):
|
||||
entities = await _fetch_related_entities(
|
||||
project_ids=[project_id],
|
||||
index_pattern=config["index_pattern"],
|
||||
model_class=config["model_class"],
|
||||
)
|
||||
return config["key"], entities.get(project_id, [])
|
||||
|
||||
tasks = [_fetch_one(cfg) for cfg in entity_configs]
|
||||
completed = await asyncio.gather(*tasks, return_exceptions=True)
|
||||
|
||||
results: Dict[str, List[Any]] = {}
|
||||
for cfg, res in zip(entity_configs, completed):
|
||||
key = cfg["key"]
|
||||
if isinstance(res, Exception):
|
||||
logger.error(f"Parallel fetch failed for '{key}': {res}")
|
||||
results[key] = []
|
||||
else:
|
||||
key_name, data = res
|
||||
results[key_name] = data
|
||||
|
||||
return results
|
||||
|
||||
|
||||
async def _fetch_related_entities(
|
||||
project_ids: List[str],
|
||||
index_pattern: str,
|
||||
model_class: Any,
|
||||
) -> Dict[str, List[Any]]:
|
||||
"""
|
||||
Fetches and groups related entities from Elasticsearch by project ID.
|
||||
|
||||
Args:
|
||||
project_ids: List of project IDs to fetch entities for.
|
||||
index_pattern: The index pattern to search (supports wildcards).
|
||||
model_class: The Pydantic model class to validate against.
|
||||
|
||||
Returns:
|
||||
Dictionary mapping project IDs to lists of validated entities.
|
||||
"""
|
||||
query = {"bool": {"filter": [{"terms": {"projectID": project_ids}}]}}
|
||||
|
||||
try:
|
||||
response = await elasticsearch.search(
|
||||
query=query,
|
||||
index=index_pattern,
|
||||
cluster=ESCluster.INSE,
|
||||
size=10000,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to fetch from {index_pattern}: {e}")
|
||||
return {}
|
||||
|
||||
grouped: Dict[str, List[Any]] = {}
|
||||
|
||||
for hit in response.get("hits", {}).get("hits", []):
|
||||
source = hit.get("_source", {})
|
||||
project_id = source.get("projectID")
|
||||
|
||||
if not project_id:
|
||||
continue
|
||||
|
||||
grouped.setdefault(project_id, [])
|
||||
|
||||
try:
|
||||
entity = model_class.model_validate(source)
|
||||
grouped[project_id].append(entity)
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to validate {model_class.__name__} for project {project_id}: {e}")
|
||||
|
||||
return grouped
|
||||
|
||||
|
||||
async def _enrich_fp7_project(
|
||||
project_id: str,
|
||||
project_source: Dict[str, Any],
|
||||
) -> Optional[Fp7ProjectDetails]:
|
||||
"""Enriches a single FP7 project with all related data."""
|
||||
try:
|
||||
project = Fp7Project.model_validate(project_source)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to validate FP7 project {project_id}: {e}")
|
||||
return None
|
||||
|
||||
related = await _fetch_related_entities_parallel(project_id, _FP7_ENTITY_CONFIGS)
|
||||
|
||||
return Fp7ProjectDetails.from_project_with_relations(project=project, **related)
|
||||
|
||||
|
||||
async def _enrich_h2020_project(
|
||||
project_id: str,
|
||||
project_source: Dict[str, Any],
|
||||
) -> Optional[H2020ProjectDetails]:
|
||||
"""Enriches a single H2020 project with all related data."""
|
||||
try:
|
||||
project = H2020Project.model_validate(project_source)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to validate H2020 project {project_id}: {e}")
|
||||
return None
|
||||
|
||||
related = await _fetch_related_entities_parallel(project_id, _H2020_ENTITY_CONFIGS)
|
||||
|
||||
return H2020ProjectDetails.from_project_with_relations(project=project, **related)
|
||||
|
||||
|
||||
async def _enrich_heu_project(
|
||||
project_id: str,
|
||||
project_source: Dict[str, Any],
|
||||
) -> Optional[HEUProjectDetails]:
|
||||
"""Enriches a single Horizon Europe project with all related data."""
|
||||
try:
|
||||
project = HEUProject.model_validate(project_source)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to validate Horizon Europe project {project_id}: {e}")
|
||||
return None
|
||||
|
||||
related = await _fetch_related_entities_parallel(project_id, _HEU_ENTITY_CONFIGS)
|
||||
|
||||
return HEUProjectDetails.from_project_with_relations(project=project, **related)
|
||||
@@ -9,7 +9,10 @@ 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
|
||||
from inse.models.projects_eu_cordis.fp7.fp7_project_details import Fp7ProjectDetails
|
||||
from typing import Union
|
||||
|
||||
class ProjectType(StrEnum):
|
||||
BUND = "bund"
|
||||
@@ -164,7 +167,25 @@ class CordisEuProjectPage(Page):
|
||||
default_factory=list, description="The CORDIS EU projects on this page."
|
||||
)
|
||||
|
||||
|
||||
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.",
|
||||
|
||||
@@ -3,7 +3,7 @@ import logging
|
||||
from typing import Any, Dict, List, Optional, Set, Tuple
|
||||
|
||||
import httpx
|
||||
|
||||
import urllib
|
||||
from inse.config import get_settings
|
||||
from inse.models.bund_project import BundProject
|
||||
from inse.projects.model import (
|
||||
@@ -22,14 +22,16 @@ from inse.projects.model import (
|
||||
ProjectsSortBy,
|
||||
SortDirection,
|
||||
)
|
||||
|
||||
from inse.projects.eu_cordis_projects_enrichment_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 typing import Union
|
||||
settings = get_settings()
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -99,7 +101,7 @@ DFG_PERSON_FIELDS: List[str] = [
|
||||
# BUND
|
||||
|
||||
|
||||
def search_bund_projects(
|
||||
async def search_bund_projects(
|
||||
filter_properties: ProjectsFilteringProperties,
|
||||
institution_names: List[str] = [],
|
||||
) -> BundProjectPage:
|
||||
@@ -158,7 +160,7 @@ def search_bund_projects(
|
||||
}
|
||||
]
|
||||
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.PROJECTS_BUND_V1,
|
||||
query=query,
|
||||
sort=sort,
|
||||
@@ -192,8 +194,8 @@ def _complete_response_to_bund_project_page(
|
||||
return BundProjectPage(elements=elements, total=total_hits, page=page, size=size)
|
||||
|
||||
|
||||
def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails]:
|
||||
"""Fetches the details of a single Bund project based on its project ID.
|
||||
async def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails]:
|
||||
"""Decodes project_id and fetches the details of a single Bund project based on its project ID.
|
||||
|
||||
Args:
|
||||
project_id (str): The ID of the project to fetch.
|
||||
@@ -201,9 +203,11 @@ def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails]:
|
||||
Returns:
|
||||
Optional[BundProjectDetails]: The details of the project if found, otherwise None.
|
||||
"""
|
||||
query = {"term": {"Förderkennzeichen.keyword": {"value": project_id}}}
|
||||
|
||||
decoded_id = urllib.parse.unquote(project_id)
|
||||
query = {"term": {"Förderkennzeichen.keyword": {"value": decoded_id}}}
|
||||
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.PROJECTS_BUND_V1,
|
||||
query=query,
|
||||
size=1,
|
||||
@@ -220,7 +224,7 @@ def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails]:
|
||||
# EU
|
||||
|
||||
|
||||
def get_eu_organization_project_contributions(
|
||||
async def get_eu_organization_project_contributions(
|
||||
organization_names: List[str],
|
||||
projects_filtering_properties: ProjectsFilteringProperties,
|
||||
) -> EuOrganizationProjectSummaryPage:
|
||||
@@ -237,11 +241,11 @@ def get_eu_organization_project_contributions(
|
||||
# For FUNDING_AMOUNT before on the organization project contributions
|
||||
# For the rest after the contributions are known on the real projects
|
||||
|
||||
organization_project_contributions = get_eu_organization_contributions(
|
||||
organization_project_contributions = await get_eu_organization_contributions(
|
||||
organization_names=organization_names,
|
||||
)
|
||||
|
||||
total_projects, projects = get_eu_organization_projects(
|
||||
total_projects, projects = await get_eu_organization_projects(
|
||||
project_contributions=list(organization_project_contributions.values()),
|
||||
projects_filtering_properties=projects_filtering_properties,
|
||||
)
|
||||
@@ -267,7 +271,7 @@ def get_eu_organization_project_contributions(
|
||||
)
|
||||
|
||||
|
||||
def get_eu_organization_contributions(
|
||||
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.
|
||||
@@ -289,7 +293,7 @@ def get_eu_organization_contributions(
|
||||
}
|
||||
}
|
||||
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD,
|
||||
cluster=ESCluster.INSE,
|
||||
source=source,
|
||||
@@ -339,7 +343,7 @@ def _process_organization_project_contributions(
|
||||
return project_contributions
|
||||
|
||||
|
||||
def get_eu_organization_projects(
|
||||
async def get_eu_organization_projects(
|
||||
project_contributions: List[EuOrganizationShort],
|
||||
projects_filtering_properties: ProjectsFilteringProperties,
|
||||
) -> Tuple[int, Dict[str, EuProjectShort]]:
|
||||
@@ -384,7 +388,7 @@ def get_eu_organization_projects(
|
||||
|
||||
# Project contributions have been filtered before based on ecContribution
|
||||
if projects_filtering_properties.sort_by == ProjectsSortBy.FUNDING_AMOUNT:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
|
||||
cluster=ESCluster.INSE,
|
||||
source=source,
|
||||
@@ -392,7 +396,7 @@ def get_eu_organization_projects(
|
||||
size=10000,
|
||||
)
|
||||
else:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
|
||||
cluster=ESCluster.INSE,
|
||||
source=source,
|
||||
@@ -492,7 +496,7 @@ def _get_raw_doi(doi: str) -> str:
|
||||
return doi
|
||||
|
||||
|
||||
def get_cordis_eu_publications_by_dois(dois: List[str]):
|
||||
async def get_cordis_eu_publications_by_dois(dois: List[str]):
|
||||
"""Retrieves Cordis EU publications associated with the given list of DOIs.
|
||||
|
||||
Args:
|
||||
@@ -504,7 +508,7 @@ def get_cordis_eu_publications_by_dois(dois: List[str]):
|
||||
raw_dois = [_get_raw_doi(doi) for doi in dois]
|
||||
query = {"bool": {"filter": [{"terms": {"qaProcessedDoi": raw_dois}}]}}
|
||||
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
query=query,
|
||||
index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD,
|
||||
cluster=ESCluster.INSE,
|
||||
@@ -515,7 +519,7 @@ def get_cordis_eu_publications_by_dois(dois: List[str]):
|
||||
return response
|
||||
|
||||
|
||||
def get_cordis_eu_project_ids_by_dois(dois: List[str]) -> List[str]:
|
||||
async def get_cordis_eu_project_ids_by_dois(dois: List[str]) -> List[str]:
|
||||
"""Retrieves the project IDs of Cordis EU projects associated with the given list of DOIs.
|
||||
|
||||
Args:
|
||||
@@ -524,7 +528,7 @@ def get_cordis_eu_project_ids_by_dois(dois: List[str]) -> List[str]:
|
||||
Returns:
|
||||
List[str]: The list of project IDs.
|
||||
"""
|
||||
response = get_cordis_eu_publications_by_dois(dois=dois)
|
||||
response = await get_cordis_eu_publications_by_dois(dois=dois)
|
||||
hits_block = response.get("hits", {})
|
||||
project_ids = set()
|
||||
for hit in hits_block.get("hits", []):
|
||||
@@ -535,12 +539,12 @@ def get_cordis_eu_project_ids_by_dois(dois: List[str]) -> List[str]:
|
||||
return list(project_ids)
|
||||
|
||||
|
||||
def get_cordis_eu_projects_by_project_ids(
|
||||
async def get_cordis_eu_projects_by_project_ids(
|
||||
project_ids: List[str],
|
||||
) -> CordisEuProjectPage:
|
||||
query = {"bool": {"filter": [{"terms": {"id": project_ids}}]}}
|
||||
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
query=query,
|
||||
index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
|
||||
cluster=ESCluster.INSE,
|
||||
@@ -557,10 +561,26 @@ def get_cordis_eu_projects_by_project_ids(
|
||||
)
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
def search_dfg_projects(
|
||||
async def search_dfg_projects(
|
||||
page: int,
|
||||
size: int,
|
||||
names: Optional[List[str]] = None,
|
||||
@@ -730,7 +750,7 @@ def search_dfg_projects(
|
||||
|
||||
body["sort"] = [sort_config]
|
||||
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.PROJECTS_DFG_ALL,
|
||||
body=body,
|
||||
)
|
||||
@@ -756,7 +776,7 @@ def _complete_response_to_dfg_project_page(
|
||||
return DfgProjectPage(elements=elements, total=total_hits, page=page, size=size)
|
||||
|
||||
|
||||
def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]:
|
||||
async def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]:
|
||||
"""Fetches the details of a single DFG project based on its project ID.
|
||||
|
||||
Args:
|
||||
@@ -767,7 +787,7 @@ def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]:
|
||||
"""
|
||||
query = {"ids": {"values": [project_id]}}
|
||||
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.PROJECTS_DFG_ALL,
|
||||
query=query,
|
||||
size=1,
|
||||
@@ -784,7 +804,7 @@ def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]:
|
||||
# All
|
||||
|
||||
|
||||
def search_all_projects(
|
||||
async def search_all_projects(
|
||||
projects_filtering_properties: ProjectsFilteringProperties,
|
||||
selected_project_types: Optional[Set[ProjectType]] = None,
|
||||
) -> FundingProjectPage:
|
||||
@@ -862,7 +882,7 @@ def search_all_projects(
|
||||
size = projects_filtering_properties.size
|
||||
page = projects_filtering_properties.page
|
||||
offset = page * size
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=index,
|
||||
size=size,
|
||||
offset=offset,
|
||||
|
||||
@@ -15,6 +15,7 @@ from inse.projects.model import (
|
||||
ProjectsFilteringProperties,
|
||||
ProjectsSortBy,
|
||||
SortDirection,
|
||||
EuCordisProjectResponse
|
||||
)
|
||||
from inse.models.dfg_project_details import DfgProjectDetails
|
||||
from inse.models.bund_project_details import BundProjectDetails
|
||||
@@ -26,6 +27,11 @@ from inse.institutions.institutions_search_client import (
|
||||
)
|
||||
from inse.institutions.router import get_institutions_search_client
|
||||
|
||||
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 typing import Union
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/api/projects", tags=[Tags.PROJECTS])
|
||||
@@ -45,13 +51,13 @@ router = APIRouter(prefix="/api/projects", tags=[Tags.PROJECTS])
|
||||
},
|
||||
response_model_by_alias=False,
|
||||
)
|
||||
def get_eu_projects_for_author(
|
||||
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 projects_service.search_cordis_eu_projects_for_author_id(
|
||||
return await projects_service.search_cordis_eu_projects_for_author_id(
|
||||
raw_oa_author_id=raw_oa_author_id,
|
||||
)
|
||||
|
||||
@@ -79,7 +85,7 @@ async def search_bund_projects(
|
||||
Body(description="The filtering properties for the projects search."),
|
||||
],
|
||||
) -> BundProjectPage:
|
||||
return projects_service.search_bund_projects(
|
||||
return await projects_service.search_bund_projects(
|
||||
institutions_search_client=institutions_search_client,
|
||||
filtering_properties=filtering_properties,
|
||||
)
|
||||
@@ -99,11 +105,11 @@ async def search_bund_projects(
|
||||
},
|
||||
response_model_by_alias=False,
|
||||
)
|
||||
def get_single_dfg_project(
|
||||
async def get_single_dfg_project(
|
||||
id: Annotated[str, Path(description="The ID of the DFG project to retrieve.")],
|
||||
) -> DfgProjectDetails:
|
||||
logger.debug(f"Received request to get single DFG project for id={id}")
|
||||
return projects_service.get_single_dfg_project(
|
||||
return await projects_service.get_single_dfg_project(
|
||||
project_id=id,
|
||||
)
|
||||
|
||||
@@ -122,15 +128,93 @@ def get_single_dfg_project(
|
||||
},
|
||||
response_model_by_alias=False,
|
||||
)
|
||||
def get_single_bund_project(
|
||||
async def get_single_bund_project(
|
||||
id: Annotated[str, Path(description="The ID of the BUND project to retrieve.")],
|
||||
) -> BundProjectDetails:
|
||||
logger.debug(f"Received request to get single BUND project for id={id}")
|
||||
return projects_service.get_single_bund_project(
|
||||
return await projects_service.get_single_bund_project(
|
||||
project_id=id,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/eu/{id}",
|
||||
summary="Get a single EU Cordis project.",
|
||||
description="Returns a single EU Cordis project based on its ID.",
|
||||
operation_id="getSingleEuCordisProject",
|
||||
responses={
|
||||
status.HTTP_200_OK: {
|
||||
"description": "Successful Response",
|
||||
"model": EuCordisProjectResponse,
|
||||
},
|
||||
status.HTTP_404_NOT_FOUND: {
|
||||
"description": "Project not found",
|
||||
"model": EuCordisProjectResponse
|
||||
},
|
||||
status.HTTP_500_INTERNAL_SERVER_ERROR: {
|
||||
"description": "Internal server error",
|
||||
"model": EuCordisProjectResponse
|
||||
}
|
||||
},
|
||||
)
|
||||
async def get_single_eu_cordis_project(
|
||||
id: Annotated[str, Path(description="The ID of the EU Cordis project to retrieve.")],
|
||||
) -> EuCordisProjectResponse:
|
||||
"""
|
||||
Get a single EU Cordis project by ID.
|
||||
Returns a wrapper response containing the project data or error information.
|
||||
"""
|
||||
logger.debug(f"Received request to get single EU Cordis project for id={id}")
|
||||
|
||||
try:
|
||||
# Get the project from the service
|
||||
project = await projects_service.get_single_eu_cordis_project(project_id=id)
|
||||
|
||||
# Check if project exists
|
||||
if project is None:
|
||||
logger.warning(f"Project with ID {id} not found")
|
||||
return EuCordisProjectResponse(
|
||||
success=False,
|
||||
project_type=None,
|
||||
eu_project_data=None,
|
||||
error=f"Project with ID {id} not found"
|
||||
)
|
||||
|
||||
# Determine the project type
|
||||
if isinstance(project, Fp7ProjectDetails):
|
||||
project_type = "fp7"
|
||||
elif isinstance(project, H2020ProjectDetails):
|
||||
project_type = "h2020"
|
||||
elif isinstance(project, HEUProjectDetails):
|
||||
project_type = "heu"
|
||||
else:
|
||||
# Unknown project type - maybe it's the base CordisEuProject
|
||||
logger.warning(f"Unknown project type for ID {id}: {type(project)}")
|
||||
return EuCordisProjectResponse(
|
||||
success=False,
|
||||
project_type=None,
|
||||
eu_project_data=None,
|
||||
error=f"Unknown project type for ID {id}"
|
||||
)
|
||||
|
||||
# Return success with the project data
|
||||
return EuCordisProjectResponse(
|
||||
success=True,
|
||||
project_type=project_type,
|
||||
eu_project_data=project,
|
||||
error=None
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error retrieving project with ID {id}: {str(e)}", exc_info=True)
|
||||
return EuCordisProjectResponse(
|
||||
success=False,
|
||||
project_type=None,
|
||||
data=None,
|
||||
error=f"Internal server error: {str(e)}"
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/institution/bund/funding-over-time",
|
||||
summary="Get funding over time for bund projects.",
|
||||
@@ -145,7 +229,7 @@ def get_single_bund_project(
|
||||
},
|
||||
response_model_by_alias=False,
|
||||
)
|
||||
def get_institution_bund_projects_funding_over_time(
|
||||
async def get_institution_bund_projects_funding_over_time(
|
||||
institutions_search_client: Annotated[
|
||||
InstitutionsSearchClient, Depends(get_institutions_search_client)
|
||||
],
|
||||
@@ -153,7 +237,7 @@ def get_institution_bund_projects_funding_over_time(
|
||||
str, Query(description="The institution ID to filter by.")
|
||||
],
|
||||
) -> InstitutionFunderSummary:
|
||||
return projects_service.get_institution_bund_projects_funding_over_time(
|
||||
return await projects_service.get_institution_bund_projects_funding_over_time(
|
||||
institutions_search_client=institutions_search_client,
|
||||
raw_oa_institution_id=raw_oa_institution_id,
|
||||
)
|
||||
@@ -182,7 +266,7 @@ async def search_cordis_eu_projects(
|
||||
Body(description="The filtering properties for the projects search."),
|
||||
],
|
||||
) -> EuOrganizationProjectSummaryPage:
|
||||
return projects_service.search_cordis_eu_projects(
|
||||
return await projects_service.search_cordis_eu_projects(
|
||||
institutions_search_client=institutions_search_client,
|
||||
projects_filtering_properties=projects_filtering_properties,
|
||||
)
|
||||
@@ -274,7 +358,7 @@ async def get_dfg_projects(
|
||||
},
|
||||
response_model_by_alias=False,
|
||||
)
|
||||
def search_projects(
|
||||
async def search_projects(
|
||||
page: Annotated[int, Query(description="The page number.", ge=0)] = 0,
|
||||
size: Annotated[int, Query(description="The page size.", ge=1)] = 10,
|
||||
selected_project_types: Annotated[
|
||||
@@ -293,7 +377,7 @@ def search_projects(
|
||||
SortDirection, Query(description="The sort direction (asc or desc).")
|
||||
] = SortDirection.ASC,
|
||||
) -> FundingProjectPage:
|
||||
return projects_service.search_all_projects(
|
||||
return await projects_service.search_all_projects(
|
||||
page=page,
|
||||
size=size,
|
||||
selected_project_types=selected_project_types,
|
||||
|
||||
@@ -17,6 +17,7 @@ from inse.projects.model import (
|
||||
ProjectsFilteringProperties,
|
||||
ProjectsSortBy,
|
||||
SortDirection,
|
||||
CordisEuProject
|
||||
)
|
||||
from inse.models.dfg_project_details import DfgProjectDetails
|
||||
from inse.models.bund_project_details import BundProjectDetails
|
||||
@@ -26,12 +27,15 @@ from inse.institutions.institutions_search_client import (
|
||||
from inse.exceptions import NotFoundException
|
||||
from inse.persons.logic import get_author_name_by_id
|
||||
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 typing import Union
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def search_all_projects(
|
||||
async def search_all_projects(
|
||||
page: int,
|
||||
size: int,
|
||||
sort_by: ProjectsSortBy,
|
||||
@@ -39,7 +43,7 @@ def search_all_projects(
|
||||
selected_project_types: Optional[Set[ProjectType]] = None,
|
||||
title: Optional[str] = None,
|
||||
) -> FundingProjectPage:
|
||||
return projects_search_client.search_all_projects(
|
||||
return await projects_search_client.search_all_projects(
|
||||
projects_filtering_properties=ProjectsFilteringProperties(
|
||||
project_type=ProjectType.EU, # placeholder, shall be ignored in search_all_projects
|
||||
page=page,
|
||||
@@ -52,7 +56,7 @@ def search_all_projects(
|
||||
)
|
||||
|
||||
|
||||
def search_bund_projects(
|
||||
async def search_bund_projects(
|
||||
institutions_search_client: InstitutionsSearchClient,
|
||||
filtering_properties: ProjectsFilteringProperties,
|
||||
) -> BundProjectPage:
|
||||
@@ -65,13 +69,13 @@ def search_bund_projects(
|
||||
f"search_bund_projects called with filtering_properties: {filtering_properties}"
|
||||
)
|
||||
|
||||
return get_bund_projects_by_institution_id(
|
||||
return await get_bund_projects_by_institution_id(
|
||||
institutions_search_client=institutions_search_client,
|
||||
filtering_properties=filtering_properties,
|
||||
)
|
||||
|
||||
|
||||
def get_bund_projects_by_institution_id(
|
||||
async def get_bund_projects_by_institution_id(
|
||||
institutions_search_client: InstitutionsSearchClient,
|
||||
filtering_properties: ProjectsFilteringProperties,
|
||||
) -> BundProjectPage:
|
||||
@@ -89,7 +93,7 @@ def get_bund_projects_by_institution_id(
|
||||
logger.debug(
|
||||
f"get_bund_projects_by_institution_id: Found institution aliases for institution_id={filtering_properties.raw_oa_institution_id}: {institution_aliases}"
|
||||
)
|
||||
response = projects_search_client.search_bund_projects(
|
||||
response = await projects_search_client.search_bund_projects(
|
||||
institution_names=institution_aliases,
|
||||
filter_properties=filtering_properties,
|
||||
)
|
||||
@@ -97,7 +101,7 @@ def get_bund_projects_by_institution_id(
|
||||
return response
|
||||
|
||||
|
||||
def search_cordis_eu_projects(
|
||||
async def search_cordis_eu_projects(
|
||||
institutions_search_client: InstitutionsSearchClient,
|
||||
projects_filtering_properties: ProjectsFilteringProperties,
|
||||
) -> EuOrganizationProjectSummaryPage:
|
||||
@@ -106,13 +110,13 @@ def search_cordis_eu_projects(
|
||||
f"Invalid project type: {projects_filtering_properties.project_type}. Expected 'eu'."
|
||||
)
|
||||
|
||||
return get_cordis_eu_projects_by_institution_id(
|
||||
return await get_cordis_eu_projects_by_institution_id(
|
||||
institutions_search_client=institutions_search_client,
|
||||
projects_filtering_properties=projects_filtering_properties,
|
||||
)
|
||||
|
||||
|
||||
def get_cordis_eu_projects_by_institution_id(
|
||||
async def get_cordis_eu_projects_by_institution_id(
|
||||
institutions_search_client: InstitutionsSearchClient,
|
||||
projects_filtering_properties: ProjectsFilteringProperties,
|
||||
) -> EuOrganizationProjectSummaryPage:
|
||||
@@ -133,7 +137,7 @@ def get_cordis_eu_projects_by_institution_id(
|
||||
f"Found institution aliases for institution_id={projects_filtering_properties.raw_oa_institution_id}: {institution_aliases}"
|
||||
)
|
||||
|
||||
page = get_eu_organization_project_contributions(
|
||||
page = await get_eu_organization_project_contributions(
|
||||
organization_names=institution_aliases,
|
||||
projects_filtering_properties=projects_filtering_properties,
|
||||
)
|
||||
@@ -154,7 +158,7 @@ async def get_dfg_projects_by_author_id(
|
||||
logger.debug(
|
||||
f"Fetching DFG projects for author_id={author_id}, topic={topic}, page={page}, size={size}, sort_by={sort_by}, sort_direction={sort_direction}"
|
||||
)
|
||||
name = get_author_name_by_id(author_id)
|
||||
name = await get_author_name_by_id(author_id)
|
||||
if not name:
|
||||
logger.debug(f"No author name found for author_id={author_id}")
|
||||
raise NotFoundException(
|
||||
@@ -162,7 +166,7 @@ async def get_dfg_projects_by_author_id(
|
||||
)
|
||||
logger.debug(f"Found author name for author_id={author_id}: {name}")
|
||||
|
||||
response = projects_search_client.search_dfg_projects(
|
||||
response = await projects_search_client.search_dfg_projects(
|
||||
page=page,
|
||||
size=size,
|
||||
names=[name],
|
||||
@@ -182,7 +186,7 @@ async def get_institution_cordis_eu_projects_funding_over_time(
|
||||
raw_oa_institution_id
|
||||
)
|
||||
)
|
||||
page = get_eu_organization_project_contributions(
|
||||
page = await get_eu_organization_project_contributions(
|
||||
organization_names=institution_aliases,
|
||||
projects_filtering_properties=ProjectsFilteringProperties(
|
||||
project_type=ProjectType.EU,
|
||||
@@ -200,7 +204,7 @@ async def get_institution_cordis_eu_projects_funding_over_time(
|
||||
)
|
||||
|
||||
|
||||
def get_institution_bund_projects_funding_over_time(
|
||||
async def get_institution_bund_projects_funding_over_time(
|
||||
institutions_search_client: InstitutionsSearchClient,
|
||||
raw_oa_institution_id: str,
|
||||
) -> InstitutionFunderSummary:
|
||||
@@ -215,7 +219,7 @@ def get_institution_bund_projects_funding_over_time(
|
||||
logger.debug(
|
||||
f"Found institution aliases for institution_id={raw_oa_institution_id}: {institution_aliases}"
|
||||
)
|
||||
response = projects_search_client.search_bund_projects(
|
||||
response = await projects_search_client.search_bund_projects(
|
||||
filter_properties=ProjectsFilteringProperties(
|
||||
project_type=ProjectType.BUND,
|
||||
page=0,
|
||||
@@ -301,29 +305,40 @@ def _calculate_funding_over_time(
|
||||
)
|
||||
|
||||
|
||||
def get_single_dfg_project(
|
||||
async def get_single_dfg_project(
|
||||
project_id: str,
|
||||
) -> DfgProjectDetails:
|
||||
logger.debug(f"Fetching single DFG project for id={project_id}")
|
||||
|
||||
project = projects_search_client.get_dfg_project_by_id(project_id)
|
||||
project = await projects_search_client.get_dfg_project_by_id(project_id)
|
||||
if not project:
|
||||
raise NotFoundException(f"DFG project with id {project_id} not found")
|
||||
return project
|
||||
|
||||
|
||||
def get_single_bund_project(
|
||||
async def get_single_bund_project(
|
||||
project_id: str,
|
||||
) -> BundProjectDetails:
|
||||
logger.debug(f"Fetching single BUND project for id={project_id}")
|
||||
|
||||
project = projects_search_client.get_bund_project_by_id(project_id)
|
||||
project = await projects_search_client.get_bund_project_by_id(project_id)
|
||||
if not project:
|
||||
raise NotFoundException(f"BUND project with id {project_id} not found")
|
||||
return project
|
||||
|
||||
|
||||
def search_cordis_eu_projects_for_author_id(
|
||||
async def get_single_eu_cordis_project(
|
||||
project_id: str,
|
||||
) -> 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)
|
||||
if not project:
|
||||
raise NotFoundException(f"EU project with id {project_id} not found")
|
||||
return project
|
||||
|
||||
|
||||
async def search_cordis_eu_projects_for_author_id(
|
||||
raw_oa_author_id: str,
|
||||
) -> CordisEuProjectPage:
|
||||
|
||||
@@ -332,18 +347,19 @@ def search_cordis_eu_projects_for_author_id(
|
||||
# 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 = get_publication_dois_of_author(raw_oa_author_id=raw_oa_author_id)
|
||||
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 = projects_search_client.get_cordis_eu_project_ids_by_dois(dois=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 = projects_search_client.get_cordis_eu_projects_by_project_ids(
|
||||
funding_project_page = await projects_search_client.get_cordis_eu_projects_by_project_ids(
|
||||
project_ids=project_ids
|
||||
)
|
||||
|
||||
return funding_project_page
|
||||
|
||||
|
||||
@@ -8,10 +8,8 @@ from copy import deepcopy
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from fastapi import HTTPException
|
||||
from pydantic import ValidationError
|
||||
from starlette.status import HTTP_400_BAD_REQUEST
|
||||
from starlette.status import HTTP_502_BAD_GATEWAY
|
||||
from inse.exceptions import UpstreamAPIException, BadRequestException, ElasticsearchException
|
||||
|
||||
from inse.models.openalex.autocomplete_response import AutocompleteResponse
|
||||
from inse.models.openalex.autocomplete_response_meta import AutocompleteResponseMeta
|
||||
@@ -38,10 +36,7 @@ async def list_topics(
|
||||
client: OpenAlexTopicsClient | None = None,
|
||||
) -> TopicsListResponse:
|
||||
if sample is not None and (sort or page not in (None, 1)):
|
||||
raise HTTPException(
|
||||
status_code=HTTP_400_BAD_REQUEST,
|
||||
detail="sample cannot be combined with sort or page.",
|
||||
)
|
||||
raise BadRequestException("sample cannot be combined with sort or page.")
|
||||
|
||||
openalex_client = client or OpenAlexTopicsClient()
|
||||
|
||||
@@ -66,12 +61,12 @@ async def list_topics(
|
||||
except ValueError:
|
||||
if exc.response.text:
|
||||
detail = exc.response.text
|
||||
raise HTTPException(status_code=status_code, detail=detail) from exc
|
||||
raise UpstreamAPIException(message=detail, status_code=status_code) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
logger.exception("OpenAlex topics request failed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex topics request failed.",
|
||||
raise UpstreamAPIException(
|
||||
message="OpenAlex topics request failed.",
|
||||
status_code=502,
|
||||
) from exc
|
||||
|
||||
try:
|
||||
@@ -79,9 +74,9 @@ async def list_topics(
|
||||
return TopicsListResponse.from_dict(normalized_data) or TopicsListResponse()
|
||||
except ValidationError as exc:
|
||||
logger.exception("OpenAlex topics response could not be parsed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex topics response could not be parsed.",
|
||||
raise UpstreamAPIException(
|
||||
message="OpenAlex topics response could not be parsed.",
|
||||
status_code=502,
|
||||
) from exc
|
||||
|
||||
|
||||
@@ -282,10 +277,7 @@ async def vector_search_topics(
|
||||
|
||||
except Exception as exc:
|
||||
logger.exception("Failed to load elasticsearch integration.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail=f"Failed to load elasticsearch integration: {exc}"
|
||||
)
|
||||
raise ElasticsearchException(f"Failed to load elasticsearch integration: {exc}") from exc
|
||||
|
||||
# 1. Vectorize query
|
||||
try:
|
||||
@@ -293,10 +285,7 @@ async def vector_search_topics(
|
||||
query_vector = model.encode(query).tolist()
|
||||
except Exception as exc:
|
||||
logger.exception("Failed to encode query text.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail=f"Failed to encode query text: {exc}"
|
||||
)
|
||||
raise ElasticsearchException(f"Failed to encode query text: {exc}") from exc
|
||||
|
||||
# 2. Query Elasticsearch using standard Bool Should hybrid search
|
||||
should_clauses = []
|
||||
@@ -357,17 +346,14 @@ async def vector_search_topics(
|
||||
}
|
||||
|
||||
try:
|
||||
raw_results = elasticsearch.search(
|
||||
raw_results = await elasticsearch.search(
|
||||
index="topicvectors",
|
||||
body=body,
|
||||
cluster="nes"
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.exception("Elasticsearch vector search failed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail=f"Elasticsearch vector search failed: {exc}"
|
||||
)
|
||||
logger.exception("Elasticsearch vector search failed with unexpected error.")
|
||||
raise ElasticsearchException(f"Unexpected vector search failure: {exc}") from exc
|
||||
|
||||
# 3. Format result
|
||||
hits = raw_results.get("hits", {}).get("hits", [])
|
||||
@@ -389,8 +375,5 @@ async def vector_search_topics(
|
||||
return TopicsListResponse.from_dict(normalized_data) or TopicsListResponse()
|
||||
except ValidationError as exc:
|
||||
logger.exception("Vector search response could not be parsed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="Vector search response could not be parsed.",
|
||||
) from exc
|
||||
raise ElasticsearchException(f"Vector search response could not be parsed: {exc}") from exc
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import httpx
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
from inse.exceptions import BadRequestException
|
||||
|
||||
from inse.topics import logic
|
||||
from inse.topics.search_client import OpenAlexTopicsClient
|
||||
@@ -76,11 +76,9 @@ async def test_list_topics_maps_openalex_response_to_model():
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_topics_rejects_sample_with_sort():
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
with pytest.raises(BadRequestException) as exc_info:
|
||||
await logic.list_topics(sample=10, sort="works_count:desc")
|
||||
|
||||
assert exc_info.value.status_code == 400
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_topics_accepts_practical_openalex_type_variants():
|
||||
|
||||
@@ -31,7 +31,7 @@ async def get_ranking_data(topic: ResearchTopic, metric: DashboardMetric) -> Ran
|
||||
|
||||
|
||||
# Fetch top institutions for the topic by works_count
|
||||
res = elasticsearch.search(
|
||||
res = await elasticsearch.search(
|
||||
index="openalex-institutions",
|
||||
query=query,
|
||||
size=10,
|
||||
|
||||
@@ -8,15 +8,14 @@ from typing import Optional
|
||||
from typing import TypeVar
|
||||
from inse.models.openalex import Author
|
||||
from . import model
|
||||
from fastapi import HTTPException
|
||||
from starlette.status import HTTP_404_NOT_FOUND
|
||||
from inse.exceptions import NotFoundException
|
||||
|
||||
T = TypeVar('T')
|
||||
|
||||
def raise_not_found_if_none(value: Optional[T]) -> T:
|
||||
''' Returns the value, if it is set, or raises a 404, if the value is None.'''
|
||||
if value == None:
|
||||
raise HTTPException(HTTP_404_NOT_FOUND)
|
||||
raise NotFoundException("Not found.")
|
||||
else:
|
||||
return value
|
||||
|
||||
|
||||
@@ -9,11 +9,8 @@ from time import time
|
||||
from typing import Any, List
|
||||
|
||||
import httpx
|
||||
from fastapi import HTTPException
|
||||
from pydantic import ValidationError
|
||||
from starlette.status import HTTP_502_BAD_GATEWAY
|
||||
from starlette.status import HTTP_404_NOT_FOUND
|
||||
from starlette.status import HTTP_503_SERVICE_UNAVAILABLE
|
||||
|
||||
from inse import config
|
||||
from inse.integrations import elasticsearch
|
||||
@@ -24,7 +21,7 @@ from inse.models.openalex.meta import Meta
|
||||
from inse.models.openalex.topic_count import TopicCount
|
||||
from inse.models.openalex.topics_by_year import TopicsByYear
|
||||
from inse.models.openalex.topics_by_time import TopicsByTime
|
||||
from .search_client import MissingApiKeyError
|
||||
from inse.exceptions import MissingApiKeyError, ElasticsearchException, UpstreamAPIException
|
||||
from .search_client import OpenAlexWorksSearchClient
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -122,10 +119,10 @@ async def get_primary_topic_counts(
|
||||
author_id: str,
|
||||
client: OpenAlexWorksSearchClient | None = None,
|
||||
) -> List[TopicCount]:
|
||||
topic_counts = _get_primary_topic_counts_from_es(author_id)
|
||||
topic_counts = await _get_primary_topic_counts_from_es(author_id)
|
||||
|
||||
topic_ids = [item["id"] for item in topic_counts if item["id"]]
|
||||
details = _get_topic_details(topic_ids)
|
||||
details = await _get_topic_details(topic_ids)
|
||||
|
||||
result = []
|
||||
|
||||
@@ -148,7 +145,7 @@ async def get_primary_topic_counts(
|
||||
return result
|
||||
|
||||
|
||||
def _get_primary_topic_counts_from_es(author_id: str) -> list[dict]:
|
||||
async def _get_primary_topic_counts_from_es(author_id: str) -> list[dict]:
|
||||
|
||||
indexed_author_id = f"https://openalex.org/{author_id.strip()}"
|
||||
|
||||
@@ -174,16 +171,13 @@ def _get_primary_topic_counts_from_es(author_id: str) -> list[dict]:
|
||||
}
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=config.settings.openalex_works_search_index,
|
||||
body=body,
|
||||
)
|
||||
except httpx.HTTPError as exc:
|
||||
except ElasticsearchException as exc:
|
||||
logger.exception("OpenAlex primary topic aggregation request failed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex works search request failed.",
|
||||
) from exc
|
||||
raise
|
||||
|
||||
aggregations = response.get("aggregations", {})
|
||||
buckets = aggregations.get("primary_topics", {}).get("buckets", [])
|
||||
@@ -197,42 +191,33 @@ def _get_primary_topic_counts_from_es(author_id: str) -> list[dict]:
|
||||
|
||||
async def get_work(
|
||||
work_id: str,
|
||||
title:str,
|
||||
client: OpenAlexWorksSearchClient | None = None,
|
||||
) -> Work:
|
||||
) -> Work | None:
|
||||
search_client = client or OpenAlexWorksSearchClient()
|
||||
try:
|
||||
data = await search_client.search_work(work_id)
|
||||
except MissingApiKeyError as exc:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="OpenAlex works search is not configured.",
|
||||
) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex works search request failed.",
|
||||
) from exc
|
||||
|
||||
data = await search_client.search_work(work_id)
|
||||
elements, _ = _parse_full_work_search_response(data)
|
||||
if (not elements) and title:
|
||||
response_by_title = await search_client.search_for_work_by_title(title=title)
|
||||
elements, _ = _parse_full_work_search_response(response_by_title)
|
||||
if not elements:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_404_NOT_FOUND,
|
||||
detail="Publication not found.",
|
||||
)
|
||||
return None
|
||||
return elements[0]
|
||||
|
||||
|
||||
def _get_topic_details(topic_ids: List[str]) -> dict[str, dict]:
|
||||
async def _get_topic_details(topic_ids: List[str]) -> dict[str, dict]:
|
||||
if not topic_ids:
|
||||
return {}
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index="openalex-topics",
|
||||
query={"terms": {"id": topic_ids}},
|
||||
source=TOPIC_DETAIL_SOURCE_FIELDS,
|
||||
size=len(topic_ids),
|
||||
)
|
||||
except httpx.HTTPError:
|
||||
except Exception:
|
||||
logger.exception("Could not load topic details from Elasticsearch.")
|
||||
return {}
|
||||
|
||||
@@ -251,7 +236,7 @@ def _get_topic_details(topic_ids: List[str]) -> dict[str, dict]:
|
||||
"domain": _extract_topic_hierarchy_item(source, "domain"),
|
||||
}
|
||||
|
||||
_enrich_topic_hierarchy_descriptions(details)
|
||||
await _enrich_topic_hierarchy_descriptions(details)
|
||||
|
||||
return details
|
||||
|
||||
@@ -269,7 +254,7 @@ def _extract_topic_hierarchy_item(source: dict, key: str) -> dict[str, str | Non
|
||||
}
|
||||
|
||||
|
||||
def _enrich_topic_hierarchy_descriptions(details: dict[str, dict]) -> None:
|
||||
async def _enrich_topic_hierarchy_descriptions(details: dict[str, dict]) -> None:
|
||||
for hierarchy_key, index in TOPIC_HIERARCHY_DESCRIPTION_INDICES.items():
|
||||
hierarchy_ids = {
|
||||
item.get(hierarchy_key, {}).get("id")
|
||||
@@ -277,7 +262,7 @@ def _enrich_topic_hierarchy_descriptions(details: dict[str, dict]) -> None:
|
||||
if item.get(hierarchy_key, {}).get("id")
|
||||
}
|
||||
|
||||
descriptions = _get_topic_hierarchy_descriptions(index, list(hierarchy_ids))
|
||||
descriptions = await _get_topic_hierarchy_descriptions(index, list(hierarchy_ids))
|
||||
|
||||
for item in details.values():
|
||||
hierarchy_item = item.get(hierarchy_key) or {}
|
||||
@@ -287,7 +272,7 @@ def _enrich_topic_hierarchy_descriptions(details: dict[str, dict]) -> None:
|
||||
hierarchy_item["description"] = descriptions[hierarchy_id]
|
||||
|
||||
|
||||
def _get_topic_hierarchy_descriptions(
|
||||
async def _get_topic_hierarchy_descriptions(
|
||||
index: str,
|
||||
hierarchy_ids: list[str],
|
||||
) -> dict[str, str | None]:
|
||||
@@ -295,13 +280,13 @@ def _get_topic_hierarchy_descriptions(
|
||||
return {}
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=index,
|
||||
query={"terms": {"id": hierarchy_ids}},
|
||||
source=TOPIC_HIERARCHY_DESCRIPTION_SOURCE_FIELDS,
|
||||
size=len(hierarchy_ids),
|
||||
)
|
||||
except httpx.HTTPError:
|
||||
except Exception:
|
||||
logger.exception("Could not load topic hierarchy details from %s.", index)
|
||||
return {}
|
||||
|
||||
@@ -442,7 +427,7 @@ async def get_topics_by_time_by_author(
|
||||
client=client,
|
||||
)
|
||||
|
||||
return _get_topics_by_time_by_author_from_es(
|
||||
return await _get_topics_by_time_by_author_from_es(
|
||||
author_id,
|
||||
max_topics_per_year=max_topics_per_year,
|
||||
target_publications=target_publications,
|
||||
@@ -530,7 +515,7 @@ async def _get_topics_by_time_by_author_from_work_pages(
|
||||
if topic["id"]:
|
||||
topic_ids.add(topic["id"])
|
||||
|
||||
topic_details = _get_topic_details(list(topic_ids))
|
||||
topic_details = await _get_topic_details(list(topic_ids))
|
||||
|
||||
elements = []
|
||||
|
||||
@@ -589,13 +574,13 @@ async def _get_topics_by_time_by_author_from_work_pages(
|
||||
)
|
||||
|
||||
|
||||
def _get_topics_by_time_by_author_from_es(
|
||||
async def _get_topics_by_time_by_author_from_es(
|
||||
author_id: str,
|
||||
max_topics_per_year: int = 3,
|
||||
target_publications: int = 300,
|
||||
include_all: bool = False,
|
||||
) -> TopicsByTime:
|
||||
year_buckets, total_publications = _get_publication_year_counts_from_es(author_id)
|
||||
year_buckets, total_publications = await _get_publication_year_counts_from_es(author_id)
|
||||
selected_years, is_limited = _select_complete_timeline_years(
|
||||
year_buckets,
|
||||
target_publications=target_publications,
|
||||
@@ -611,13 +596,13 @@ def _get_topics_by_time_by_author_from_es(
|
||||
total_publications=total_publications,
|
||||
)
|
||||
|
||||
year_topic_buckets = _get_timeline_topic_counts_from_es(
|
||||
year_topic_buckets = await _get_timeline_topic_counts_from_es(
|
||||
author_id,
|
||||
years=selected_years,
|
||||
max_topics_per_year=max_topics_per_year,
|
||||
)
|
||||
topic_ids = _collect_topic_ids_from_year_buckets(year_topic_buckets)
|
||||
topic_details = _get_topic_details(list(topic_ids))
|
||||
topic_details = await _get_topic_details(list(topic_ids))
|
||||
|
||||
elements = _build_timeline_elements_from_aggregations(
|
||||
year_topic_buckets,
|
||||
@@ -634,7 +619,7 @@ def _get_topics_by_time_by_author_from_es(
|
||||
)
|
||||
|
||||
|
||||
def _get_publication_year_counts_from_es(author_id: str) -> tuple[list[dict], int]:
|
||||
async def _get_publication_year_counts_from_es(author_id: str) -> tuple[list[dict], int]:
|
||||
body = {
|
||||
"size": 0,
|
||||
"track_total_hits": True,
|
||||
@@ -651,21 +636,18 @@ def _get_publication_year_counts_from_es(author_id: str) -> tuple[list[dict], in
|
||||
}
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=config.settings.openalex_works_search_index,
|
||||
body=body,
|
||||
)
|
||||
except httpx.HTTPError as exc:
|
||||
except ElasticsearchException as exc:
|
||||
logger.exception("OpenAlex publication year aggregation request failed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex works search request failed.",
|
||||
) from exc
|
||||
raise
|
||||
|
||||
return _parse_year_count_buckets(response), _parse_total_hits(response)
|
||||
|
||||
|
||||
def _get_timeline_topic_counts_from_es(
|
||||
async def _get_timeline_topic_counts_from_es(
|
||||
author_id: str,
|
||||
years: list[int],
|
||||
max_topics_per_year: int,
|
||||
@@ -722,16 +704,13 @@ def _get_timeline_topic_counts_from_es(
|
||||
}
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=config.settings.openalex_works_search_index,
|
||||
body=body,
|
||||
)
|
||||
except httpx.HTTPError as exc:
|
||||
except ElasticsearchException as exc:
|
||||
logger.exception("OpenAlex timeline topic aggregation request failed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex works search request failed.",
|
||||
) from exc
|
||||
raise
|
||||
|
||||
return response.get("aggregations", {}).get("by_year", {}).get("buckets", [])
|
||||
|
||||
@@ -892,29 +871,16 @@ async def _search_author_works_data(
|
||||
institution_id: list[str] | None = None,
|
||||
topic_id: list[str] | None = None,
|
||||
) -> dict:
|
||||
try:
|
||||
return await search_client.search_author_works(
|
||||
author_id,
|
||||
page,
|
||||
size,
|
||||
publication_year=publication_year,
|
||||
work_type=work_type,
|
||||
language=language,
|
||||
institution_id=institution_id,
|
||||
topic_id=topic_id,
|
||||
)
|
||||
except MissingApiKeyError as exc:
|
||||
logger.error("OpenAlex works Elasticsearch API key is not configured.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="OpenAlex works search is not configured.",
|
||||
) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
logger.exception("OpenAlex works search request failed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex works search request failed.",
|
||||
) from exc
|
||||
return await search_client.search_author_works(
|
||||
author_id,
|
||||
page,
|
||||
size,
|
||||
publication_year=publication_year,
|
||||
work_type=work_type,
|
||||
language=language,
|
||||
institution_id=institution_id,
|
||||
topic_id=topic_id,
|
||||
)
|
||||
|
||||
|
||||
def _parse_full_work_search_response(data: dict) -> tuple[list[Work], int]:
|
||||
@@ -955,15 +921,15 @@ def _parse_full_work_search_response(data: dict) -> tuple[list[Work], int]:
|
||||
elements.append(work)
|
||||
except ValidationError as exc:
|
||||
logger.exception("OpenAlex works search response could not be parsed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex works search response could not be parsed.",
|
||||
raise UpstreamAPIException(
|
||||
message="OpenAlex works search response could not be parsed.",
|
||||
status_code=502,
|
||||
) from exc
|
||||
|
||||
return elements, total
|
||||
|
||||
|
||||
def get_publication_dois_of_author(
|
||||
async def get_publication_dois_of_author(
|
||||
raw_oa_author_id: str,
|
||||
) -> List[str]:
|
||||
query = {
|
||||
@@ -985,19 +951,16 @@ def get_publication_dois_of_author(
|
||||
}
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index="openalex-works",
|
||||
source=["doi"],
|
||||
size=10000,
|
||||
query=query,
|
||||
cluster="nes",
|
||||
)
|
||||
except httpx.HTTPError as exc:
|
||||
except ElasticsearchException as exc:
|
||||
logger.exception("Request for publication DOIs of author failed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="Request for publication DOIs of author failed.",
|
||||
) from exc
|
||||
raise
|
||||
|
||||
dois = []
|
||||
for hit in response.get("hits", {}).get("hits", []):
|
||||
|
||||
@@ -7,12 +7,11 @@ import logging
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
import urllib
|
||||
from .. import config
|
||||
|
||||
|
||||
class MissingApiKeyError(Exception):
|
||||
pass
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster, ESIndex
|
||||
from inse.exceptions import MissingApiKeyError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -141,46 +140,72 @@ class OpenAlexWorksSearchClient:
|
||||
if not self.api_key:
|
||||
raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.")
|
||||
|
||||
async with httpx.AsyncClient(
|
||||
base_url=self.base_url,
|
||||
timeout=self.timeout,
|
||||
transport=self.transport,
|
||||
) as client:
|
||||
response = await client.post(
|
||||
f"/{self.index}/_search",
|
||||
headers={"Authorization": f"ApiKey {self.api_key}"},
|
||||
json=self.author_works_query(
|
||||
author_id,
|
||||
page,
|
||||
size,
|
||||
publication_year=publication_year,
|
||||
work_type=work_type,
|
||||
language=language,
|
||||
institution_id=institution_id,
|
||||
topic_id=topic_id,
|
||||
),
|
||||
)
|
||||
# logging.debug(f"Response: {response.text}")
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
body = self.author_works_query(
|
||||
author_id,
|
||||
page,
|
||||
size,
|
||||
publication_year=publication_year,
|
||||
work_type=work_type,
|
||||
language=language,
|
||||
institution_id=institution_id,
|
||||
topic_id=topic_id,
|
||||
)
|
||||
return await elasticsearch.search(index=self.index,body=body,cluster=ESCluster.NES,)
|
||||
|
||||
async def search_work(self, work_id: str) -> dict[str, Any]:
|
||||
async def search_work(self, identifier: str) -> dict[str, Any]:
|
||||
if not self.api_key:
|
||||
raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.")
|
||||
decoded_id = urllib.parse.unquote(identifier)
|
||||
body = {
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"term": {
|
||||
"_id": {
|
||||
"value": decoded_id,
|
||||
"boost": 5
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"term": {
|
||||
"doi": {
|
||||
"value": "https://doi.org/" + decoded_id.lower(),
|
||||
"boost": 3
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"minimum_should_match": 1
|
||||
}
|
||||
}
|
||||
}
|
||||
response = await elasticsearch.search(index=f"{ESIndex.OPENALEX_WORKS}*",body=body,cluster=ESCluster.NES,size=1)
|
||||
return response
|
||||
|
||||
async def search_for_work_by_title(
|
||||
self,
|
||||
title: str,
|
||||
) -> dict[str, Any]:
|
||||
if not self.api_key:
|
||||
raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.")
|
||||
|
||||
indexed_work_id = f"https://openalex.org/{work_id.strip().split('/')[-1]}"
|
||||
async with httpx.AsyncClient(
|
||||
base_url=self.base_url,
|
||||
timeout=self.timeout,
|
||||
transport=self.transport,
|
||||
) as client:
|
||||
response = await client.post(
|
||||
f"/{self.index}/_search",
|
||||
headers={"Authorization": f"ApiKey {self.api_key}"},
|
||||
json={
|
||||
"size": 1,
|
||||
"query": {"term": {"id": indexed_work_id}},
|
||||
query_clauses = [
|
||||
{"match_phrase": {"title": title}},
|
||||
]
|
||||
|
||||
body = {
|
||||
"query": {
|
||||
"bool": {
|
||||
"must": query_clauses,
|
||||
},
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
},
|
||||
"sort": [
|
||||
{"publication_year": {"order": "desc", "missing": "_last"}},
|
||||
{"cited_by_count": {"order": "desc", "missing": "_last"}},
|
||||
],
|
||||
}
|
||||
response = await elasticsearch.search(index=f'{ESIndex.OPENALEX_WORKS}*',body=body,cluster=ESCluster.NES,size=1)
|
||||
|
||||
return response
|
||||
@@ -4,7 +4,7 @@
|
||||
REST API for publication works.
|
||||
"""
|
||||
|
||||
from typing import Annotated
|
||||
from typing import Annotated, Optional
|
||||
|
||||
from fastapi import APIRouter
|
||||
from fastapi import Depends
|
||||
@@ -123,17 +123,20 @@ async def get_topics_by_time_by_author(
|
||||
|
||||
|
||||
@router.get(
|
||||
"/detail/{work_id}",
|
||||
"/detail/{identifier}",
|
||||
operation_id="getWork",
|
||||
response_model=Work,
|
||||
summary="Returns one publication.",
|
||||
response_model=Work | None,
|
||||
summary="Returns one publication by OpenAlex ID or DOI.",
|
||||
)
|
||||
async def get_work(
|
||||
work_id: Annotated[
|
||||
str, Path(description="The OpenAlex work id, for example W2741809807.")
|
||||
async def get_work_by_identifier(
|
||||
identifier: Annotated[
|
||||
str, Path(description="The OpenAlex work id (e.g., W2741809807) or DOI number of the publication.")
|
||||
],
|
||||
title: Annotated[
|
||||
Optional[str], Query(description="Do we want to fallback to title search if ID and DOI dont work?")
|
||||
] = "",
|
||||
principal: security.Principal = Depends(
|
||||
security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])
|
||||
),
|
||||
):
|
||||
return await logic.get_work(work_id)
|
||||
return await logic.get_work(identifier,title=title)
|
||||
@@ -3,7 +3,7 @@ import json
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from inse.works.search_client import MissingApiKeyError
|
||||
from inse.exceptions import MissingApiKeyError
|
||||
from inse.works.search_client import OpenAlexWorksSearchClient
|
||||
|
||||
|
||||
@@ -152,37 +152,47 @@ def test_author_works_query_adds_topic_filter():
|
||||
]
|
||||
|
||||
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_search_author_works_passes_institution_filter_to_query():
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
body = json.loads(request.content)
|
||||
assert body["query"]["bool"]["must"][1]["nested"]["path"] == (
|
||||
"authorships.institutions"
|
||||
with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search:
|
||||
mock_search.return_value = {"hits": {"total": {"value": 1}, "hits": []}}
|
||||
client = OpenAlexWorksSearchClient(index="openalex-works")
|
||||
|
||||
await client.search_author_works(
|
||||
"A5023888391",
|
||||
page=1,
|
||||
size=20,
|
||||
institution_id=["https://openalex.org/I205640436"],
|
||||
)
|
||||
|
||||
assert mock_search.call_count == 1
|
||||
_, kwargs = mock_search.call_args
|
||||
body = kwargs.get("body")
|
||||
assert body["query"]["bool"]["must"][1]["nested"]["path"] == "authorships.institutions"
|
||||
assert body["query"]["bool"]["must"][1]["nested"]["query"]["terms"] == {
|
||||
"authorships.institutions.id": ["https://openalex.org/I205640436"],
|
||||
}
|
||||
return httpx.Response(200, json={"hits": {"total": {"value": 1}, "hits": []}})
|
||||
|
||||
client = OpenAlexWorksSearchClient(
|
||||
base_url="https://project.nes.uni-due.de/elastic",
|
||||
index="openalex-works",
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
|
||||
await client.search_author_works(
|
||||
"A5023888391",
|
||||
page=1,
|
||||
size=20,
|
||||
institution_id=["https://openalex.org/I205640436"],
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_search_author_works_passes_topic_filter_to_query():
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
body = json.loads(request.content)
|
||||
with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search:
|
||||
mock_search.return_value = {"hits": {"total": {"value": 1}, "hits": []}}
|
||||
client = OpenAlexWorksSearchClient(index="openalex-works")
|
||||
|
||||
await client.search_author_works(
|
||||
"A5023888391",
|
||||
page=1,
|
||||
size=20,
|
||||
topic_id=["https://openalex.org/T12419"],
|
||||
)
|
||||
|
||||
assert mock_search.call_count == 1
|
||||
_, kwargs = mock_search.call_args
|
||||
body = kwargs.get("body")
|
||||
assert body["query"]["bool"]["filter"] == [
|
||||
{
|
||||
"bool": {
|
||||
@@ -207,61 +217,55 @@ async def test_search_author_works_passes_topic_filter_to_query():
|
||||
},
|
||||
},
|
||||
]
|
||||
return httpx.Response(200, json={"hits": {"total": {"value": 1}, "hits": []}})
|
||||
|
||||
client = OpenAlexWorksSearchClient(
|
||||
base_url="https://project.nes.uni-due.de/elastic",
|
||||
index="openalex-works",
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
|
||||
await client.search_author_works(
|
||||
"A5023888391",
|
||||
page=1,
|
||||
size=20,
|
||||
topic_id=["https://openalex.org/T12419"],
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_search_author_works_calls_elasticsearch_index_with_api_key():
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
assert request.method == "POST"
|
||||
assert request.url.path == "/elastic/openalex-works/_search"
|
||||
assert request.headers["Authorization"] == "ApiKey test-key"
|
||||
return httpx.Response(200, json={"hits": {"total": {"value": 0}, "hits": []}})
|
||||
with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search:
|
||||
mock_search.return_value = {"hits": {"total": {"value": 0}, "hits": []}}
|
||||
client = OpenAlexWorksSearchClient(index="openalex-works")
|
||||
|
||||
client = OpenAlexWorksSearchClient(
|
||||
base_url="https://project.nes.uni-due.de/elastic",
|
||||
index="openalex-works",
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
result = await client.search_author_works("A5023888391", page=1, size=20)
|
||||
|
||||
result = await client.search_author_works("A5023888391", page=1, size=20)
|
||||
|
||||
assert result == {"hits": {"total": {"value": 0}, "hits": []}}
|
||||
assert result == {"hits": {"total": {"value": 0}, "hits": []}}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_search_work_filters_by_work_id():
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
body = json.loads(request.content)
|
||||
with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search:
|
||||
mock_search.return_value = {"hits": {"total": {"value": 1}, "hits": []}}
|
||||
client = OpenAlexWorksSearchClient(index="openalex-works")
|
||||
|
||||
await client.search_work("W2741809807")
|
||||
|
||||
assert mock_search.call_count == 1
|
||||
_, kwargs = mock_search.call_args
|
||||
body = kwargs.get("body")
|
||||
assert body == {
|
||||
"size": 1,
|
||||
"query": {"term": {"id": "https://openalex.org/W2741809807"}},
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"term": {
|
||||
"_id": {
|
||||
"value": "W2741809807",
|
||||
"boost": 5
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"term": {
|
||||
"doi": {
|
||||
"value": "https://doi.org/w2741809807",
|
||||
"boost": 3
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"minimum_should_match": 1
|
||||
}
|
||||
}
|
||||
}
|
||||
return httpx.Response(200, json={"hits": {"total": {"value": 1}, "hits": []}})
|
||||
|
||||
client = OpenAlexWorksSearchClient(
|
||||
base_url="https://project.nes.uni-due.de/elastic",
|
||||
index="openalex-works",
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
|
||||
await client.search_work("W2741809807")
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
|
||||
Generated
-62
@@ -178,36 +178,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/b2/b7/545d2c10c1fc15e48653c91efde329a790f2eecfbbf2bd16003b5db2bab0/dotenv-0.9.9-py2.py3-none-any.whl", hash = "sha256:29cf74a087b31dafdb5a446b6d7e11cbce8ed2741540e2339c69fbef92c94ce9", size = 1892, upload-time = "2025-02-19T22:15:01.647Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "elastic-transport"
|
||||
version = "9.4.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "certifi" },
|
||||
{ name = "sniffio" },
|
||||
{ name = "urllib3" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/0f/a8/dd1431b95daa54d4859c1d250362433df6df9cfaab7bfac3eafd410d019a/elastic_transport-9.4.1.tar.gz", hash = "sha256:d12c86ea73528690ebf63a488d9ae323292e6aa5ee55e1e29f14293472f4197f", size = 79170, upload-time = "2026-05-25T14:16:47.416Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/5c/f6/508c1e541b840b6eaf60a46a8994ba55affd07bf6a311cffc860781ae06a/elastic_transport-9.4.1-py3-none-any.whl", hash = "sha256:186a29e6c66ff269487e33f7b17176316e18b6061702c25eb0bb15681302e91d", size = 66229, upload-time = "2026-05-25T14:16:45.882Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "elasticsearch"
|
||||
version = "9.4.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "anyio" },
|
||||
{ name = "elastic-transport" },
|
||||
{ name = "python-dateutil" },
|
||||
{ name = "sniffio" },
|
||||
{ name = "typing-extensions" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/e0/4b/9b753f0a8f56ae508dced2f7ac87bef7a27ce8f890e349e16812e9f7f4fa/elasticsearch-9.4.1.tar.gz", hash = "sha256:1d78fdfba97a903ec35a5eb5808a74e33392b7c620bd5f742d465a3a26c27d75", size = 908138, upload-time = "2026-05-26T16:28:40.132Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/cf/8e/2c93805e93e724a90156004a9212572ec86473974deede4605a33b8b169a/elasticsearch-9.4.1-py3-none-any.whl", hash = "sha256:71ab71c3d1b20fd88c2922fb82c3277cce7ea03c160686e7b9368b265c2b4cac", size = 993647, upload-time = "2026-05-26T16:28:36.556Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fastapi"
|
||||
version = "0.115.14"
|
||||
@@ -799,18 +769,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/f0/d7/a812a0bd0f5160823e647524488cc9734f93782f2c273b8f77e8afc60a37/pytest-8.1.2-py3-none-any.whl", hash = "sha256:6c06dc309ff46a05721e6fd48e492a775ed8165d2ecdf57f156a80c7e95bb142", size = 337456, upload-time = "2024-04-26T18:05:15.452Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "python-dateutil"
|
||||
version = "2.9.0.post0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "six" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/66/c0/0c8b6ad9f17a802ee498c46e004a0eb49bc148f2fd230864601a86dcf6db/python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 342432, upload-time = "2024-03-01T18:36:20.211Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892, upload-time = "2024-03-01T18:36:18.57Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "python-dotenv"
|
||||
version = "1.2.2"
|
||||
@@ -1127,7 +1085,6 @@ source = { virtual = "." }
|
||||
dependencies = [
|
||||
{ name = "cryptography" },
|
||||
{ name = "dotenv" },
|
||||
{ name = "elasticsearch" },
|
||||
{ name = "fastapi" },
|
||||
{ name = "httpx" },
|
||||
{ name = "openai" },
|
||||
@@ -1148,7 +1105,6 @@ dependencies = [
|
||||
requires-dist = [
|
||||
{ name = "cryptography", specifier = "~=42.0.0" },
|
||||
{ name = "dotenv", specifier = ">=0.9.9" },
|
||||
{ name = "elasticsearch", specifier = "~=9.4.0" },
|
||||
{ name = "fastapi", specifier = "~=0.115.0" },
|
||||
{ name = "httpx", specifier = "~=0.27.0" },
|
||||
{ name = "openai", specifier = "~=2.41.0" },
|
||||
@@ -1182,15 +1138,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/e0/f9/0595336914c5619e5f28a1fb793285925a8cd4b432c9da0a987836c7f822/shellingham-1.5.4-py2.py3-none-any.whl", hash = "sha256:7ecfff8f2fd72616f7481040475a65b2bf8af90a56c89140852d1120324e8686", size = 9755, upload-time = "2023-10-24T04:13:38.866Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "six"
|
||||
version = "1.17.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031, upload-time = "2024-12-04T17:35:28.174Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sniffio"
|
||||
version = "1.3.1"
|
||||
@@ -1421,15 +1368,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/18/67/36e9267722cc04a6b9f15c7f3441c2363321a3ea07da7ae0c0707beb2a9c/typing_extensions-4.15.0-py3-none-any.whl", hash = "sha256:f0fa19c6845758ab08074a0cfa8b7aecb71c999ca73d62883bc25cc018c4e548", size = 44614, upload-time = "2025-08-25T13:49:24.86Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "urllib3"
|
||||
version = "2.7.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/53/0c/06f8b233b8fd13b9e5ee11424ef85419ba0d8ba0b3138bf360be2ff56953/urllib3-2.7.0.tar.gz", hash = "sha256:231e0ec3b63ceb14667c67be60f2f2c40a518cb38b03af60abc813da26505f4c", size = 433602, upload-time = "2026-05-07T16:13:18.596Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/7f/3e/5db95bcf282c52709639744ca2a8b149baccf648e39c8cc87553df9eae0c/urllib3-2.7.0-py3-none-any.whl", hash = "sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897", size = 131087, upload-time = "2026-05-07T16:13:17.151Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "uvicorn"
|
||||
version = "0.29.0"
|
||||
|
||||
@@ -22,6 +22,7 @@ encoder.ts
|
||||
git_push.sh
|
||||
index.ts
|
||||
model/accessGrant.ts
|
||||
model/allPatentsResponse.ts
|
||||
model/authAccount.ts
|
||||
model/authScope.ts
|
||||
model/author.ts
|
||||
@@ -61,16 +62,46 @@ model/dehydratedSource.ts
|
||||
model/dfgProjectDetails.ts
|
||||
model/dfgProjectPage.ts
|
||||
model/dfgProjectSummary.ts
|
||||
model/euCordisProjectResponse.ts
|
||||
model/euOrganizationProjectSummary.ts
|
||||
model/euOrganizationProjectSummaryPage.ts
|
||||
model/euProjectData.ts
|
||||
model/filterInformation.ts
|
||||
model/filterProperties.ts
|
||||
model/fp7EurosciVoc.ts
|
||||
model/fp7LegalBasis.ts
|
||||
model/fp7Organization.ts
|
||||
model/fp7ProjectDetails.ts
|
||||
model/fp7ProjectIPR.ts
|
||||
model/fp7Publication.ts
|
||||
model/fp7ReportSummary.ts
|
||||
model/fp7Topic.ts
|
||||
model/fp7WebLink.ts
|
||||
model/funderByAuthor.ts
|
||||
model/fundersByAuthorResponse.ts
|
||||
model/fundingProject.ts
|
||||
model/fundingProjectPage.ts
|
||||
model/fwci.ts
|
||||
model/groupByResult.ts
|
||||
model/h2020Deliverable.ts
|
||||
model/h2020ErcPI.ts
|
||||
model/h2020EurosciVoc.ts
|
||||
model/h2020LegalBasis.ts
|
||||
model/h2020Organization.ts
|
||||
model/h2020ProjectDetails.ts
|
||||
model/h2020Publication.ts
|
||||
model/h2020ReportSummary.ts
|
||||
model/h2020Topic.ts
|
||||
model/h2020WebLink.ts
|
||||
model/hEUDeliverable.ts
|
||||
model/hEUEurosciVoc.ts
|
||||
model/hEULegalBasis.ts
|
||||
model/hEUOrganization.ts
|
||||
model/hEUProjectDetails.ts
|
||||
model/hEUPublication.ts
|
||||
model/hEUReportSummary.ts
|
||||
model/hEUTopic.ts
|
||||
model/hEUWebLink.ts
|
||||
model/hTTPValidationError.ts
|
||||
model/identityGrant.ts
|
||||
model/institution.ts
|
||||
@@ -81,6 +112,7 @@ model/institutionInformation.ts
|
||||
model/institutionNetworkNode.ts
|
||||
model/institutionPage.ts
|
||||
model/institutionsListResponse.ts
|
||||
model/ipcClassification.ts
|
||||
model/item.ts
|
||||
model/itemCreate.ts
|
||||
model/itemPage.ts
|
||||
|
||||
@@ -22,9 +22,13 @@ import {
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
// @ts-ignore
|
||||
import { AllPatentsResponse } from '../model/allPatentsResponse';
|
||||
// @ts-ignore
|
||||
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||
// @ts-ignore
|
||||
import { PatentEntry } from '../model/patentEntry';
|
||||
// @ts-ignore
|
||||
import { PatentsByAuthorResponse } from '../model/patentsByAuthorResponse';
|
||||
|
||||
// @ts-ignore
|
||||
@@ -44,6 +48,285 @@ export class PatentsService extends BaseService {
|
||||
super(basePath, configuration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all patents with pagination and search.
|
||||
* @endpoint get /api/inse-service/patents
|
||||
* @param page
|
||||
* @param size
|
||||
* @param search
|
||||
* @param source
|
||||
* @param sortBy
|
||||
* @param sortDirection
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getAllPatents(
|
||||
page?: number,
|
||||
size?: number,
|
||||
search?: string,
|
||||
source?: string,
|
||||
sortBy?: string,
|
||||
sortDirection?: string,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<AllPatentsResponse>;
|
||||
public getAllPatents(
|
||||
page?: number,
|
||||
size?: number,
|
||||
search?: string,
|
||||
source?: string,
|
||||
sortBy?: string,
|
||||
sortDirection?: string,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<AllPatentsResponse>>;
|
||||
public getAllPatents(
|
||||
page?: number,
|
||||
size?: number,
|
||||
search?: string,
|
||||
source?: string,
|
||||
sortBy?: string,
|
||||
sortDirection?: string,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<AllPatentsResponse>>;
|
||||
public getAllPatents(
|
||||
page?: number,
|
||||
size?: number,
|
||||
search?: string,
|
||||
source?: string,
|
||||
sortBy?: string,
|
||||
sortDirection?: string,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>page,
|
||||
'page',
|
||||
);
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>size,
|
||||
'size',
|
||||
);
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>search,
|
||||
'search',
|
||||
);
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>source,
|
||||
'source',
|
||||
);
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>sortBy,
|
||||
'sort_by',
|
||||
);
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>sortDirection,
|
||||
'sort_direction',
|
||||
);
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (
|
||||
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
|
||||
) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/inse-service/patents`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<AllPatentsResponse>(
|
||||
'get',
|
||||
`${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns one publication by OpenAlex ID or DOI.
|
||||
* @endpoint get /api/inse-service/patents/{identifier}
|
||||
* @param identifier
|
||||
* @param prefix Application Prefix (EP or US)
|
||||
* @param title Do we want to fallback to title search if ID and DOI dont work?
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getPatentByIdOrTitle(
|
||||
identifier: string,
|
||||
prefix?: string,
|
||||
title?: string,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<PatentEntry>;
|
||||
public getPatentByIdOrTitle(
|
||||
identifier: string,
|
||||
prefix?: string,
|
||||
title?: string,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<PatentEntry>>;
|
||||
public getPatentByIdOrTitle(
|
||||
identifier: string,
|
||||
prefix?: string,
|
||||
title?: string,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<PatentEntry>>;
|
||||
public getPatentByIdOrTitle(
|
||||
identifier: string,
|
||||
prefix?: string,
|
||||
title?: string,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
if (identifier === null || identifier === undefined) {
|
||||
throw new Error(
|
||||
'Required parameter identifier was null or undefined when calling getPatentByIdOrTitle.',
|
||||
);
|
||||
}
|
||||
|
||||
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>prefix,
|
||||
'prefix',
|
||||
);
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>title,
|
||||
'title',
|
||||
);
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (
|
||||
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
|
||||
) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/inse-service/patents/${this.configuration.encodeParam({ name: 'identifier', value: identifier, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<PatentEntry>(
|
||||
'get',
|
||||
`${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get patents matched to an author by name.
|
||||
* @endpoint get /api/inse-service/authors/{author_id}/patents
|
||||
|
||||
@@ -33,6 +33,8 @@ import { DfgProjectDetails } from '../model/dfgProjectDetails';
|
||||
// @ts-ignore
|
||||
import { DfgProjectPage } from '../model/dfgProjectPage';
|
||||
// @ts-ignore
|
||||
import { EuCordisProjectResponse } from '../model/euCordisProjectResponse';
|
||||
// @ts-ignore
|
||||
import { EuOrganizationProjectSummaryPage } from '../model/euOrganizationProjectSummaryPage';
|
||||
// @ts-ignore
|
||||
import { FundingProjectPage } from '../model/fundingProjectPage';
|
||||
@@ -758,6 +760,109 @@ export class ProjectsService extends BaseService {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a single EU Cordis project.
|
||||
* Returns a single EU Cordis project based on its ID.
|
||||
* @endpoint get /api/projects/eu/{id}
|
||||
* @param id The ID of the EU Cordis project to retrieve.
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getSingleEuCordisProject(
|
||||
id: string,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<EuCordisProjectResponse>;
|
||||
public getSingleEuCordisProject(
|
||||
id: string,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<EuCordisProjectResponse>>;
|
||||
public getSingleEuCordisProject(
|
||||
id: string,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<EuCordisProjectResponse>>;
|
||||
public getSingleEuCordisProject(
|
||||
id: string,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
if (id === null || id === undefined) {
|
||||
throw new Error(
|
||||
'Required parameter id was null or undefined when calling getSingleEuCordisProject.',
|
||||
);
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (
|
||||
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
|
||||
) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/projects/eu/${this.configuration.encodeParam({ name: 'id', value: id, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<EuCordisProjectResponse>(
|
||||
'get',
|
||||
`${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get bund projects.
|
||||
* Returns a page of bund projects based on the provided pagination parameters and optional institution filter.
|
||||
|
||||
@@ -619,14 +619,16 @@ export class WorksService extends BaseService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns one publication.
|
||||
* @endpoint get /api/works/detail/{work_id}
|
||||
* @param workId The OpenAlex work id, for example W2741809807.
|
||||
* Returns one publication by OpenAlex ID or DOI.
|
||||
* @endpoint get /api/works/detail/{identifier}
|
||||
* @param identifier The OpenAlex work id (e.g., W2741809807) or DOI number of the publication.
|
||||
* @param title Do we want to fallback to title search if ID and DOI dont work?
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getWork(
|
||||
workId: string,
|
||||
identifier: string,
|
||||
title?: string,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
@@ -636,7 +638,8 @@ export class WorksService extends BaseService {
|
||||
},
|
||||
): Observable<Work>;
|
||||
public getWork(
|
||||
workId: string,
|
||||
identifier: string,
|
||||
title?: string,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
@@ -646,7 +649,8 @@ export class WorksService extends BaseService {
|
||||
},
|
||||
): Observable<HttpResponse<Work>>;
|
||||
public getWork(
|
||||
workId: string,
|
||||
identifier: string,
|
||||
title?: string,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
@@ -656,7 +660,8 @@ export class WorksService extends BaseService {
|
||||
},
|
||||
): Observable<HttpEvent<Work>>;
|
||||
public getWork(
|
||||
workId: string,
|
||||
identifier: string,
|
||||
title?: string,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
@@ -665,12 +670,19 @@ export class WorksService extends BaseService {
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
if (workId === null || workId === undefined) {
|
||||
if (identifier === null || identifier === undefined) {
|
||||
throw new Error(
|
||||
'Required parameter workId was null or undefined when calling getWork.',
|
||||
'Required parameter identifier was null or undefined when calling getWork.',
|
||||
);
|
||||
}
|
||||
|
||||
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>title,
|
||||
'title',
|
||||
);
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (bearer) required
|
||||
@@ -709,10 +721,11 @@ export class WorksService extends BaseService {
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/works/detail/${this.configuration.encodeParam({ name: 'workId', value: workId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`;
|
||||
let localVarPath = `/api/works/detail/${this.configuration.encodeParam({ name: 'identifier', value: identifier, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<Work>('get', `${basePath}${localVarPath}`, {
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
import { PatentEntry } from './patentEntry';
|
||||
|
||||
|
||||
export interface AllPatentsResponse {
|
||||
total: number;
|
||||
page: number;
|
||||
size: number;
|
||||
patents: Array<PatentEntry>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
import { EuProjectData } from './euProjectData';
|
||||
|
||||
|
||||
/**
|
||||
* Response model for EU Cordis project endpoints.
|
||||
*/
|
||||
export interface EuCordisProjectResponse {
|
||||
/**
|
||||
* Indicates if the request was successful
|
||||
*/
|
||||
success: boolean;
|
||||
project_type?: string | null;
|
||||
eu_project_data?: EuProjectData | null;
|
||||
error?: string | null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
import { H2020ProjectDetails } from './h2020ProjectDetails';
|
||||
import { Fp7ProjectDetails } from './fp7ProjectDetails';
|
||||
import { HEUOrganization } from './hEUOrganization';
|
||||
import { HEUPublication } from './hEUPublication';
|
||||
import { Fp7WebLink } from './fp7WebLink';
|
||||
import { HEUWebLink } from './hEUWebLink';
|
||||
import { HEUDeliverable } from './hEUDeliverable';
|
||||
import { Fp7ProjectIPR } from './fp7ProjectIPR';
|
||||
import { HEUEurosciVoc } from './hEUEurosciVoc';
|
||||
import { H2020ErcPI } from './h2020ErcPI';
|
||||
import { HEULegalBasis } from './hEULegalBasis';
|
||||
import { HEUTopic } from './hEUTopic';
|
||||
import { Fp7ReportSummary } from './fp7ReportSummary';
|
||||
import { HEUReportSummary } from './hEUReportSummary';
|
||||
import { HEUProjectDetails } from './hEUProjectDetails';
|
||||
|
||||
|
||||
/**
|
||||
* The project data
|
||||
*/
|
||||
export interface EuProjectData {
|
||||
acronym?: string;
|
||||
contentUpdateDate?: string;
|
||||
ecMaxContribution?: number;
|
||||
ecSignatureDate?: string;
|
||||
endDate?: string;
|
||||
frameworkProgramme?: string;
|
||||
fundingScheme?: string;
|
||||
grantDoi?: string;
|
||||
humanValidated?: boolean;
|
||||
id?: string;
|
||||
keywords?: string;
|
||||
legalBasis?: string;
|
||||
masterCall?: string;
|
||||
nature?: string;
|
||||
objective?: string;
|
||||
rcn?: string;
|
||||
startDate?: string;
|
||||
status?: string;
|
||||
subCall?: string;
|
||||
title?: string;
|
||||
topics?: string;
|
||||
totalCost?: number;
|
||||
organizations?: Array<HEUOrganization>;
|
||||
publications?: Array<HEUPublication>;
|
||||
iprs?: Array<Fp7ProjectIPR>;
|
||||
report_summaries?: Array<Fp7ReportSummary>;
|
||||
topicsList?: Array<HEUTopic>;
|
||||
web_links?: Array<Fp7WebLink>;
|
||||
eurosciVoc?: Array<HEUEurosciVoc>;
|
||||
legalBasisList?: Array<HEULegalBasis>;
|
||||
organizationCount?: number;
|
||||
publicationCount?: number;
|
||||
iprCount?: number;
|
||||
deliverables?: Array<HEUDeliverable>;
|
||||
reportSummaries?: Array<HEUReportSummary>;
|
||||
webLinks?: Array<HEUWebLink>;
|
||||
ercPrincipalInvestigators?: Array<H2020ErcPI>;
|
||||
deliverableCount?: number;
|
||||
ercPiCount?: number;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* Fp7EurosciVoc
|
||||
*/
|
||||
export interface Fp7EurosciVoc {
|
||||
code?: string | null;
|
||||
description?: string | null;
|
||||
id?: string | null;
|
||||
path?: string | null;
|
||||
projectID?: string | null;
|
||||
title?: string | null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* Fp7LegalBasis
|
||||
*/
|
||||
export interface Fp7LegalBasis {
|
||||
id?: string | null;
|
||||
legalBasis?: string | null;
|
||||
projectID?: string | null;
|
||||
title?: string | null;
|
||||
uniqueProgrammePart?: string | null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* Fp7Organization
|
||||
*/
|
||||
export interface Fp7Organization {
|
||||
SME?: boolean | null;
|
||||
active?: boolean | null;
|
||||
activityType?: string | null;
|
||||
city?: string | null;
|
||||
contactForm?: string | null;
|
||||
contentUpdateDate?: string | null;
|
||||
country?: string | null;
|
||||
ecContribution?: number | null;
|
||||
endOfParticipation?: boolean | null;
|
||||
geolocation?: string | null;
|
||||
id?: string | null;
|
||||
name?: string | null;
|
||||
netEcContribution?: number | null;
|
||||
nutsCode?: string | null;
|
||||
order?: number | null;
|
||||
organisationID?: string | null;
|
||||
organizationURL?: string | null;
|
||||
postCode?: string | null;
|
||||
projectAcronym?: string | null;
|
||||
projectID?: string | null;
|
||||
rcn?: string | null;
|
||||
role?: string | null;
|
||||
shortName?: string | null;
|
||||
street?: string | null;
|
||||
totalCost?: number | null;
|
||||
vatNumber?: string | null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
import { Fp7EurosciVoc } from './fp7EurosciVoc';
|
||||
import { Fp7WebLink } from './fp7WebLink';
|
||||
import { Fp7Publication } from './fp7Publication';
|
||||
import { Fp7ReportSummary } from './fp7ReportSummary';
|
||||
import { Fp7Topic } from './fp7Topic';
|
||||
import { Fp7ProjectIPR } from './fp7ProjectIPR';
|
||||
import { Fp7Organization } from './fp7Organization';
|
||||
import { Fp7LegalBasis } from './fp7LegalBasis';
|
||||
|
||||
|
||||
/**
|
||||
* Comprehensive FP7 Project model combining all related entities. This model extends the base Fp7Project with all associated data.
|
||||
*/
|
||||
export interface Fp7ProjectDetails {
|
||||
acronym?: string | null;
|
||||
contentUpdateDate?: string | null;
|
||||
ecMaxContribution?: number | null;
|
||||
ecSignatureDate?: string | null;
|
||||
endDate?: string | null;
|
||||
frameworkProgramme?: string | null;
|
||||
fundingScheme?: string | null;
|
||||
grantDoi?: string | null;
|
||||
humanValidated?: boolean | null;
|
||||
id?: string | null;
|
||||
keywords?: string | null;
|
||||
legalBasis?: string | null;
|
||||
masterCall?: string | null;
|
||||
nature?: string | null;
|
||||
objective?: string | null;
|
||||
rcn?: string | null;
|
||||
startDate?: string | null;
|
||||
status?: string | null;
|
||||
subCall?: string | null;
|
||||
title?: string | null;
|
||||
topics?: string | null;
|
||||
totalCost?: number | null;
|
||||
organizations?: Array<Fp7Organization> | null;
|
||||
publications?: Array<Fp7Publication> | null;
|
||||
iprs?: Array<Fp7ProjectIPR> | null;
|
||||
report_summaries?: Array<Fp7ReportSummary> | null;
|
||||
topicsList?: Array<Fp7Topic> | null;
|
||||
web_links?: Array<Fp7WebLink> | null;
|
||||
eurosciVoc?: Array<Fp7EurosciVoc> | null;
|
||||
legalBasisList?: Array<Fp7LegalBasis> | null;
|
||||
organizationCount?: number | null;
|
||||
publicationCount?: number | null;
|
||||
iprCount?: number | null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* Fp7ProjectIPR
|
||||
*/
|
||||
export interface Fp7ProjectIPR {
|
||||
applicantName?: string | null;
|
||||
applicationDate?: string | null;
|
||||
applicationIdentifier?: string | null;
|
||||
applicationKind?: string | null;
|
||||
applicationPrefix?: string | null;
|
||||
awardDate?: string | null;
|
||||
awardIdentifier?: string | null;
|
||||
awardKind?: string | null;
|
||||
awardPrefix?: string | null;
|
||||
epoAppUrl?: string | null;
|
||||
epoPubUrl?: string | null;
|
||||
id?: string | null;
|
||||
organisationID?: string | null;
|
||||
patentFamilyIdentifier?: string | null;
|
||||
patentType?: string | null;
|
||||
priorityDate?: string | null;
|
||||
projectID?: string | null;
|
||||
title?: string | null;
|
||||
type?: string | null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* Fp7Publication
|
||||
*/
|
||||
export interface Fp7Publication {
|
||||
authors?: string | null;
|
||||
collection?: string | null;
|
||||
contentUpdateDate?: string | null;
|
||||
doi?: string | null;
|
||||
id?: string | null;
|
||||
isPublishedAs?: string | null;
|
||||
journalNumber?: string | null;
|
||||
journalTitle?: string | null;
|
||||
projectAcronym?: string | null;
|
||||
projectID?: string | null;
|
||||
publishedPages?: string | null;
|
||||
publishedYear?: number | null;
|
||||
publisher?: string | null;
|
||||
qaProcessedDoi?: string | null;
|
||||
rcn?: string | null;
|
||||
repositoryUrl?: string | null;
|
||||
title?: string | null;
|
||||
volume?: string | null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* Fp7ReportSummary
|
||||
*/
|
||||
export interface Fp7ReportSummary {
|
||||
attachments?: string | null;
|
||||
contentUpdateDate?: string | null;
|
||||
id?: string | null;
|
||||
projectAcronym?: string | null;
|
||||
projectID?: string | null;
|
||||
rcn?: string | null;
|
||||
title?: string | null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* Fp7Topic
|
||||
*/
|
||||
export interface Fp7Topic {
|
||||
id?: string | null;
|
||||
projectID?: string | null;
|
||||
title?: string | null;
|
||||
topic?: string | null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* Fp7WebLink
|
||||
*/
|
||||
export interface Fp7WebLink {
|
||||
archivedDate?: string | null;
|
||||
availableLanguages?: string | null;
|
||||
id?: string | null;
|
||||
linkId?: string | null;
|
||||
projectID?: string | null;
|
||||
represents?: string | null;
|
||||
source?: string | null;
|
||||
status?: string | null;
|
||||
type?: string | null;
|
||||
url?: string | null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* H2020Deliverable
|
||||
*/
|
||||
export interface H2020Deliverable {
|
||||
collection?: string | null;
|
||||
contentUpdateDate?: string | null;
|
||||
deliverableType?: string | null;
|
||||
description?: string | null;
|
||||
projectAcronym?: string | null;
|
||||
projectID?: string | null;
|
||||
rcn?: string | null;
|
||||
url?: string | null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* H2020ErcPI
|
||||
*/
|
||||
export interface H2020ErcPI {
|
||||
firstName?: string | null;
|
||||
fundingScheme?: string | null;
|
||||
id?: string | null;
|
||||
lastName?: string | null;
|
||||
organisationID?: string | null;
|
||||
projectAcronym?: string | null;
|
||||
projectID?: string | null;
|
||||
title?: string | null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* H2020EurosciVoc
|
||||
*/
|
||||
export interface H2020EurosciVoc {
|
||||
code?: string | null;
|
||||
description?: string | null;
|
||||
id?: string | null;
|
||||
path?: string | null;
|
||||
projectID?: string | null;
|
||||
title?: string | null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* H2020LegalBasis
|
||||
*/
|
||||
export interface H2020LegalBasis {
|
||||
id?: string | null;
|
||||
legalBasis?: string | null;
|
||||
projectID?: string | null;
|
||||
title?: string | null;
|
||||
uniqueProgrammePart?: string | null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* H2020Organization
|
||||
*/
|
||||
export interface H2020Organization {
|
||||
SME?: boolean | null;
|
||||
active?: boolean | null;
|
||||
activityType?: string | null;
|
||||
city?: string | null;
|
||||
contactForm?: string | null;
|
||||
contentUpdateDate?: string | null;
|
||||
country?: string | null;
|
||||
ecContribution?: number | null;
|
||||
endOfParticipation?: boolean | null;
|
||||
geolocation?: string | null;
|
||||
id?: string | null;
|
||||
name?: string | null;
|
||||
netEcContribution?: number | null;
|
||||
nutsCode?: string | null;
|
||||
order?: number | null;
|
||||
organisationID?: string | null;
|
||||
organizationURL?: string | null;
|
||||
postCode?: string | null;
|
||||
projectAcronym?: string | null;
|
||||
projectID?: string | null;
|
||||
rcn?: string | null;
|
||||
role?: string | null;
|
||||
shortName?: string | null;
|
||||
street?: string | null;
|
||||
totalCost?: number | null;
|
||||
vatNumber?: string | null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
import { H2020LegalBasis } from './h2020LegalBasis';
|
||||
import { H2020ErcPI } from './h2020ErcPI';
|
||||
import { H2020Deliverable } from './h2020Deliverable';
|
||||
import { H2020WebLink } from './h2020WebLink';
|
||||
import { H2020Publication } from './h2020Publication';
|
||||
import { H2020ReportSummary } from './h2020ReportSummary';
|
||||
import { H2020Topic } from './h2020Topic';
|
||||
import { H2020EurosciVoc } from './h2020EurosciVoc';
|
||||
import { H2020Organization } from './h2020Organization';
|
||||
|
||||
|
||||
/**
|
||||
* Comprehensive Horizon 2020 Project model combining all related entities. This model extends the base H2020Project with all associated data.
|
||||
*/
|
||||
export interface H2020ProjectDetails {
|
||||
acronym?: string | null;
|
||||
contentUpdateDate?: string | null;
|
||||
ecMaxContribution?: number | null;
|
||||
ecSignatureDate?: string | null;
|
||||
endDate?: string | null;
|
||||
frameworkProgramme?: string | null;
|
||||
fundingScheme?: string | null;
|
||||
grantDoi?: string | null;
|
||||
humanValidated?: boolean | null;
|
||||
id?: string | null;
|
||||
keywords?: string | null;
|
||||
legalBasis?: string | null;
|
||||
masterCall?: string | null;
|
||||
nature?: string | null;
|
||||
objective?: string | null;
|
||||
rcn?: string | null;
|
||||
startDate?: string | null;
|
||||
status?: string | null;
|
||||
subCall?: string | null;
|
||||
title?: string | null;
|
||||
topics?: string | null;
|
||||
totalCost?: number | null;
|
||||
organizations?: Array<H2020Organization> | null;
|
||||
publications?: Array<H2020Publication> | null;
|
||||
deliverables?: Array<H2020Deliverable> | null;
|
||||
reportSummaries?: Array<H2020ReportSummary> | null;
|
||||
topicsList?: Array<H2020Topic> | null;
|
||||
webLinks?: Array<H2020WebLink> | null;
|
||||
eurosciVoc?: Array<H2020EurosciVoc> | null;
|
||||
legalBasisList?: Array<H2020LegalBasis> | null;
|
||||
ercPrincipalInvestigators?: Array<H2020ErcPI> | null;
|
||||
organizationCount?: number | null;
|
||||
publicationCount?: number | null;
|
||||
deliverableCount?: number | null;
|
||||
ercPiCount?: number | null;
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user