Merge remote-tracking branch 'origin/dev' into topic-colored-chips

This commit is contained in:
2026-06-26 11:42:04 +02:00
120 changed files with 12396 additions and 567 deletions
+2
View File
@@ -34,6 +34,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 +62,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,
+39 -5
View File
@@ -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
@@ -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
@@ -0,0 +1,133 @@
#!/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 .elastic_search_client import MissingApiKeyError
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]:
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()
@@ -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
@@ -97,13 +95,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 +150,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 = 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}},
}
+221
View File
@@ -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,150 @@
#!/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 .elastic_search_client import MissingApiKeyError
from .ipc_lookup import IpcHierarchyKeys
from .ipc_lookup import build_ipc_classification
from .ipc_lookup import parse_ipc_symbol
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]:
async with httpx.AsyncClient(
base_url=self.base_url,
timeout=self.timeout,
transport=self.transport,
) as client:
response = await client.post(
f"/{IPC_INDEX}/_search",
headers=self._headers(),
json=payload,
)
response.raise_for_status()
return response.json()
+331 -156
View File
@@ -1,156 +1,331 @@
#!/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 fastapi import HTTPException
from starlette.status import HTTP_502_BAD_GATEWAY
from starlette.status import HTTP_503_SERVICE_UNAVAILABLE
from starlette.status import HTTP_404_NOT_FOUND
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 .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 = _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)
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 httpx.HTTPError 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,
)
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
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()
try:
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)
)
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
await _enrich_patents_classifications(patents, ipc_search_client)
return model.AllPatentsResponse(
total=total,
page=page,
size=size,
patents=patents,
)
+28 -1
View File
@@ -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]
+48 -4
View File
@@ -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,67 @@
import httpx
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():
requests: list[str] = []
def handler(request: httpx.Request) -> httpx.Response:
requests.append(request.url.path)
return httpx.Response(
200,
json={
"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",
}
},
]
}
},
)
transport = httpx.MockTransport(handler)
client = IpcSearchClient(api_key="test-key", transport=transport)
result = await client.resolve_symbols(["H01L 21/02"])
assert len(requests) >= 1
assert all(path.endswith(f"/{IPC_INDEX}/_search") for path in requests)
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():
def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(200, json={"hits": {"hits": []}})
client = IpcSearchClient(api_key="test-key", transport=httpx.MockTransport(handler))
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"]
@@ -0,0 +1,282 @@
import logging
from concurrent.futures import ThreadPoolExecutor, as_completed
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},
]
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 = 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 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"
def _fetch_related_entities_parallel(
project_id: str,
entity_configs: List[Dict[str, Any]],
max_workers: int = 8,
) -> 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'.
max_workers: Maximum number of concurrent Elasticsearch requests.
Returns:
Dictionary mapping each config 'key' to a list of validated entities.
"""
def _fetch_one(config: Dict[str, Any]):
entities = _fetch_related_entities(
project_ids=[project_id],
index_pattern=config["index_pattern"],
model_class=config["model_class"],
)
return config["key"], entities.get(project_id, [])
results: Dict[str, List[Any]] = {}
with ThreadPoolExecutor(max_workers=max_workers) as executor:
futures = {executor.submit(_fetch_one, cfg): cfg["key"] for cfg in entity_configs}
for future in as_completed(futures):
try:
key, data = future.result()
results[key] = data
except Exception as e:
key = futures[future]
logger.error(f"Parallel fetch failed for '{key}': {e}")
results[key] = []
return results
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 = 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
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 = _fetch_related_entities_parallel(project_id, _FP7_ENTITY_CONFIGS)
return Fp7ProjectDetails.from_project_with_relations(project=project, **related)
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 = _fetch_related_entities_parallel(project_id, _H2020_ENTITY_CONFIGS)
return H2020ProjectDetails.from_project_with_relations(project=project, **related)
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 = _fetch_related_entities_parallel(project_id, _HEU_ENTITY_CONFIGS)
return HEUProjectDetails.from_project_with_relations(project=project, **related)
+23 -2
View File
@@ -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__)
@@ -193,7 +195,7 @@ def _complete_response_to_bund_project_page(
def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails]:
"""Fetches the details of a single Bund project based on its project ID.
"""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,7 +203,9 @@ 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(
index=ESIndex.PROJECTS_BUND_V1,
@@ -557,6 +561,22 @@ def get_cordis_eu_projects_by_project_ids(
)
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 = get_enriched_cordis_project_by_id(
project_id=project_id
)
return enriched_project
# DFG
+85
View File
@@ -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])
@@ -131,6 +137,85 @@ def get_single_bund_project(
)
@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
}
},
)
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 = 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.",
+15 -1
View File
@@ -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,7 +27,10 @@ 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__)
@@ -322,6 +326,15 @@ def get_single_bund_project(
raise NotFoundException(f"BUND project with id {project_id} not found")
return project
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 = 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
def search_cordis_eu_projects_for_author_id(
raw_oa_author_id: str,
@@ -347,3 +360,4 @@ def search_cordis_eu_projects_for_author_id(
)
return funding_project_page
+8 -17
View File
@@ -197,27 +197,18 @@ 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]
+58 -19
View File
@@ -7,10 +7,10 @@ import logging
from typing import Any
import httpx
import urllib
from .. import config
from inse.integrations import elasticsearch
from inse.model import ESCluster, ESIndex
class MissingApiKeyError(Exception):
pass
@@ -164,23 +164,62 @@ class OpenAlexWorksSearchClient:
response.raise_for_status()
return response.json()
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
}
}
}
print(body)
response = 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 = elasticsearch.search(index=f'{ESIndex.OPENALEX_WORKS}*',body=body,cluster=ESCluster.NES,size=1)
return response
+11 -8
View File
@@ -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)
@@ -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
+283
View File
@@ -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
+105
View File
@@ -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.
+23 -10
View File
@@ -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,17 @@
/**
* 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,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.
*/
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;
}
+69
View File
@@ -0,0 +1,69 @@
/**
* 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;
}
+21
View File
@@ -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.
*/
/**
* Fp7EurosciVoc
*/
export interface Fp7EurosciVoc {
code?: string | null;
description?: string | null;
id?: string | null;
path?: string | null;
projectID?: string | null;
title?: string | null;
}
+20
View File
@@ -0,0 +1,20 @@
/**
* 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,41 @@
/**
* 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,56 @@
/**
* 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;
}
+34
View File
@@ -0,0 +1,34 @@
/**
* 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,33 @@
/**
* 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,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.
*/
/**
* 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;
}
+19
View File
@@ -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.
*/
/**
* Fp7Topic
*/
export interface Fp7Topic {
id?: string | null;
projectID?: string | null;
title?: string | null;
topic?: string | null;
}
+25
View File
@@ -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.
*/
/**
* 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,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.
*/
/**
* 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;
}
+23
View File
@@ -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.
*/
/**
* 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,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.
*/
/**
* 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,20 @@
/**
* 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,41 @@
/**
* 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,59 @@
/**
* 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;
}
@@ -0,0 +1,33 @@
/**
* 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.
*/
/**
* H2020Publication
*/
export interface H2020Publication {
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,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.
*/
/**
* H2020ReportSummary
*/
export interface H2020ReportSummary {
attachments?: string | null;
contentUpdateDate?: string | null;
id?: string | null;
projectAcronym?: string | null;
projectID?: string | null;
rcn?: string | null;
title?: string | null;
}
+19
View File
@@ -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.
*/
/**
* H2020Topic
*/
export interface H2020Topic {
id?: string | null;
projectID?: string | null;
title?: string | null;
topic?: string | null;
}
+25
View File
@@ -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.
*/
/**
* H2020WebLink
*/
export interface H2020WebLink {
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,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.
*/
/**
* HEUDeliverable
*/
export interface HEUDeliverable {
collection?: string | null;
contentUpdateDate?: string | null;
deliverableType?: string | null;
description?: string | null;
projectAcronym?: string | null;
projectID?: string | null;
rcn?: string | null;
url?: string | null;
}
+21
View File
@@ -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.
*/
/**
* HEUEurosciVoc
*/
export interface HEUEurosciVoc {
code?: string | null;
description?: string | null;
id?: string | null;
path?: string | null;
projectID?: string | null;
title?: string | null;
}
+20
View File
@@ -0,0 +1,20 @@
/**
* 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.
*/
/**
* HEULegalBasis
*/
export interface HEULegalBasis {
id?: string | null;
legalBasis?: string | null;
projectID?: string | null;
title?: string | null;
uniqueProgrammePart?: string | null;
}
@@ -0,0 +1,41 @@
/**
* 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.
*/
/**
* HEUOrganization
*/
export interface HEUOrganization {
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,56 @@
/**
* 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 { HEULegalBasis } from './hEULegalBasis';
import { HEUOrganization } from './hEUOrganization';
import { HEUTopic } from './hEUTopic';
import { HEUPublication } from './hEUPublication';
import { HEUWebLink } from './hEUWebLink';
import { HEUReportSummary } from './hEUReportSummary';
import { HEUDeliverable } from './hEUDeliverable';
import { HEUEurosciVoc } from './hEUEurosciVoc';
/**
* Comprehensive Horizon Europe Project model combining all related entities. This model extends the base HEUProject with all associated data.
*/
export interface HEUProjectDetails {
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<HEUOrganization> | null;
publications?: Array<HEUPublication> | null;
deliverables?: Array<HEUDeliverable> | null;
reportSummaries?: Array<HEUReportSummary> | null;
topicsList?: Array<HEUTopic> | null;
webLinks?: Array<HEUWebLink> | null;
eurosciVoc?: Array<HEUEurosciVoc> | null;
legalBasisList?: Array<HEULegalBasis> | null;
organizationCount?: number | null;
publicationCount?: number | null;
deliverableCount?: number | null;
}
@@ -0,0 +1,33 @@
/**
* 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.
*/
/**
* HEUPublication
*/
export interface HEUPublication {
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,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.
*/
/**
* HEUReportSummary
*/
export interface HEUReportSummary {
attachments?: string | null;
contentUpdateDate?: string | null;
id?: string | null;
projectAcronym?: string | null;
projectID?: string | null;
rcn?: string | null;
title?: string | null;
}
+19
View File
@@ -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.
*/
/**
* HEUTopic
*/
export interface HEUTopic {
id?: string | null;
projectID?: string | null;
title?: string | null;
topic?: string | null;
}
+25
View File
@@ -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.
*/
/**
* HEUWebLink
*/
export interface HEUWebLink {
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,18 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export interface IpcClassification {
symbol: string;
section?: string | null;
class?: string | null;
subclass?: string | null;
main_group?: string | null;
subgroup?: string | null;
}
+30
View File
@@ -38,16 +38,45 @@ export * from './dehydratedSource';
export * from './dfgProjectDetails';
export * from './dfgProjectPage';
export * from './dfgProjectSummary';
export * from './euCordisProjectResponse';
export * from './euOrganizationProjectSummary';
export * from './euOrganizationProjectSummaryPage';
export * from './filterInformation';
export * from './filterProperties';
export * from './fp7EurosciVoc';
export * from './fp7LegalBasis';
export * from './fp7Organization';
export * from './fp7ProjectDetails';
export * from './fp7ProjectIPR';
export * from './fp7Publication';
export * from './fp7ReportSummary';
export * from './fp7Topic';
export * from './fp7WebLink';
export * from './funderByAuthor';
export * from './fundersByAuthorResponse';
export * from './fundingProject';
export * from './fundingProjectPage';
export * from './fwci';
export * from './groupByResult';
export * from './h2020Deliverable';
export * from './h2020ErcPI';
export * from './h2020EurosciVoc';
export * from './h2020LegalBasis';
export * from './h2020Organization';
export * from './h2020ProjectDetails';
export * from './h2020Publication';
export * from './h2020ReportSummary';
export * from './h2020Topic';
export * from './h2020WebLink';
export * from './hEUDeliverable';
export * from './hEUEurosciVoc';
export * from './hEULegalBasis';
export * from './hEUOrganization';
export * from './hEUProjectDetails';
export * from './hEUPublication';
export * from './hEUReportSummary';
export * from './hEUTopic';
export * from './hEUWebLink';
export * from './hTTPValidationError';
export * from './identityGrant';
export * from './institution';
@@ -69,6 +98,7 @@ export * from './matchedOfficer';
export * from './mentionedPerson';
export * from './meta';
export * from './model2YrMeanCitedness';
export * from './neteccontribution';
export * from './newsArticle';
export * from './newsArticleDetail';
export * from './newsPage';
@@ -0,0 +1,11 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export interface Neteccontribution {}
+25 -17
View File
@@ -1,22 +1,30 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export interface IpcClassification {
symbol: string;
section: string | null;
class: string | null;
subclass: string | null;
main_group: string | null;
subgroup: string | null;
}
export interface PatentEntry {
patent_id: string;
source: string;
title?: string | null;
abstract?: string | null;
publication_date?: string | null;
publication_year?: string | null;
inventors?: Array<string>;
assignees?: Array<string>;
ipc?: Array<string>;
country?: string | null;
title: string | null;
abstract: string | null;
publication_date: string | null;
publication_year: string | null;
application_number: string | null;
application_date: string | null;
kind: string | null;
application_type: string | null;
number_of_claims: number | null;
status: string | null;
inventors: string[];
assignees: string[];
ipc: string[];
ipc_descriptions: IpcClassification[];
cpc: string[];
cpc_descriptions: IpcClassification[];
country: string | null;
}
+40 -124
View File
@@ -7,7 +7,6 @@ import { personResolver } from './resolvers/person.resolver';
import { institutionResolver } from './resolvers/institution.resolver';
import { bundProjectPageResolver } from './resolvers/bund-project-page.resolver';
import { dfgProjectsResolver } from './resolvers/dfg-projects.resolver';
import { personNewsResolver } from './resolvers/person-news.resolver';
import { institutionsResolver } from './resolvers/institutions.resolver';
import { bundProjectsFundingResolver } from './resolvers/bund-projects-funding.resolver';
import { dfgSingleProjectResolver } from './resolvers/dfg-single-project-resolver';
@@ -16,7 +15,8 @@ import { cordisEuProjectPageResolver } from './resolvers/cordis-eu-project-page.
import { cordisEuProjectsFundingResolver } from './resolvers/cordis-eu-projects-funding.resolver';
import { fundingProjectPageResolver } from './resolvers/funding-project-page.resolver';
import { personCordisEuProjectPageResolver } from './resolvers/person-cordis-eu-project-page.resolver';
import { euSingleProjectResolver } from './resolvers/eu-single-project-resolver';
import { publicationResolver } from './resolvers/publication-resolver';
export const routes: Routes = [
{
path: '',
@@ -67,37 +67,17 @@ export const routes: Routes = [
'filterMode',
'filterYear',
];
// scalar params
const scalarChanged = keys.some(
(key) => to.queryParamMap.get(key) !== from.queryParamMap.get(key),
);
// multi-value param: topics
const toTopics = to.queryParamMap.getAll('topic');
const fromTopics = from.queryParamMap.getAll('topic');
const topicsChanged =
toTopics.length !== fromTopics.length ||
toTopics.some((t, i) => t !== fromTopics[i]);
return scalarChanged || topicsChanged;
},
},
{
path: 'news',
canActivate: [userGuard],
loadComponent: () =>
import('./modules/news/news.component').then((mod) => mod.NewsComponent),
},
{
path: 'news/:id',
canActivate: [userGuard],
loadComponent: () =>
import('./modules/news-detail/news-detail.component').then(
(mod) => mod.NewsDetailComponent,
),
},
{
path: 'publication/:publicationId',
canActivate: [userGuard],
@@ -105,29 +85,40 @@ export const routes: Routes = [
import('./modules/publication-detail/publication-detail.component').then(
(mod) => mod.PublicationDetailComponent,
),
resolve: {
publication: publicationResolver,
},
},
{
path: 'projects/dfg/:id',
canActivate: [userGuard],
pathMatch: 'full',
loadComponent: () =>
import('./modules/person-projects/dfg-details/dfg-details.component').then(
import('./modules/projects/dfg-details/dfg-details.component').then(
(mod) => mod.DfgDetailsComponent,
),
resolve: {
dfgSingleProject: dfgSingleProjectResolver,
},
resolve: { dfgSingleProject: dfgSingleProjectResolver },
},
{
path: 'projects/bund/:id',
canActivate: [userGuard],
pathMatch: 'full',
loadComponent: () =>
import('./modules/person-projects/bund-details/bund-details.component').then(
import('./modules/projects/bund-details/bund-details.component').then(
(mod) => mod.BundDetailsComponent,
),
resolve: { bundSingleProject: bundSingleProjectResolver },
},
{
path: 'projects/eu/:id',
canActivate: [userGuard],
pathMatch: 'full',
loadComponent: () =>
import('./modules/projects/eu-cordis-details/eu-details.component').then(
(mod) => mod.EuDetailsComponent,
),
resolve: {
bundSingleProject: bundSingleProjectResolver,
euSingleProject: euSingleProjectResolver,
},
},
{
@@ -143,11 +134,7 @@ export const routes: Routes = [
},
runGuardsAndResolvers: (from, to) => from.params['id'] !== to.params['id'],
children: [
{
path: '',
pathMatch: 'full',
redirectTo: 'overview',
},
{ path: '', pathMatch: 'full', redirectTo: 'overview' },
{
path: 'overview',
loadComponent: () =>
@@ -161,13 +148,9 @@ export const routes: Routes = [
import('./modules/person-projects/person-projects.component').then(
(mod) => mod.PersonProjectsComponent,
),
resolve: {
dfgProjectPage: dfgProjectsResolver,
personCordisEuProjectPage: personCordisEuProjectPageResolver,
},
resolve: { dfgProjectPage: dfgProjectsResolver },
runGuardsAndResolvers: (from, to) => {
const keys = ['page', 'size', 'sort_by', 'sort_direction', 'search'];
return keys.some(
(key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
);
@@ -186,37 +169,8 @@ export const routes: Routes = [
import('./modules/person-network/person-network.component').then(
(mod) => mod.PersonNetworkComponent,
),
resolve: {
collaborationNetwork: collaborationNetworkResolver,
},
resolve: { collaborationNetwork: collaborationNetworkResolver },
runGuardsAndResolvers: (from, to) => {
const network = from.data['collaborationNetwork'] as
| {
filter_information?: {
min_possible_year?: number;
max_possible_year?: number;
};
}
| undefined;
const filterInformation = network?.filter_information;
const defaultQueryParams: Record<string, string> = {
filter_by: 'works',
start_year: filterInformation?.min_possible_year
? String(filterInformation.min_possible_year)
: '',
end_year: filterInformation?.max_possible_year
? String(filterInformation.max_possible_year)
: '',
min_contributors: '2',
max_contributors: '10',
min_collaborations: '1',
max_collaborations: '100',
institutions: '',
topics: '',
};
const keys = [
'filter_by',
'start_year',
@@ -228,26 +182,11 @@ export const routes: Routes = [
'institutions',
'topics',
];
return keys.some((key) => {
const fromRawValue = from.queryParamMap.get(key);
const toRawValue = to.queryParamMap.get(key);
const fromValue =
fromRawValue === null || fromRawValue === ''
? defaultQueryParams[key]
: fromRawValue;
const toValue =
toRawValue === null || toRawValue === ''
? defaultQueryParams[key]
: toRawValue;
return fromValue !== toValue;
});
return keys.some(
(key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
);
},
},
{
path: 'funding',
loadComponent: () =>
@@ -255,23 +194,6 @@ export const routes: Routes = [
(mod) => mod.PersonFundingComponent,
),
},
{
path: 'news',
loadComponent: () =>
import('./modules/person-news/person-news.component').then(
(mod) => mod.PersonNewsComponent,
),
resolve: {
newsPage: personNewsResolver,
},
runGuardsAndResolvers: (from, to) => {
const keys = ['page', 'pageSize', 'sortOrder', 'query'];
return keys.some(
(key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
);
},
},
{
path: 'patents',
loadComponent: () =>
@@ -295,12 +217,9 @@ export const routes: Routes = [
import('./modules/institutions/institutions.component').then(
(mod) => mod.InstitutionsComponent,
),
resolve: {
institutionPage: institutionsResolver,
},
resolve: { institutionPage: institutionsResolver },
runGuardsAndResolvers: (from, to) => {
const keys = ['search', 'page', 'size', 'sort_by', 'sorting_order'];
return keys.some(
(key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
);
@@ -313,15 +232,9 @@ export const routes: Routes = [
import('./modules/institution/institution.component').then(
(mod) => mod.InstitutionComponent,
),
resolve: {
institution: institutionResolver,
},
resolve: { institution: institutionResolver },
children: [
{
path: '',
pathMatch: 'full',
redirectTo: 'overview',
},
{ path: '', pathMatch: 'full', redirectTo: 'overview' },
{
path: 'overview',
loadComponent: () =>
@@ -338,11 +251,10 @@ export const routes: Routes = [
},
{
path: 'projects',
loadComponent: () => {
return import('./modules/institution-projects/institution-projects.component').then(
loadComponent: () =>
import('./modules/institution-projects/institution-projects.component').then(
(mod) => mod.InstitutionProjectsComponent,
);
},
),
resolve: {
bundProjectPage: bundProjectPageResolver,
bundProjectsFunding: bundProjectsFundingResolver,
@@ -351,7 +263,6 @@ export const routes: Routes = [
},
runGuardsAndResolvers: (from, to) => {
const keys = ['page', 'size', 'sort_by', 'sort_direction', 'search'];
return keys.some(
(key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
);
@@ -366,9 +277,7 @@ export const routes: Routes = [
import('./modules/projects/projects.component').then(
(mod) => mod.ProjectsComponent,
),
resolve: {
fundingProjectPage: fundingProjectPageResolver,
},
resolve: { fundingProjectPage: fundingProjectPageResolver },
runGuardsAndResolvers: (from, to) => {
const keys = [
'search',
@@ -378,12 +287,19 @@ export const routes: Routes = [
'sort_by',
'sorting_order',
];
return keys.some(
(key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
);
},
},
{
path: 'patents',
canActivate: [userGuard],
loadComponent: () =>
import('./modules/patents/patents.component').then(
(mod) => mod.PatentsComponent,
),
},
{
path: 'error',
loadComponent: () =>
@@ -0,0 +1,316 @@
<div class="content">
<h1>Patente</h1>
<mat-divider />
<div class="search-and-filter">
<mat-form-field style="width: 100%">
<mat-label>Suche nach Titel oder Patent-Nr.</mat-label>
<input
matInput
type="search"
[value]="searchTerm"
(input)="onSearchInput($event)" />
<mat-icon matPrefix>search</mat-icon>
<button matIconButton matSuffix (click)="clearSearch()">
<mat-icon>clear</mat-icon>
</button>
</mat-form-field>
<div class="filter-row">
<mat-chip-listbox
[value]="activeFilter"
(change)="setFilterFromChip($event)">
<mat-chip-option value="all">Alle</mat-chip-option>
<mat-chip-option value="EPO">EPO</mat-chip-option>
<mat-chip-option value="USPTO">USPTO</mat-chip-option>
</mat-chip-listbox>
<div class="sorting">
<select
(change)="setSortDirection($any($event.target).value)"
[value]="sortDirection">
<option value="desc">Absteigend</option>
<option value="asc">Aufsteigend</option>
</select>
</div>
</div>
</div>
<mat-divider />
@if (loading) {
<div class="state-message">
<mat-progress-spinner diameter="36" mode="indeterminate" />
<span>Lade Patente...</span>
</div>
} @else if (error) {
<p class="state-message error">Fehler beim Laden der Patente.</p>
} @else if (showDetail && selectedPatent) {
<div class="detail-view">
<button type="button" class="back-btn" (click)="closeDetail()">
← Zurück zu den Patenten
</button>
<h2>{{ selectedPatent.title ?? selectedPatent.patent_id }}</h2>
<div class="patent-meta__list">
@for (row of getPatentMetadataRows(selectedPatent); track row.label) {
<div class="patent-meta__row">
<dt>{{ row.label }}</dt>
<dd>
@if (row.variant === 'source') {
<span
class="source-badge source-badge--{{
row.value.toLowerCase()
}}"
>{{ row.value }}</span
>
} @else {
{{ row.value }}
}
</dd>
</div>
}
</div>
@if (selectedPatent.abstract) {
<div class="detail-section">
<h4>Abstract</h4>
<p>{{ selectedPatent.abstract }}</p>
</div>
}
<div class="detail-section">
<h4>Erfinder</h4>
<ul class="tag-list">
@for (inv of selectedPatent.inventors; track inv) {
<li class="tag">{{ inv }}</li>
}
</ul>
</div>
@if (selectedPatent.assignees.length > 0) {
<div class="detail-section">
<h4>Anmelder</h4>
<ul class="tag-list">
@for (a of selectedPatent.assignees; track a) {
<li class="tag">{{ a }}</li>
}
</ul>
</div>
}
@if (selectedPatent.ipc_descriptions.length > 0) {
<div
class="detail-section classification-section classification-section--ipc">
<h4>Klassifikation (IPC)</h4>
<div class="classification-cards">
@for (
card of getClassificationCards(
selectedPatent.ipc_descriptions,
'IPC'
);
track card.key
) {
<article class="classification-card">
<header class="classification-card__header">
<div class="classification-card__codes">
@for (sym of card.symbols; track sym) {
<span class="classification-code">{{ sym }}</span>
}
</div>
<div class="classification-card__badges">
<span
class="classification-badge classification-badge--system"
>{{ card.system }}</span
>
<span
class="classification-badge classification-badge--level"
>{{ card.levelLabel }}</span
>
</div>
</header>
@if (card.primaryDescription) {
<p class="classification-summary">
{{
isClassificationExpanded(card.key)
? card.primaryDescription
: getDescriptionPreview(card.primaryDescription)
}}
</p>
@if (isLongDescription(card.primaryDescription)) {
<button
type="button"
class="classification-toggle"
(click)="toggleClassificationExpanded(card.key)">
{{
isClassificationExpanded(card.key)
? 'Weniger anzeigen'
: 'Mehr anzeigen'
}}
</button>
}
}
@if (card.hierarchy.length > 0) {
<dl class="classification-hierarchy">
@for (row of card.hierarchy; track row.label) {
<div class="classification-hierarchy__row">
<dt>{{ row.label }}</dt>
<dd>{{ row.value }}</dd>
</div>
}
</dl>
}
</article>
}
</div>
</div>
} @else if (selectedPatent.ipc.length > 0) {
<div class="detail-section">
<h4>Klassifikation (IPC)</h4>
<ul class="tag-list tag-list--compact">
@for (ipc of selectedPatent.ipc; track ipc) {
<li class="tag">{{ ipc }}</li>
}
</ul>
</div>
}
@if (selectedPatent.cpc_descriptions.length > 0) {
<div
class="detail-section classification-section classification-section--cpc">
<h4>Klassifikation (CPC)</h4>
<div class="classification-cards">
@for (
card of getClassificationCards(
selectedPatent.cpc_descriptions,
'CPC'
);
track card.key
) {
<article class="classification-card">
<header class="classification-card__header">
<div class="classification-card__codes">
@for (sym of card.symbols; track sym) {
<span class="classification-code">{{ sym }}</span>
}
</div>
<div class="classification-card__badges">
<span
class="classification-badge classification-badge--system"
>{{ card.system }}</span
>
<span
class="classification-badge classification-badge--level"
>{{ card.levelLabel }}</span
>
</div>
</header>
@if (card.primaryDescription) {
<p class="classification-summary">
{{
isClassificationExpanded(card.key)
? card.primaryDescription
: getDescriptionPreview(card.primaryDescription)
}}
</p>
@if (isLongDescription(card.primaryDescription)) {
<button
type="button"
class="classification-toggle"
(click)="toggleClassificationExpanded(card.key)">
{{
isClassificationExpanded(card.key)
? 'Weniger anzeigen'
: 'Mehr anzeigen'
}}
</button>
}
}
@if (card.hierarchy.length > 0) {
<dl class="classification-hierarchy">
@for (row of card.hierarchy; track row.label) {
<div class="classification-hierarchy__row">
<dt>{{ row.label }}</dt>
<dd>{{ row.value }}</dd>
</div>
}
</dl>
}
</article>
}
</div>
</div>
} @else if (selectedPatent.cpc.length > 0) {
<div class="detail-section">
<h4>Klassifikation (CPC)</h4>
<ul class="tag-list tag-list--compact">
@for (cpc of selectedPatent.cpc; track cpc) {
<li class="tag">{{ cpc }}</li>
}
</ul>
</div>
}
</div>
} @else if (patents.length === 0) {
<div class="no-results">
<p>Keine Patente gefunden.</p>
</div>
} @else {
<div class="cards">
@for (
patent of patents;
track patent.patent_id + (patent.publication_date ?? '')
) {
<mat-card
class="card"
appearance="outlined"
(click)="selectPatent(patent)">
<mat-card-header>
<mat-card-title>{{
patent.title ?? patent.patent_id
}}</mat-card-title>
<mat-card-subtitle>
<span
class="source-badge source-badge--{{
patent.source.toLowerCase()
}}"
>{{ patent.source }}</span
>
</mat-card-subtitle>
</mat-card-header>
<mat-card-content class="card-content">
<mat-divider />
<div class="card-metadata">
<span>{{ patent.patent_id }}</span>
<span>{{ formatDate(patent.publication_date) }}</span>
</div>
<mat-divider />
</mat-card-content>
<mat-card-footer>
<mat-card-actions>
<button
mat-button
(click)="selectPatent(patent); $event.stopPropagation()">
<mat-icon>info</mat-icon>
Übersicht
</button>
</mat-card-actions>
</mat-card-footer>
</mat-card>
}
</div>
}
<mat-divider />
@if (!showDetail) {
<mat-paginator
[length]="total"
[pageSize]="pageSize"
[pageIndex]="page"
[pageSizeOptions]="[10, 25, 50]"
(page)="handlePageChange($event)" />
}
</div>
@@ -0,0 +1,373 @@
.content {
display: flex;
flex-direction: column;
gap: 1rem;
padding: 1rem;
}
h1 {
margin: 0;
font-size: 2rem;
font-weight: 700;
padding: 1rem 0 0;
}
.sorting {
display: flex;
justify-content: flex-end;
gap: 0.5rem;
select {
padding: 0.75rem;
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm);
font-size: 1rem;
cursor: pointer;
}
}
.search-and-filter {
padding: 0 1rem;
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.filter-row {
display: flex;
justify-content: space-between;
align-items: center;
}
.state-message {
display: flex;
align-items: center;
gap: 12px;
padding: 24px 1rem;
color: #666;
font-size: 14px;
&.error {
color: #c0392b;
}
}
.cards {
display: grid;
gap: 1.5rem;
grid-template-columns: repeat(4, 1fr);
padding: 0 1rem;
}
@media (max-width: 900px) {
.cards {
grid-template-columns: repeat(2, 1fr);
}
}
@media (max-width: 600px) {
.cards {
grid-template-columns: 1fr;
}
}
mat-paginator {
background-color: var(--sg-background);
}
.card {
padding: 0.5rem;
background-color: var(--sg-background);
transition: transform 0.3s ease;
display: flex;
flex-direction: column;
gap: 0.5rem;
&:hover {
cursor: pointer;
transform: scale(1.05);
}
mat-card-title {
font-size: 14px;
font-weight: 600;
line-height: 1.4;
}
}
.card-content {
display: flex;
flex-direction: column;
justify-content: flex-end;
gap: 0.5rem;
flex: 1;
}
.card-metadata {
display: flex;
flex-direction: column;
gap: 0.2rem;
font-size: 0.9rem;
color: var(--sg-text-secondary);
}
mat-card-actions {
padding-top: 0.5rem;
display: flex;
gap: 0.5rem;
button {
width: 100%;
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm);
}
}
.source-badge {
display: inline-flex;
align-items: center;
padding: 3px 10px;
border-radius: 999px;
font-size: 0.75rem;
font-weight: 700;
&--epo {
background: #effaf3;
color: #24834f;
border: 1px solid #bdebcf;
}
&--uspto {
background: #f0f6ff;
color: #0b63ce;
border: 1px solid #bdd4ff;
}
}
.no-results {
text-align: center;
padding: 2rem;
color: var(--sg-text-secondary);
}
.detail-view {
padding: 1rem;
h2 {
margin: 0 0 1rem;
font-size: 1.4rem;
color: #333;
line-height: 1.4;
}
h4 {
margin: 16px 0 8px;
font-size: 14px;
color: #555;
font-weight: 600;
}
p {
font-size: 13px;
color: #444;
line-height: 1.6;
margin: 0;
}
}
.back-btn {
display: inline-flex;
align-items: center;
gap: 0.4rem;
margin-bottom: 1rem;
padding: 0.5rem 0.85rem;
border: 1px solid #d6e3f8;
border-radius: 999px;
background: #f8fbff;
color: #2563eb;
font-size: 0.9rem;
font-weight: 600;
cursor: pointer;
&:hover {
background: #eef5ff;
border-color: #bcd3f7;
}
}
.patent-meta__list {
margin: 12px 0 20px;
border: 1px solid #e2e8f4;
border-radius: 12px;
background: linear-gradient(180deg, #fff 0%, #f8faff 100%);
overflow: hidden;
}
.patent-meta__row {
display: grid;
grid-template-columns: minmax(130px, 38%) 1fr;
gap: 12px 16px;
align-items: center;
padding: 11px 16px;
border-top: 1px solid #eef2f8;
&:first-child {
border-top: 0;
}
dt {
margin: 0;
font-size: 12px;
font-weight: 500;
color: #64748b;
}
dd {
margin: 0;
font-size: 14px;
font-weight: 600;
color: #1e293b;
word-break: break-word;
}
}
.detail-section {
margin-top: 12px;
padding-top: 12px;
border-top: 1px solid #eee;
}
.tag-list {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin: 0;
padding: 0;
list-style: none;
&--compact .tag {
font-size: 0.75rem;
padding: 3px 8px;
}
}
.tag {
padding: 4px 10px;
border-radius: 999px;
background: #f0f6ff;
border: 1px solid #dbeafe;
color: #1e40af;
font-size: 0.8rem;
}
.classification-section {
&--ipc .classification-card {
background: #f0f6ff;
border-color: #bfdbfe;
}
&--ipc .classification-badge--system {
background: #dbeafe;
color: #1d4ed8;
}
&--cpc .classification-card {
background: #f0fdf4;
border-color: #bbf7d0;
}
&--cpc .classification-badge--system {
background: #dcfce7;
color: #15803d;
}
}
.classification-cards {
display: flex;
flex-direction: column;
gap: 10px;
}
.classification-card {
padding: 12px 14px;
border-radius: 10px;
border: 1px solid #dbeafe;
}
.classification-card__header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
flex-wrap: wrap;
}
.classification-card__codes {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.classification-card__badges {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.classification-code {
font-size: 0.9rem;
font-weight: 700;
color: #0f172a;
}
.classification-badge {
display: inline-flex;
align-items: center;
padding: 2px 8px;
border-radius: 999px;
font-size: 0.68rem;
font-weight: 700;
text-transform: uppercase;
}
.classification-badge--level {
background: #e2e8f0;
color: #475569;
}
.classification-summary {
margin: 10px 0 0;
font-size: 0.84rem;
line-height: 1.5;
color: #334155;
}
.classification-toggle {
margin-top: 6px;
padding: 0;
border: 0;
background: none;
color: #2563eb;
font-size: 0.78rem;
cursor: pointer;
&:hover {
text-decoration: underline;
}
}
.classification-hierarchy {
margin: 10px 0 0;
padding-top: 10px;
border-top: 1px solid rgba(15, 23, 42, 0.08);
}
.classification-hierarchy__row {
display: grid;
grid-template-columns: 88px 1fr;
gap: 8px;
margin-bottom: 6px;
dt {
margin: 0;
font-size: 0.72rem;
font-weight: 700;
color: #64748b;
text-transform: uppercase;
}
dd {
margin: 0;
font-size: 0.8rem;
line-height: 1.45;
color: #334155;
}
}
@@ -0,0 +1,354 @@
import { Component, OnInit, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
import { MatIconModule } from '@angular/material/icon';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatPaginatorModule, PageEvent } from '@angular/material/paginator';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatChipsModule } from '@angular/material/chips';
import { MatDividerModule } from '@angular/material/divider';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { debounceTime, distinctUntilChanged, Subject } from 'rxjs';
import { PatentsService } from '../../api/api/patents.service';
import { PatentEntry, IpcClassification } from '../../api/model/patentEntry';
type SourceFilter = 'all' | 'EPO' | 'USPTO';
type ClassificationSystem = 'IPC' | 'CPC';
interface ClassificationCard {
key: string;
symbols: string[];
system: ClassificationSystem;
levelLabel: string;
primaryDescription: string | null;
hierarchy: { label: string; value: string }[];
}
const DESCRIPTION_PREVIEW_LENGTH = 140;
@Component({
selector: 'app-patents',
imports: [
CommonModule,
RouterModule,
MatIconModule,
MatButtonModule,
MatCardModule,
MatFormFieldModule,
MatInputModule,
MatPaginatorModule,
MatProgressSpinnerModule,
MatChipsModule,
MatDividerModule,
],
templateUrl: './patents.component.html',
styleUrl: './patents.component.scss',
})
export class PatentsComponent implements OnInit {
private router = inject(Router);
private route = inject(ActivatedRoute);
private patentsApi = inject(PatentsService);
patents: PatentEntry[] = [];
total = 0;
page = 0;
pageSize = 10;
loading = true;
error = false;
searchTerm = '';
activeFilter: SourceFilter = 'all';
sortDirection: string = 'desc';
selectedPatent: PatentEntry | null = null;
showDetail = false;
private expandedClassificationKeys = new Set<string>();
private searchSubject = new Subject<string>();
constructor() {
this.searchSubject
.pipe(debounceTime(300), distinctUntilChanged(), takeUntilDestroyed())
.subscribe((term) => {
this.searchTerm = term;
this.page = 0;
this.selectedPatent = null;
this.showDetail = false;
this.loadPatents();
this.updateQueryParams();
});
}
ngOnInit(): void {
const qp = this.route.snapshot.queryParamMap;
this.searchTerm = qp.get('search') ?? '';
this.page = parseInt(qp.get('page') ?? '0', 10);
this.pageSize = parseInt(qp.get('size') ?? '10', 10);
const f = qp.get('source');
if (f === 'EPO' || f === 'USPTO') this.activeFilter = f;
const d = qp.get('sort_direction');
if (d === 'asc' || d === 'desc') this.sortDirection = d;
this.loadPatents();
}
private loadPatents(): void {
this.loading = true;
this.error = false;
const source = this.activeFilter === 'all' ? undefined : this.activeFilter;
this.patentsApi
.getAllPatents(
this.page,
this.pageSize,
this.searchTerm || undefined,
source,
'date',
this.sortDirection,
)
.subscribe({
next: (res) => {
this.patents = res.patents;
this.total = res.total;
this.loading = false;
},
error: () => {
this.error = true;
this.loading = false;
},
});
}
onSearchInput(event: Event): void {
this.searchSubject.next((event.target as HTMLInputElement).value);
}
clearSearch(): void {
this.searchTerm = '';
this.page = 0;
this.selectedPatent = null;
this.showDetail = false;
this.loadPatents();
this.updateQueryParams();
}
setFilterFromChip(event: any): void {
const val = event.value;
this.activeFilter = val === 'EPO' || val === 'USPTO' ? val : 'all';
this.page = 0;
this.selectedPatent = null;
this.showDetail = false;
this.loadPatents();
this.updateQueryParams();
}
setSortDirection(direction: string): void {
this.sortDirection = direction;
this.loadPatents();
this.updateQueryParams();
}
handlePageChange(event: PageEvent): void {
this.page = event.pageIndex;
this.pageSize = event.pageSize;
this.selectedPatent = null;
this.showDetail = false;
this.loadPatents();
this.updateQueryParams();
}
selectPatent(patent: PatentEntry): void {
this.selectedPatent = patent;
this.showDetail = true;
this.expandedClassificationKeys.clear();
}
closeDetail(): void {
this.showDetail = false;
this.selectedPatent = null;
this.expandedClassificationKeys.clear();
}
private updateQueryParams(): void {
this.router.navigate([], {
relativeTo: this.route,
queryParams: {
search: this.searchTerm || null,
page: this.page,
size: this.pageSize,
source: this.activeFilter === 'all' ? null : this.activeFilter,
sort_direction: this.sortDirection,
},
queryParamsHandling: 'merge',
replaceUrl: true,
});
}
formatDate(date: string | null): string {
if (!date) return '-';
const d = date.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3');
const parsed = new Date(d);
if (isNaN(parsed.getTime())) return date;
return new Intl.DateTimeFormat('de-DE').format(parsed);
}
getPublicationStageLabel(patent: PatentEntry): string | null {
return patent.kind ?? patent.application_type ?? null;
}
getPatentMetadataRows(patent: PatentEntry) {
const rows: { label: string; value: string; variant?: 'source' }[] = [];
rows.push({ label: 'Quelle', value: patent.source, variant: 'source' });
rows.push({ label: 'Patent-Nr.', value: patent.patent_id });
if (patent.publication_date)
rows.push({
label: 'Veröffentlichungsdatum',
value: this.formatDate(patent.publication_date),
});
if (patent.application_number)
rows.push({
label: 'Anmeldungsnummer',
value: patent.application_number,
});
if (patent.application_date)
rows.push({
label: 'Anmeldedatum',
value: this.formatDate(patent.application_date),
});
const stage = this.getPublicationStageLabel(patent);
if (stage)
rows.push({
label: patent.kind ? 'Publikationsstufe' : 'Anmeldungstyp',
value: this.formatMetadataLabel(stage),
});
if (patent.number_of_claims != null)
rows.push({ label: 'Ansprüche', value: String(patent.number_of_claims) });
if (patent.status)
rows.push({
label: 'Status',
value: this.formatMetadataLabel(patent.status),
});
return rows;
}
private formatMetadataLabel(value: string): string {
return value
.replace(/_/g, ' ')
.toLowerCase()
.replace(/\b\w/g, (c) => c.toUpperCase());
}
getClassificationCards(
entries: IpcClassification[] | undefined,
system: ClassificationSystem,
): ClassificationCard[] {
if (!entries?.length) return [];
const merged = new Map<string, ClassificationCard>();
for (const entry of entries) {
const card = this.buildClassificationCard(entry, system);
const mergeKey =
card.primaryDescription?.toLocaleLowerCase('en') ??
card.symbols[0] ??
card.key;
const existing = merged.get(mergeKey);
if (existing) {
for (const s of card.symbols) {
if (!existing.symbols.includes(s)) existing.symbols.push(s);
}
continue;
}
merged.set(mergeKey, card);
}
return [...merged.values()];
}
toggleClassificationExpanded(key: string): void {
this.expandedClassificationKeys.has(key)
? this.expandedClassificationKeys.delete(key)
: this.expandedClassificationKeys.add(key);
}
isClassificationExpanded(key: string): boolean {
return this.expandedClassificationKeys.has(key);
}
isLongDescription(text: string | null): boolean {
return !!text && text.length > DESCRIPTION_PREVIEW_LENGTH;
}
getDescriptionPreview(text: string | null): string {
if (!text) return '';
return text.length <= DESCRIPTION_PREVIEW_LENGTH
? text
: `${text.slice(0, DESCRIPTION_PREVIEW_LENGTH).trimEnd()}…`;
}
private buildClassificationCard(
entry: IpcClassification,
system: ClassificationSystem,
): ClassificationCard {
const level = this.getClassificationLevel(entry);
const primaryDescription = this.extractDescriptionText(entry[level.field]);
return {
key: `${system}-${entry.symbol}`,
symbols: [entry.symbol],
system,
levelLabel: level.label,
primaryDescription,
hierarchy: this.buildHierarchyRows(entry, primaryDescription),
};
}
private getClassificationLevel(entry: IpcClassification): {
label: string;
field: keyof IpcClassification;
} {
if (entry.subgroup) return { label: 'Untergruppe', field: 'subgroup' };
if (entry.main_group) return { label: 'Hauptgruppe', field: 'main_group' };
if (entry.subclass) return { label: 'Unterklasse', field: 'subclass' };
if (entry.section) return { label: 'Sektion', field: 'section' };
return { label: 'Code', field: 'symbol' };
}
private buildHierarchyRows(
entry: IpcClassification,
primaryDescription: string | null,
) {
const rows: { label: string; value: string }[] = [];
const seen = new Set<string>();
const addRow = (label: string, raw: string | null) => {
const value = this.extractDescriptionText(raw);
if (!value) return;
const norm = value.toLocaleLowerCase('en');
if (
seen.has(norm) ||
norm === primaryDescription?.toLocaleLowerCase('en')
)
return;
seen.add(norm);
rows.push({ label, value });
};
addRow('Sektion', entry.section);
addRow('Klasse', entry.class);
addRow('Unterklasse', entry.subclass);
return rows;
}
private extractDescriptionText(
value: string | null | undefined,
): string | null {
if (!value?.trim()) return null;
const text = value.includes(' - ')
? value.split(' - ').slice(1).join(' - ').trim()
: value.trim();
if (!text) return null;
const first = text.split(/[;|]/)[0]?.trim() ?? text;
return first === first.toUpperCase()
? first.charAt(0) + first.slice(1).toLowerCase()
: first;
}
}
@@ -6,32 +6,42 @@
<p class="message">Keine Patente gefunden.</p>
} @else {
<div class="patents-container">
<div class="patents-summary">
<p class="summary-line">
<span class="summary-value">{{ filteredPatents.length }}</span>
<span class="summary-label"> Patente</span>
</p>
<p class="summary-line">
<span class="summary-value">{{ getEpoCount() }}</span>
<span class="summary-label"> EPO</span>
</p>
<p class="summary-line">
<span class="summary-value">{{ getUsptoCount() }}</span>
<span class="summary-label"> USPTO</span>
</p>
</div>
@if (showDetail && selectedPatent) {
<button class="back-btn" (click)="showDetail = false">
← Zurück zu den Patenten
</button>
}
<div class="patents-content">
@if (showDetail && selectedPatent) {
<div class="patent-full-detail">
<button type="button" class="back-btn" (click)="closeDetail()">
← Zurück zu den Patenten
</button>
<h3>{{ selectedPatent.title ?? selectedPatent.patent_id }}</h3>
@if (hasPatentMetadata(selectedPatent)) {
<div class="patent-meta patent-meta--inline">
<dl class="patent-meta__list">
@for (
row of getPatentMetadataRows(selectedPatent);
track row.label
) {
<div class="patent-meta__row">
<dt>{{ row.label }}</dt>
<dd>
@if (row.variant === 'source') {
<span
class="source-badge source-badge--{{
row.value.toLowerCase()
}}">
{{ row.value }}
</span>
} @else {
{{ row.value }}
}
</dd>
</div>
}
</dl>
</div>
}
@if (selectedPatent.abstract) {
<div class="detail-section">
<h4>Abstract</h4>
@@ -48,7 +58,9 @@
</ul>
</div>
@if (hasAsignees(selectedPatent)) {
@if (
selectedPatent.assignees && selectedPatent.assignees.length > 0
) {
<div class="detail-section">
<h4>Anmelder</h4>
<ul class="tag-list">
@@ -59,7 +71,77 @@
</div>
}
@if (hasIpcs(selectedPatent)) {
@if (
selectedPatent.ipc_descriptions &&
selectedPatent.ipc_descriptions.length > 0
) {
<div
class="detail-section classification-section classification-section--ipc">
<h4>Klassifikation (IPC)</h4>
<div class="classification-cards">
@for (
card of getClassificationCards(
selectedPatent.ipc_descriptions,
'IPC'
);
track card.key
) {
<article class="classification-card">
<header class="classification-card__header">
<div class="classification-card__codes">
@for (symbol of card.symbols; track symbol) {
<span class="classification-code">{{ symbol }}</span>
}
</div>
<div class="classification-card__badges">
<span
class="classification-badge classification-badge--system"
>{{ card.system }}</span
>
<span
class="classification-badge classification-badge--level"
>{{ card.levelLabel }}</span
>
</div>
</header>
@if (card.primaryDescription) {
<p class="classification-summary">
{{
isClassificationExpanded(card.key)
? card.primaryDescription
: getDescriptionPreview(card.primaryDescription)
}}
</p>
@if (isLongDescription(card.primaryDescription)) {
<button
type="button"
class="classification-toggle"
(click)="toggleClassificationExpanded(card.key)">
{{
isClassificationExpanded(card.key)
? 'Weniger anzeigen'
: 'Mehr anzeigen'
}}
</button>
}
}
@if (card.hierarchy.length > 0) {
<dl class="classification-hierarchy">
@for (row of card.hierarchy; track row.label) {
<div class="classification-hierarchy__row">
<dt>{{ row.label }}</dt>
<dd>{{ row.value }}</dd>
</div>
}
</dl>
}
</article>
}
</div>
</div>
} @else if (selectedPatent.ipc && selectedPatent.ipc.length > 0) {
<div class="detail-section">
<h4>Klassifikation (IPC)</h4>
<ul class="tag-list tag-list--compact">
@@ -69,6 +151,78 @@
</ul>
</div>
}
@if (
selectedPatent.cpc_descriptions &&
selectedPatent.cpc_descriptions.length > 0
) {
<div
class="detail-section classification-section classification-section--cpc">
<h4>Klassifikation (CPC)</h4>
<div class="classification-cards">
@for (
card of getClassificationCards(
selectedPatent.cpc_descriptions,
'CPC'
);
track card.key
) {
<article class="classification-card">
<header class="classification-card__header">
<div class="classification-card__codes">
@for (symbol of card.symbols; track symbol) {
<span class="classification-code">{{ symbol }}</span>
}
</div>
<div class="classification-card__badges">
<span
class="classification-badge classification-badge--system"
>{{ card.system }}</span
>
<span
class="classification-badge classification-badge--level"
>{{ card.levelLabel }}</span
>
</div>
</header>
@if (card.primaryDescription) {
<p class="classification-summary">
{{
isClassificationExpanded(card.key)
? card.primaryDescription
: getDescriptionPreview(card.primaryDescription)
}}
</p>
@if (isLongDescription(card.primaryDescription)) {
<button
type="button"
class="classification-toggle"
(click)="toggleClassificationExpanded(card.key)">
{{
isClassificationExpanded(card.key)
? 'Weniger anzeigen'
: 'Mehr anzeigen'
}}
</button>
}
}
@if (card.hierarchy.length > 0) {
<dl class="classification-hierarchy">
@for (row of card.hierarchy; track row.label) {
<div class="classification-hierarchy__row">
<dt>{{ row.label }}</dt>
<dd>{{ row.value }}</dd>
</div>
}
</dl>
}
</article>
}
</div>
</div>
}
</div>
}
@@ -104,7 +258,10 @@
</tr>
</thead>
<tbody>
@for (patent of getPagedPatents(); track patent.patent_id) {
@for (
patent of getPagedPatents();
track trackPatent($index, patent)
) {
<tr
[class.selected]="selectedPatent === patent"
(click)="selectPatent(patent)">
@@ -142,11 +299,11 @@
}
</div>
@if (selectedPatent) {
@if (selectedPatent && !showDetail) {
<div class="patent-detail">
<h3>{{ selectedPatent.title ?? selectedPatent.patent_id }}</h3>
<div class="detail-stats">
<div class="stat stat--clickable" (click)="openDetail()">
<div class="stat">
<span class="stat-label">Quelle</span>
<span class="stat-value">
<span
@@ -164,14 +321,60 @@
<div class="stat">
<span class="stat-label">Datum</span>
<span class="stat-value">{{
formatDate(selectedPatent.publication_date || '')
formatDate(selectedPatent.publication_date)
}}</span>
</div>
@if (getPublicationStageLabel(selectedPatent); as stageLabel) {
<div class="stat">
<span class="stat-label">Publikationsstufe</span>
<span class="stat-value">{{ stageLabel }}</span>
</div>
}
</div>
@if (
getAbstractPreview(selectedPatent.abstract);
as abstractPreview
) {
<p class="patent-detail-preview">{{ abstractPreview }}</p>
}
<button
type="button"
class="patent-detail-action"
(click)="openDetail()">
<span class="patent-detail-action__label"
>Patentdetails anzeigen</span
>
<span class="material-icons" aria-hidden="true">chevron_right</span>
</button>
<p class="patent-detail-hint">
Abstract, Erfinder, Anmelder und IPC/CPC-Klassifikation
</p>
</div>
} @else {
<div class="patent-detail empty">
<p>Klicke auf ein Patent für Details.</p>
<div class="patent-detail overview">
<p class="overview-title">Patentübersicht</p>
<p class="overview-subtitle">
Alle Patente dieser Person im Überblick.
</p>
<div class="overview-stats">
<div class="overview-stat">
<span class="overview-value">{{ patents.length }}</span>
<span class="overview-label">Patente</span>
</div>
<div class="overview-stat">
<span class="overview-value">{{ getEpoCount() }}</span>
<span class="overview-label">EPO</span>
</div>
<div class="overview-stat">
<span class="overview-value">{{ getUsptoCount() }}</span>
<span class="overview-label">USPTO</span>
</div>
</div>
<p class="overview-hint">
Wähle links ein Patent aus, um Kurzinfos und Details zu sehen.
</p>
</div>
}
</div>
@@ -10,27 +10,6 @@
gap: 16px;
}
.patents-summary {
margin-bottom: 8px;
display: flex;
gap: 24px;
.summary-line {
margin: 0;
font-size: 14px;
color: #333;
}
.summary-label {
color: #333;
}
.summary-value {
font-weight: 600;
color: #333;
}
}
.sort-control {
display: inline-flex;
align-items: center;
@@ -154,6 +133,60 @@
min-height: 200px;
}
&.overview {
display: flex;
flex-direction: column;
gap: 12px;
.overview-title {
font-size: 15px;
font-weight: 600;
color: #333;
margin: 0;
}
.overview-subtitle {
font-size: 13px;
color: #888;
margin: 0;
}
.overview-stats {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 10px;
margin-top: 4px;
}
.overview-stat {
background: white;
border: 1px solid #e0e0e0;
border-radius: 8px;
padding: 12px 8px;
text-align: center;
.overview-value {
display: block;
font-size: 22px;
font-weight: 700;
color: #333;
}
.overview-label {
display: block;
font-size: 12px;
color: #888;
margin-top: 4px;
}
}
.overview-hint {
font-size: 12px;
color: #aaa;
margin: 0;
}
}
h3 {
margin: 0 0 16px 0;
font-size: 16px;
@@ -192,16 +225,50 @@
}
}
.stat--clickable {
.patent-detail-preview {
margin: 14px 0 0;
font-size: 13px;
line-height: 1.55;
color: #555;
}
.patent-detail-action {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
width: 100%;
margin-top: 16px;
padding: 12px 14px;
border: 1px solid #bdd4ff;
border-radius: 10px;
background: linear-gradient(180deg, #f8fbff 0%, #eef4ff 100%);
color: #0b63ce;
font-size: 14px;
font-weight: 600;
cursor: pointer;
transition:
border-color 0.15s,
background 0.15s;
background 0.15s,
box-shadow 0.15s;
&:hover {
border-color: #0b63ce;
background: #f0f6ff;
box-shadow: 0 2px 8px rgba(11, 99, 206, 0.12);
}
.material-icons {
font-size: 20px;
}
}
.patent-detail-hint {
margin: 8px 0 0;
font-size: 12px;
line-height: 1.4;
color: #888;
text-align: center;
}
.patent-full-detail {
@@ -212,7 +279,7 @@
background: #fafafa;
h3 {
margin: 0 0 16px 0;
margin: 0 0 4px 0;
font-size: 16px;
color: #333;
line-height: 1.4;
@@ -234,17 +301,40 @@
}
.back-btn {
border: none;
background: none;
color: #333;
display: inline-flex;
align-items: center;
gap: 0.4rem;
width: auto;
margin-bottom: 1rem;
padding: 0.5rem 0.85rem;
border: 1px solid #d6e3f8;
border-radius: 999px;
background: #f8fbff;
color: #2563eb;
font-size: 0.9rem;
font-weight: 600;
cursor: pointer;
font-size: 14px;
font-weight: 400;
padding: 0;
align-self: flex-start; // NEU
transition:
background-color 0.15s ease,
border-color 0.15s ease,
color 0.15s ease,
box-shadow 0.15s ease;
&:hover {
text-decoration: underline;
background: #eef5ff;
border-color: #bcd3f7;
color: #1d4ed8;
box-shadow: 0 1px 4px rgba(37, 99, 235, 0.12);
}
&:focus-visible {
outline: 2px solid #93c5fd;
outline-offset: 2px;
}
}
@@ -254,6 +344,51 @@
border-top: 1px solid #eee;
}
.patent-meta {
&--inline {
margin: 12px 0 20px;
}
&__list {
margin: 0;
border: 1px solid #e2e8f4;
border-radius: 12px;
background: linear-gradient(180deg, #fff 0%, #f8faff 100%);
box-shadow: 0 1px 3px rgba(15, 23, 42, 0.04);
overflow: hidden;
}
&__row {
display: grid;
grid-template-columns: minmax(130px, 38%) 1fr;
gap: 12px 16px;
align-items: center;
padding: 11px 16px;
border-top: 1px solid #eef2f8;
&:first-child {
border-top: 0;
}
dt {
margin: 0;
font-size: 12px;
font-weight: 500;
color: #64748b;
line-height: 1.35;
}
dd {
margin: 0;
font-size: 14px;
font-weight: 600;
color: #1e293b;
line-height: 1.35;
word-break: break-word;
}
}
}
.tag-list {
display: flex;
flex-wrap: wrap;
@@ -278,6 +413,132 @@
line-height: 1.3;
}
.classification-section {
&--ipc .classification-card {
background: #f0f6ff;
border-color: #bfdbfe;
}
&--ipc .classification-badge--system {
background: #dbeafe;
color: #1d4ed8;
}
&--cpc .classification-card {
background: #f0fdf4;
border-color: #bbf7d0;
}
&--cpc .classification-badge--system {
background: #dcfce7;
color: #15803d;
}
}
.classification-cards {
display: flex;
flex-direction: column;
gap: 10px;
}
.classification-card {
padding: 12px 14px;
border-radius: 10px;
border: 1px solid #dbeafe;
}
.classification-card__header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
flex-wrap: wrap;
}
.classification-card__codes {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.classification-card__badges {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.classification-code {
font-size: 0.9rem;
font-weight: 700;
color: #0f172a;
}
.classification-badge {
display: inline-flex;
align-items: center;
padding: 2px 8px;
border-radius: 999px;
font-size: 0.68rem;
font-weight: 700;
letter-spacing: 0.02em;
text-transform: uppercase;
}
.classification-badge--level {
background: #e2e8f0;
color: #475569;
}
.classification-summary {
margin: 10px 0 0;
font-size: 0.84rem;
line-height: 1.5;
color: #334155;
}
.classification-toggle {
margin-top: 6px;
padding: 0;
border: 0;
background: none;
color: #2563eb;
font-size: 0.78rem;
cursor: pointer;
&:hover {
text-decoration: underline;
}
}
.classification-hierarchy {
margin: 10px 0 0;
padding-top: 10px;
border-top: 1px solid rgba(15, 23, 42, 0.08);
}
.classification-hierarchy__row {
display: grid;
grid-template-columns: 88px 1fr;
gap: 8px;
margin-bottom: 6px;
dt {
margin: 0;
font-size: 0.72rem;
font-weight: 700;
color: #64748b;
text-transform: uppercase;
letter-spacing: 0.03em;
}
dd {
margin: 0;
font-size: 0.8rem;
line-height: 1.45;
color: #334155;
}
}
.pagination {
display: flex;
align-items: center;
@@ -2,10 +2,28 @@ import { Component, OnInit, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ActivatedRoute, Router } from '@angular/router';
import { PatentsService } from '../../api/api/patents.service';
import { PatentEntry } from '../../api';
import { PatentEntry, IpcClassification } from '../../api/model/patentEntry';
type SortMode = 'date' | 'title';
type SourceFilter = 'all' | 'EPO' | 'USPTO';
type ClassificationSystem = 'IPC' | 'CPC';
interface ClassificationCard {
key: string;
symbols: string[];
system: ClassificationSystem;
levelLabel: string;
primaryDescription: string | null;
hierarchy: { label: string; value: string }[];
}
interface PatentMetadataRow {
label: string;
value: string;
variant?: 'source';
}
const DESCRIPTION_PREVIEW_LENGTH = 140;
@Component({
selector: 'app-person-patents',
@@ -32,14 +50,7 @@ export class PersonPatentsComponent implements OnInit {
selectedPage = 1;
readonly pageSize = 10;
hasAsignees(selectedPatent: PatentEntry | null): boolean {
return !!selectedPatent?.assignees && selectedPatent.assignees.length > 0;
}
hasIpcs(selectedPatent: PatentEntry | null): boolean {
return !!selectedPatent?.ipc && selectedPatent.ipc.length > 0;
}
private expandedClassificationKeys = new Set<string>();
ngOnInit(): void {
this.route.parent?.paramMap.subscribe((params) => {
@@ -90,11 +101,18 @@ export class PersonPatentsComponent implements OnInit {
selectPatent(patent: PatentEntry): void {
this.selectedPatent = patent;
this.showDetail = false;
this.expandedClassificationKeys.clear();
this.updateQueryParams();
}
openDetail(): void {
this.showDetail = true;
this.expandedClassificationKeys.clear();
}
closeDetail(): void {
this.showDetail = false;
this.expandedClassificationKeys.clear();
}
private applyFilter(): void {
@@ -158,7 +176,7 @@ export class PersonPatentsComponent implements OnInit {
this.updateQueryParams();
}
formatDate(date: string | null): string {
formatDate(date: string | null | undefined): string {
if (!date) return '-';
const d = date.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3');
return new Intl.DateTimeFormat('de-DE').format(new Date(d));
@@ -171,4 +189,245 @@ export class PersonPatentsComponent implements OnInit {
getUsptoCount(): number {
return this.patents.filter((p) => p.source === 'USPTO').length;
}
trackPatent(_index: number, patent: PatentEntry): string {
return [
patent.source,
patent.patent_id,
patent.publication_date ?? '',
patent.kind ?? patent.application_type ?? '',
].join('|');
}
getAbstractPreview(abstract: string | null | undefined): string | null {
if (!abstract?.trim()) {
return null;
}
const text = abstract.trim();
if (text.length <= 160) {
return text;
}
return `${text.slice(0, 160).trimEnd()}…`;
}
getPublicationStageLabel(patent: PatentEntry): string | null {
if (patent.kind) {
return patent.kind;
}
if (patent.application_type) {
return patent.application_type;
}
return null;
}
hasPatentMetadata(_patent: PatentEntry): boolean {
return true;
}
getPatentMetadataRows(patent: PatentEntry): PatentMetadataRow[] {
const rows: PatentMetadataRow[] = [];
rows.push({ label: 'Quelle', value: patent.source, variant: 'source' });
rows.push({ label: 'Patent-Nr.', value: patent.patent_id });
if (patent.publication_date) {
rows.push({
label: 'Veröffentlichungsdatum',
value: this.formatDate(patent.publication_date),
});
}
if (patent.application_number) {
rows.push({
label: 'Anmeldungsnummer',
value: patent.application_number,
});
}
if (patent.application_date) {
rows.push({
label: 'Anmeldedatum',
value: this.formatDate(patent.application_date),
});
}
const stageLabel = this.getPublicationStageLabel(patent);
if (stageLabel) {
rows.push({
label: patent.kind ? 'Publikationsstufe' : 'Anmeldungstyp',
value: patent.kind ? stageLabel : this.formatMetadataLabel(stageLabel),
});
}
if (patent.number_of_claims != null) {
rows.push({ label: 'Ansprüche', value: String(patent.number_of_claims) });
}
if (patent.status) {
rows.push({
label: 'Status',
value: this.formatMetadataLabel(patent.status),
});
}
return rows;
}
private formatMetadataLabel(value: string): string {
return value
.replace(/_/g, ' ')
.toLowerCase()
.replace(/\b\w/g, (char) => char.toUpperCase());
}
getClassificationCards(
entries: IpcClassification[] | undefined,
system: ClassificationSystem,
): ClassificationCard[] {
if (!entries?.length) {
return [];
}
const merged = new Map<string, ClassificationCard>();
for (const entry of entries) {
const card = this.buildClassificationCard(entry, system);
const mergeKey =
card.primaryDescription?.toLocaleLowerCase('en') ??
card.symbols[0] ??
card.key;
const existing = merged.get(mergeKey);
if (existing) {
for (const symbol of card.symbols) {
if (!existing.symbols.includes(symbol)) {
existing.symbols.push(symbol);
}
}
continue;
}
merged.set(mergeKey, card);
}
return [...merged.values()];
}
toggleClassificationExpanded(key: string): void {
if (this.expandedClassificationKeys.has(key)) {
this.expandedClassificationKeys.delete(key);
return;
}
this.expandedClassificationKeys.add(key);
}
isClassificationExpanded(key: string): boolean {
return this.expandedClassificationKeys.has(key);
}
isLongDescription(text: string | null): boolean {
return !!text && text.length > DESCRIPTION_PREVIEW_LENGTH;
}
getDescriptionPreview(text: string | null): string {
if (!text) {
return '';
}
if (text.length <= DESCRIPTION_PREVIEW_LENGTH) {
return text;
}
return `${text.slice(0, DESCRIPTION_PREVIEW_LENGTH).trimEnd()}…`;
}
private buildClassificationCard(
entry: IpcClassification,
system: ClassificationSystem,
): ClassificationCard {
const level = this.getClassificationLevel(entry);
const primaryDescription = this.extractDescriptionText(entry[level.field]);
return {
key: `${system}-${entry.symbol}`,
symbols: [entry.symbol],
system,
levelLabel: level.label,
primaryDescription,
hierarchy: this.buildHierarchyRows(entry, primaryDescription),
};
}
private getClassificationLevel(entry: IpcClassification): {
label: string;
field: keyof IpcClassification;
} {
if (entry.subgroup) {
return { label: 'Untergruppe', field: 'subgroup' };
}
if (entry.main_group) {
return { label: 'Hauptgruppe', field: 'main_group' };
}
if (entry.subclass) {
return { label: 'Unterklasse', field: 'subclass' };
}
if (entry.section) {
return { label: 'Sektion', field: 'section' };
}
return { label: 'Code', field: 'symbol' };
}
private buildHierarchyRows(
entry: IpcClassification,
primaryDescription: string | null,
): { label: string; value: string }[] {
const rows: { label: string; value: string }[] = [];
const seen = new Set<string>();
const addRow = (label: string, raw: string | null) => {
const value = this.extractDescriptionText(raw);
if (!value) {
return;
}
const normalized = value.toLocaleLowerCase('en');
if (
seen.has(normalized) ||
normalized === primaryDescription?.toLocaleLowerCase('en')
) {
return;
}
seen.add(normalized);
rows.push({ label, value });
};
if (entry.section) {
addRow('Sektion', entry.section);
}
if (entry.class) {
addRow('Klasse', entry.class);
}
if (entry.subclass) {
addRow('Unterklasse', entry.subclass);
}
return rows;
}
private extractDescriptionText(
value: string | null | undefined,
): string | null {
if (!value?.trim()) {
return null;
}
const text = value.includes(' - ')
? value.split(' - ').slice(1).join(' - ').trim()
: value.trim();
if (!text) {
return null;
}
const firstSentence = text.split(/[;|]/)[0]?.trim() ?? text;
return this.normalizeDescriptionCase(firstSentence);
}
private normalizeDescriptionCase(text: string): string {
if (text !== text.toUpperCase()) {
return text;
}
return text.charAt(0) + text.slice(1).toLowerCase();
}
}
@@ -26,6 +26,14 @@
</p>
}
<div class="hero-actions">
<div
class="status-badge"
[style.background-color]="
getStatusColor(getStatusDisplay(bundProject.funding_end_date))
">
<mat-icon>circle</mat-icon>
<span>{{ getStatusDisplay(bundProject.funding_end_date) }}</span>
</div>
<!-- @if (bundProject.project_agency) {
<div class="agency-info" (click)="searchForAgency(bundProject.project_agency)">
<mat-icon>account_balance</mat-icon>
@@ -46,14 +54,23 @@
<mat-icon>calendar_today</mat-icon>
<div class="metric-content">
<strong>{{ getStartDate() || 'N/A' }}</strong>
<span>Startdatum</span>
<span>Förderbeginn</span>
</div>
</div>
<div class="metric-item">
<mat-icon>event_busy</mat-icon>
<div class="metric-content">
<strong>{{ getFundingStatus(getEndDate()) }}</strong>
<span>Enddatum</span>
<span>Förderende</span>
</div>
</div>
<div class="metric-item">
<mat-icon>access_time</mat-icon>
<div class="metric-content">
<strong>{{
getStatusDisplay(bundProject.funding_end_date)
}}</strong>
<span>Status</span>
</div>
</div>
@if (bundProject.funding_amount) {
@@ -77,18 +94,17 @@
</div>
</div>
@if (bundProject.description) {
<mat-card appearance="outlined" class="card description-card">
<div class="section-header">
<mat-icon>description</mat-icon>
<h2>Beschreibung</h2>
</div>
<p class="description-text">{{ bundProject.description }}</p>
</mat-card>
}
<div class="content-grid">
<main class="main-content">
@if (bundProject.description) {
<mat-card appearance="outlined" class="card description-card">
<div class="section-header">
<mat-icon>description</mat-icon>
<h2>Beschreibung</h2>
</div>
<p class="description-text">{{ bundProject.description }}</p>
</mat-card>
}
<!-- Beteiligte Personen -->
@if (getAssociatedPersons().length > 0) {
<mat-card appearance="outlined" class="card">
@@ -351,11 +367,11 @@
}
<!-- <div class="detail-row">
<dt>Startdatum</dt>
<dt>Förderbeginn</dt>
<dd>{{ getStartDate() || 'N/A' }}</dd>
</div>
<div class="detail-row">
<dt>Enddatum</dt>
<dt>Förderende</dt>
<dd>{{ getFundingStatus(getEndDate()) }}</dd>
</div> -->
@if (getDuration()) {

Some files were not shown because too many files have changed in this diff Show More