Compare commits
91
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
adc9599515 | ||
|
|
514e572eb9 | ||
|
|
0c2a45ba66 | ||
|
|
fa7e607f3e | ||
|
|
a0477fcdb1 | ||
|
|
f3539e4210 | ||
|
|
9cd109fc17 | ||
|
|
84f3314b60 | ||
|
|
514634d5f0 | ||
|
|
d1588ac5c1 | ||
|
|
239129e513 | ||
|
|
e21b84544c | ||
|
|
3b16f8d8fc | ||
|
|
be74063a51 | ||
|
|
c8b055902f | ||
|
|
124d65f8c9 | ||
|
|
db5156a02d | ||
|
|
9dadc1f12f | ||
|
|
08cfec6be0 | ||
|
|
28b57059b7 | ||
|
|
c3944b71e0 | ||
|
|
0cdacf20f7 | ||
|
|
b4fe867eee | ||
|
|
fc9c18f965 | ||
|
|
c211e8d210 | ||
|
|
d86c871918 | ||
|
|
7baddf2b54 | ||
|
|
e9178cb26e | ||
|
|
466b36fb88 | ||
|
|
86cbe025ca | ||
|
|
000b68758d | ||
|
|
e7cf85116d | ||
|
|
edb76054d5 | ||
|
|
6cd32eecec | ||
|
|
305ab7ba6a | ||
|
|
5396b45314 | ||
|
|
226ab22e69 | ||
|
|
8d4045d428 | ||
|
|
17f52d1e2d | ||
|
|
6c6f13de14 | ||
|
|
4945e3d7e7 | ||
|
|
37ef212304 | ||
|
|
7c85624c1c | ||
|
|
fb9d2c23d9 | ||
|
|
2d3ff1a092 | ||
|
|
70a517e456 | ||
|
|
98ef93f642 | ||
|
|
73e67fa336 | ||
|
|
dae9147cce | ||
|
|
44ab578078 | ||
|
|
513cfeaed4 | ||
|
|
dbd1616e36 | ||
|
|
09aeb537cf | ||
|
|
f644473f3d | ||
|
|
75e7d2313e | ||
|
|
6f81849364 | ||
|
|
9711c4694d | ||
|
|
82e3bb514c | ||
|
|
51a369de4a | ||
|
|
98ce10fcd4 | ||
|
|
dc2ef6fd20 | ||
|
|
11d20546b1 | ||
|
|
029bdb5bca | ||
|
|
b6618e030e | ||
|
|
23da3e44ba | ||
|
|
379f94ddc7 | ||
|
|
ebdf0b8eab | ||
|
|
b496cfd52c | ||
|
|
e9935207ea | ||
|
|
bb066117bc | ||
|
|
a7d41237eb | ||
|
|
13c4975932 | ||
|
|
a7620b1900 | ||
|
|
6ecc0acc23 | ||
|
|
563ade40e9 | ||
|
|
9ac9e1785e | ||
|
|
a5fe9728e8 | ||
|
|
bd39e16d9b | ||
|
|
6d3e68a759 | ||
|
|
79105b83b9 | ||
|
|
c298a388d0 | ||
|
|
0dd03e0ae0 | ||
|
|
977ac97241 | ||
|
|
d465ef6915 | ||
|
|
bc7b7784ea | ||
|
|
db853f72a1 | ||
|
|
e5efd351f0 | ||
|
|
11eb898745 | ||
|
|
08669a4776 | ||
|
|
7442a56b0a | ||
|
|
9432d01135 |
Vendored
+3
@@ -28,6 +28,9 @@ pipeline {
|
||||
}
|
||||
|
||||
stage('Save Docker image') {
|
||||
when {
|
||||
branch 'main'
|
||||
}
|
||||
steps {
|
||||
sh 'docker save ${IMAGE_PREFIX}-app:${IMAGE_VERSION} | gzip > app-image.tar.gz'
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -35,15 +35,6 @@ headers = {
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
def float_array_to_base64(vector):
|
||||
"""
|
||||
Convert a float vector into a Base64 string representing 32-bit big-endian float bytes.
|
||||
Elasticsearch expects big-endian floats for binary/Base64 dense_vector encoding.
|
||||
"""
|
||||
arr = np.asarray(vector, dtype=np.float32)
|
||||
big_endian_bytes = arr.astype('>f4').tobytes()
|
||||
return base64.b64encode(big_endian_bytes).decode('utf-8')
|
||||
|
||||
def split_into_sentences(text):
|
||||
if not text:
|
||||
return []
|
||||
@@ -52,77 +43,6 @@ def split_into_sentences(text):
|
||||
# Filter out empty or extremely short sentences
|
||||
return [s for s in sentences if len(s.strip()) > 3]
|
||||
|
||||
def check_and_update_mapping():
|
||||
print("Checking 'topicvectors' index...")
|
||||
|
||||
with httpx.Client(timeout=30.0) as client:
|
||||
exists_resp = client.head(f"{ELASTIC_URL}topicvectors", headers=headers)
|
||||
if exists_resp.status_code == 404:
|
||||
print("Index 'topicvectors' does not exist. Creating index with mapping...")
|
||||
create_payload = {
|
||||
"mappings": {
|
||||
"properties": {
|
||||
"id": {"type": "keyword"},
|
||||
"display_name": {
|
||||
"type": "text",
|
||||
"fields": {
|
||||
"keyword": {"type": "keyword", "ignore_above": 256}
|
||||
}
|
||||
},
|
||||
"display_name_vector": {
|
||||
"type": "dense_vector",
|
||||
"dims": 768,
|
||||
"index": True,
|
||||
"similarity": "cosine",
|
||||
"index_options": {
|
||||
"type": "int8_hnsw",
|
||||
"m": 16,
|
||||
"ef_construction": 100
|
||||
}
|
||||
},
|
||||
"description": {"type": "text"},
|
||||
"description_vectors": {
|
||||
"type": "nested",
|
||||
"properties": {
|
||||
"vector": {
|
||||
"type": "dense_vector",
|
||||
"dims": 768,
|
||||
"index": True,
|
||||
"similarity": "cosine",
|
||||
"index_options": {
|
||||
"type": "int8_hnsw",
|
||||
"m": 16,
|
||||
"ef_construction": 100
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"keywords": {
|
||||
"type": "text",
|
||||
"fields": {
|
||||
"keyword": {"type": "keyword"}
|
||||
}
|
||||
},
|
||||
"cited_by_count": {"type": "long"},
|
||||
"works_count": {"type": "long"},
|
||||
"updated_date": {"type": "date"},
|
||||
"created_date": {"type": "date"}
|
||||
}
|
||||
}
|
||||
}
|
||||
resp = client.put(
|
||||
f"{ELASTIC_URL}topicvectors",
|
||||
json=create_payload,
|
||||
headers=headers
|
||||
)
|
||||
if resp.status_code == 200:
|
||||
print("Successfully created 'topicvectors' index.")
|
||||
else:
|
||||
print(f"Failed to create index: {resp.status_code} - {resp.text}")
|
||||
resp.raise_for_status()
|
||||
else:
|
||||
print("Index 'topicvectors' already exists.")
|
||||
|
||||
def fetch_all_topics():
|
||||
print("Fetching topics from 'openalex-topics'...")
|
||||
topics = []
|
||||
@@ -204,8 +124,6 @@ def bulk_index_topics(topics, display_name_vectors, nested_description_vectors):
|
||||
print(f"Indexed batch {i} to {i + len(batch_topics)}")
|
||||
|
||||
def main():
|
||||
check_and_update_mapping()
|
||||
|
||||
topics = fetch_all_topics()
|
||||
if not topics:
|
||||
print("No topics found. Exiting.")
|
||||
|
||||
@@ -1,150 +1,114 @@
|
||||
{
|
||||
"query": "Robotics",
|
||||
"max_score": 22.734766,
|
||||
"query": "localization",
|
||||
"max_score": 23.237041,
|
||||
"results": [
|
||||
{
|
||||
"topic_name": "Soft Robotics and Applications",
|
||||
"score": 22.734766
|
||||
},
|
||||
{
|
||||
"topic_name": "Robotics and Automated Systems",
|
||||
"score": 21.997686
|
||||
},
|
||||
{
|
||||
"topic_name": "Educational Robotics and Engineering",
|
||||
"score": 21.919401
|
||||
},
|
||||
{
|
||||
"topic_name": "Prosthetics and Rehabilitation Robotics",
|
||||
"score": 21.846806
|
||||
},
|
||||
{
|
||||
"topic_name": "Micro and Nano Robotics",
|
||||
"score": 21.820261
|
||||
},
|
||||
{
|
||||
"topic_name": "Reinforcement Learning in Robotics",
|
||||
"score": 21.757397
|
||||
"topic_name": "Indoor and Outdoor Localization Technologies",
|
||||
"score": 23.237041
|
||||
},
|
||||
{
|
||||
"topic_name": "Robotics and Sensor-Based Localization",
|
||||
"score": 19.993645
|
||||
"score": 21.511477
|
||||
},
|
||||
{
|
||||
"topic_name": "Social Robot Interaction and HRI",
|
||||
"score": 13.187252
|
||||
"topic_name": "Spectral Theory in Mathematical Physics",
|
||||
"score": 14.039959
|
||||
},
|
||||
{
|
||||
"topic_name": "Robotic Locomotion and Control",
|
||||
"score": 12.283064
|
||||
"topic_name": "Socioeconomic Development in MENA",
|
||||
"score": 11.518878
|
||||
},
|
||||
{
|
||||
"topic_name": "Power Line Inspection Robots",
|
||||
"score": 11.873396
|
||||
"topic_name": "Electrical Fault Detection and Protection",
|
||||
"score": 10.770052
|
||||
},
|
||||
{
|
||||
"topic_name": "Mechatronics Education and Applications",
|
||||
"score": 11.171629
|
||||
"topic_name": "Machine Learning in Bioinformatics",
|
||||
"score": 10.322677
|
||||
},
|
||||
{
|
||||
"topic_name": "Educational Technology and Optimization",
|
||||
"score": 10.924184
|
||||
"topic_name": "Software System Performance and Reliability",
|
||||
"score": 10.112644
|
||||
},
|
||||
{
|
||||
"topic_name": "Mechanical and Thermal Properties Analysis",
|
||||
"score": 10.924184
|
||||
"topic_name": "Quantum many-body systems",
|
||||
"score": 10.112644
|
||||
},
|
||||
{
|
||||
"topic_name": "Psychiatry, Mental Health, Neuroscience",
|
||||
"score": 10.687462
|
||||
"topic_name": "Random lasers and scattering media",
|
||||
"score": 10.112644
|
||||
},
|
||||
{
|
||||
"topic_name": "Advanced Materials and Mechanics",
|
||||
"score": 10.460782
|
||||
"topic_name": "Insect Pheromone Research and Control",
|
||||
"score": 9.910988
|
||||
},
|
||||
{
|
||||
"topic_name": "Wetland Management and Conservation",
|
||||
"score": 10.460782
|
||||
"topic_name": "Tactile and Sensory Interactions",
|
||||
"score": 9.910988
|
||||
},
|
||||
{
|
||||
"topic_name": "Artificial Intelligence Applications",
|
||||
"score": 10.243518
|
||||
"topic_name": "Handwritten Text Recognition Techniques",
|
||||
"score": 9.910988
|
||||
},
|
||||
{
|
||||
"topic_name": "Digitalization, Law, and Regulation",
|
||||
"score": 10.243518
|
||||
"topic_name": "Integrated Circuits and Semiconductor Failure Analysis",
|
||||
"score": 9.910988
|
||||
},
|
||||
{
|
||||
"topic_name": "Engineering and Technology Innovations",
|
||||
"score": 10.243518
|
||||
"topic_name": "Medical Imaging and Analysis",
|
||||
"score": 9.7172165
|
||||
},
|
||||
{
|
||||
"topic_name": "Advanced Algorithms and Applications",
|
||||
"score": 10.035095
|
||||
"topic_name": "Microwave Imaging and Scattering Analysis",
|
||||
"score": 9.7172165
|
||||
},
|
||||
{
|
||||
"topic_name": "Teaching and Learning Programming",
|
||||
"score": 10.035095
|
||||
"topic_name": "Neurology and Historical Studies",
|
||||
"score": 9.7172165
|
||||
},
|
||||
{
|
||||
"topic_name": "Distributed Control Multi-Agent Systems",
|
||||
"score": 10.035095
|
||||
"topic_name": "High-Velocity Impact and Material Behavior",
|
||||
"score": 9.7172165
|
||||
},
|
||||
{
|
||||
"topic_name": "Advanced Scientific and Engineering Studies",
|
||||
"score": 9.834986
|
||||
"topic_name": "Software Engineering Research",
|
||||
"score": 9.530875
|
||||
},
|
||||
{
|
||||
"topic_name": "Space Satellite Systems and Control",
|
||||
"score": 9.6427
|
||||
"topic_name": "Software Testing and Debugging Techniques",
|
||||
"score": 9.530875
|
||||
},
|
||||
{
|
||||
"topic_name": "Smart Agriculture and AI",
|
||||
"score": 9.279837
|
||||
"topic_name": "Digital Media Forensic Detection",
|
||||
"score": 9.530875
|
||||
},
|
||||
{
|
||||
"topic_name": "Infrared Thermography in Medicine",
|
||||
"score": 9.351548
|
||||
},
|
||||
{
|
||||
"topic_name": "Explainable Artificial Intelligence (XAI)",
|
||||
"score": 9.351548
|
||||
},
|
||||
{
|
||||
"topic_name": "Underwater Vehicles and Communication Systems",
|
||||
"score": 9.279837
|
||||
"score": 9.351548
|
||||
},
|
||||
{
|
||||
"topic_name": "Modular Robots and Swarm Intelligence",
|
||||
"score": 7.7584143
|
||||
"topic_name": "Diffusion and Search Dynamics",
|
||||
"score": 8.8518915
|
||||
},
|
||||
{
|
||||
"topic_name": "Diverse Perspectives in Modern Studies",
|
||||
"topic_name": "Direction-of-Arrival Estimation Techniques",
|
||||
"score": 5.968384
|
||||
},
|
||||
{
|
||||
"topic_name": "Retinal Imaging and Analysis",
|
||||
"score": 5.6107
|
||||
},
|
||||
{
|
||||
"topic_name": "Teleoperation and Haptic Systems",
|
||||
"score": 5.2510495
|
||||
},
|
||||
{
|
||||
"topic_name": "Optimization and Search Problems",
|
||||
"score": 5.1682277
|
||||
},
|
||||
{
|
||||
"topic_name": "Adaptive Dynamic Programming Control",
|
||||
"score": 4.8615155
|
||||
},
|
||||
{
|
||||
"topic_name": "Robotic Mechanisms and Dynamics",
|
||||
"score": 2.6450925
|
||||
},
|
||||
{
|
||||
"topic_name": "Control and Dynamics of Mobile Robots",
|
||||
"score": 2.5917463
|
||||
},
|
||||
{
|
||||
"topic_name": "Robot Manipulation and Learning",
|
||||
"score": 2.5859585
|
||||
},
|
||||
{
|
||||
"topic_name": "Robotic Process Automation Applications",
|
||||
"score": 1.7370787
|
||||
},
|
||||
{
|
||||
"topic_name": "Robotic Path Planning Algorithms",
|
||||
"score": 1.6302633
|
||||
"topic_name": "Radar Systems and Signal Processing",
|
||||
"score": 4.721418
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
+21
-21
@@ -1,22 +1,22 @@
|
||||
{
|
||||
"users": [
|
||||
{
|
||||
"username": "superadmin",
|
||||
"password": "superadmin",
|
||||
"email": "some_email@uni-due.de",
|
||||
"account": 0,
|
||||
"organization": 0,
|
||||
"organization_name": "University of Duisburg-Essen",
|
||||
"superadmin": true
|
||||
},
|
||||
{
|
||||
"username": "user",
|
||||
"password": "user",
|
||||
"email": "user_email@uni-due.de",
|
||||
"account": 1,
|
||||
"organization": 1,
|
||||
"organization_name": "University of Duisburg-Essen",
|
||||
"superadmin": false
|
||||
}
|
||||
]
|
||||
}
|
||||
"users": [
|
||||
{
|
||||
"username": "superadmin",
|
||||
"password": "superadmin",
|
||||
"email": "some_email@uni-due.de",
|
||||
"account": 0,
|
||||
"organization": 0,
|
||||
"organization_name": "University of Duisburg-Essen",
|
||||
"superadmin": true
|
||||
},
|
||||
{
|
||||
"username": "user",
|
||||
"password": "user",
|
||||
"email": "user_email@uni-due.de",
|
||||
"account": 1,
|
||||
"organization": 1,
|
||||
"organization_name": "University of Duisburg-Essen",
|
||||
"superadmin": false
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,3 +1,13 @@
|
||||
ELASTICSEARCH_URL=https://project.nes.uni-due.de/elastic/
|
||||
ELASTICSEARCH_API_KEY=am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ
|
||||
|
||||
LLM_API_URL=https://project.nes.uni-due.de/llm2/v1/
|
||||
LLM_API_KEY=c2d5e7ccf7a4760dd3d19bed2caed9d85ff7437400e0ea82a6d6f912ebc2f212
|
||||
LLM_MODEL=gemma4-e4b
|
||||
|
||||
# Patent search (EPO + USPTO)
|
||||
PATENT_ELASTICSEARCH_URL=https://inse.nes.uni-due.de/elastic
|
||||
PATENT_ELASTICSEARCH_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
|
||||
ELASTICSEARCH_URL=https://project.nes.uni-due.de/elastic
|
||||
ELASTICSEARCH_API_KEY=am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ
|
||||
|
||||
@@ -7,6 +17,3 @@ ELASTICSEARCH_INSE_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FM
|
||||
LLM_API_URL=https://project.nes.uni-due.de/llm2/v1/
|
||||
LLM_API_KEY=c2d5e7ccf7a4760dd3d19bed2caed9d85ff7437400e0ea82a6d6f912ebc2f212
|
||||
LLM_MODEL=gemma4-e4b
|
||||
|
||||
ELASTICSEARCH_INSE_URL=https://inse.nes.uni-due.de/elastic
|
||||
ELASTICSEARCH_INSE_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
|
||||
@@ -0,0 +1,298 @@
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from fastapi import HTTPException
|
||||
from starlette.status import HTTP_502_BAD_GATEWAY, HTTP_503_SERVICE_UNAVAILABLE
|
||||
|
||||
from . import model
|
||||
from .search_client import CompanyConnectionsSearchClient, MissingApiKeyError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
UDE_OPENALEX_ID = "https://openalex.org/I62318514"
|
||||
UDE_ROR = "https://ror.org/04mz5ra38"
|
||||
UDE_DISPLAY_NAME = "University of Duisburg-Essen"
|
||||
|
||||
MATCHING_METHOD = "exact_openalex_display_name_to_handelsregister_officer_name"
|
||||
|
||||
|
||||
async def get_company_connections_by_author_id(
|
||||
author_id: str,
|
||||
client: CompanyConnectionsSearchClient | None = None,
|
||||
) -> model.CompanyConnectionsResponse:
|
||||
search_client = client or CompanyConnectionsSearchClient()
|
||||
|
||||
try:
|
||||
author_hit = await search_client.get_openalex_author(author_id)
|
||||
except MissingApiKeyError as exc:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Elasticsearch is not configured.",
|
||||
) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
logger.exception("OpenAlex author lookup failed for %s.", author_id)
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex author lookup failed.",
|
||||
) from exc
|
||||
|
||||
if author_hit is None:
|
||||
raise HTTPException(status_code=404, detail=f"Author {author_id} not found.")
|
||||
|
||||
source = author_hit.get("_source", {})
|
||||
display_name = _clean(source.get("display_name"))
|
||||
institution_scope, matching_institutions = _get_ude_institution_scope(source)
|
||||
is_ude_author = institution_scope is not None
|
||||
|
||||
if not is_ude_author or not display_name:
|
||||
return model.CompanyConnectionsResponse(
|
||||
author_id=author_id,
|
||||
display_name=display_name or None,
|
||||
is_ude_author=is_ude_author,
|
||||
institution_scope=institution_scope,
|
||||
matching_institutions=matching_institutions,
|
||||
matching_method=None,
|
||||
company_count=0,
|
||||
has_more_results=False,
|
||||
common_name_warning=False,
|
||||
connections=[],
|
||||
)
|
||||
|
||||
try:
|
||||
hr_response = await search_client.search_handelsregister_by_officer_name(
|
||||
display_name
|
||||
)
|
||||
except MissingApiKeyError as exc:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Elasticsearch is not configured.",
|
||||
) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
logger.exception("Handelsregister lookup failed for %s.", display_name)
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="Handelsregister lookup failed.",
|
||||
) from exc
|
||||
|
||||
company_count, company_count_relation = _parse_total(hr_response)
|
||||
connections = _parse_company_connections(
|
||||
response=hr_response,
|
||||
matched_person_name=display_name,
|
||||
)
|
||||
|
||||
has_more_results = company_count_relation == "gte" or company_count > len(
|
||||
connections
|
||||
)
|
||||
common_name_warning = has_more_results or company_count > 3
|
||||
|
||||
return model.CompanyConnectionsResponse(
|
||||
author_id=author_id,
|
||||
display_name=display_name,
|
||||
is_ude_author=True,
|
||||
institution_scope=institution_scope,
|
||||
matching_institutions=matching_institutions,
|
||||
matching_method=MATCHING_METHOD,
|
||||
company_count=company_count,
|
||||
has_more_results=has_more_results,
|
||||
common_name_warning=common_name_warning,
|
||||
connections=connections,
|
||||
)
|
||||
|
||||
|
||||
def _get_ude_institution_scope(source: dict[str, Any]) -> tuple[str | None, list[str]]:
|
||||
institutions = source.get("last_known_institutions") or []
|
||||
|
||||
direct_matches: list[str] = []
|
||||
child_matches: list[str] = []
|
||||
|
||||
for institution in institutions:
|
||||
if not isinstance(institution, dict):
|
||||
continue
|
||||
|
||||
institution_id = _clean(institution.get("id"))
|
||||
ror = _clean(institution.get("ror"))
|
||||
name = _clean(institution.get("display_name"))
|
||||
lineage = institution.get("lineage") or []
|
||||
|
||||
label = name or institution_id or ror
|
||||
|
||||
is_direct = (
|
||||
institution_id == UDE_OPENALEX_ID
|
||||
or ror == UDE_ROR
|
||||
or name == UDE_DISPLAY_NAME
|
||||
)
|
||||
is_child = UDE_OPENALEX_ID in lineage and not is_direct
|
||||
|
||||
if is_direct:
|
||||
direct_matches.append(label)
|
||||
elif is_child:
|
||||
child_matches.append(label)
|
||||
|
||||
if direct_matches:
|
||||
return "direct_ude", sorted(set(direct_matches))
|
||||
|
||||
if child_matches:
|
||||
return "child_of_ude", sorted(set(child_matches))
|
||||
|
||||
return None, []
|
||||
|
||||
|
||||
def _parse_total(response: dict[str, Any]) -> tuple[int, str]:
|
||||
total = response.get("hits", {}).get("total", 0)
|
||||
|
||||
if isinstance(total, dict):
|
||||
return int(total.get("value") or 0), total.get("relation") or "eq"
|
||||
|
||||
return int(total or 0), "eq"
|
||||
|
||||
|
||||
def _parse_company_connections(
|
||||
response: dict[str, Any],
|
||||
matched_person_name: str,
|
||||
) -> list[model.CompanyConnection]:
|
||||
connections: list[model.CompanyConnection] = []
|
||||
|
||||
hits = response.get("hits", {}).get("hits", [])
|
||||
|
||||
for hit in hits:
|
||||
source = hit.get("_source", {})
|
||||
|
||||
matched_officers = _parse_inner_hit_officers(hit)
|
||||
officers = _parse_source_officers(
|
||||
source=source,
|
||||
matched_person_name=matched_person_name,
|
||||
)
|
||||
|
||||
connections.append(
|
||||
model.CompanyConnection(
|
||||
company_number=source.get("company_number"),
|
||||
company_name=source.get("name"),
|
||||
company_status=source.get("current_status"),
|
||||
register_art=source.get("register_art"),
|
||||
register_nummer=source.get("register_nummer"),
|
||||
native_company_number=source.get("native_company_number"),
|
||||
registrar=source.get("registrar"),
|
||||
registered_office=source.get("registered_office"),
|
||||
registered_address=source.get("registered_address"),
|
||||
retrieved_at=source.get("retrieved_at"),
|
||||
matched_officers=matched_officers,
|
||||
officers=officers,
|
||||
)
|
||||
)
|
||||
|
||||
return connections
|
||||
|
||||
|
||||
def _parse_inner_hit_officers(hit: dict[str, Any]) -> list[model.MatchedOfficer]:
|
||||
inner_hits = (
|
||||
hit.get("inner_hits", {}).get("officers", {}).get("hits", {}).get("hits", [])
|
||||
)
|
||||
|
||||
officers: list[model.MatchedOfficer] = []
|
||||
|
||||
for inner_hit in inner_hits:
|
||||
source = inner_hit.get("_source", {})
|
||||
officer_source = _normalize_officer_source(source)
|
||||
|
||||
officers.append(
|
||||
_to_officer(
|
||||
officer_source,
|
||||
is_matched_person=True,
|
||||
)
|
||||
)
|
||||
|
||||
return _deduplicate_officers(officers)
|
||||
|
||||
|
||||
def _parse_source_officers(
|
||||
source: dict[str, Any],
|
||||
matched_person_name: str,
|
||||
) -> list[model.MatchedOfficer]:
|
||||
raw_officers = source.get("officers") or []
|
||||
|
||||
if not isinstance(raw_officers, list):
|
||||
return []
|
||||
|
||||
officers: list[model.MatchedOfficer] = []
|
||||
|
||||
for raw_officer in raw_officers:
|
||||
if not isinstance(raw_officer, dict):
|
||||
continue
|
||||
|
||||
if _clean(raw_officer.get("type")) != "person":
|
||||
continue
|
||||
|
||||
officer_name = _clean(raw_officer.get("name"))
|
||||
is_matched_person = officer_name == matched_person_name
|
||||
|
||||
officers.append(
|
||||
_to_officer(
|
||||
raw_officer,
|
||||
is_matched_person=is_matched_person,
|
||||
)
|
||||
)
|
||||
|
||||
return _deduplicate_officers(officers)
|
||||
|
||||
|
||||
def _to_officer(
|
||||
source: dict[str, Any],
|
||||
is_matched_person: bool,
|
||||
) -> model.MatchedOfficer:
|
||||
return model.MatchedOfficer(
|
||||
name=_clean_or_none(source.get("name")),
|
||||
firstname=_clean_or_none(source.get("firstname")),
|
||||
lastname=_clean_or_none(source.get("lastname")),
|
||||
city=_clean_or_none(source.get("city")),
|
||||
position=_clean_or_none(source.get("position")),
|
||||
start_date=_clean_or_none(source.get("start_date")),
|
||||
type=_clean_or_none(source.get("type")),
|
||||
flag=_clean_or_none(source.get("flag")),
|
||||
is_matched_person=is_matched_person,
|
||||
)
|
||||
|
||||
|
||||
def _deduplicate_officers(
|
||||
officers: list[model.MatchedOfficer],
|
||||
) -> list[model.MatchedOfficer]:
|
||||
seen: set[tuple[str, str, str, str]] = set()
|
||||
deduplicated: list[model.MatchedOfficer] = []
|
||||
|
||||
for officer in officers:
|
||||
key = (
|
||||
officer.name or "",
|
||||
officer.position or "",
|
||||
officer.city or "",
|
||||
officer.start_date or "",
|
||||
)
|
||||
|
||||
if key in seen:
|
||||
continue
|
||||
|
||||
seen.add(key)
|
||||
deduplicated.append(officer)
|
||||
|
||||
return deduplicated
|
||||
|
||||
|
||||
def _normalize_officer_source(source: dict[str, Any]) -> dict[str, Any]:
|
||||
officers = source.get("officers")
|
||||
|
||||
if isinstance(officers, dict):
|
||||
return officers
|
||||
|
||||
return source
|
||||
|
||||
|
||||
def _clean_or_none(value: Any) -> str | None:
|
||||
cleaned = _clean(value)
|
||||
|
||||
return cleaned or None
|
||||
|
||||
|
||||
def _clean(value: Any) -> str:
|
||||
if value is None:
|
||||
return ""
|
||||
|
||||
return str(value).strip()
|
||||
@@ -0,0 +1,44 @@
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class MatchedOfficer(BaseModel):
|
||||
name: str | None = None
|
||||
firstname: str | None = None
|
||||
lastname: str | None = None
|
||||
city: str | None = None
|
||||
position: str | None = None
|
||||
start_date: str | None = None
|
||||
type: str | None = None
|
||||
flag: str | None = None
|
||||
is_matched_person: bool = False
|
||||
|
||||
|
||||
class CompanyConnection(BaseModel):
|
||||
company_number: str | None = None
|
||||
company_name: str | None = None
|
||||
company_status: str | None = None
|
||||
register_art: str | None = None
|
||||
register_nummer: str | None = None
|
||||
native_company_number: str | None = None
|
||||
registrar: str | None = None
|
||||
registered_office: str | None = None
|
||||
registered_address: str | None = None
|
||||
retrieved_at: str | None = None
|
||||
matched_officers: list[MatchedOfficer] = Field(default_factory=list)
|
||||
officers: list[MatchedOfficer] = Field(default_factory=list)
|
||||
|
||||
|
||||
class CompanyConnectionsResponse(BaseModel):
|
||||
author_id: str
|
||||
display_name: str | None = None
|
||||
is_ude_author: bool
|
||||
institution_scope: str | None = None
|
||||
matching_institutions: list[str] = Field(default_factory=list)
|
||||
|
||||
matching_method: str | None = None
|
||||
|
||||
company_count: int
|
||||
has_more_results: bool
|
||||
common_name_warning: bool
|
||||
|
||||
connections: list[CompanyConnection] = Field(default_factory=list)
|
||||
@@ -0,0 +1,140 @@
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
class MissingApiKeyError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class CompanyConnectionsSearchClient:
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str | None = None,
|
||||
api_key: str | None = None,
|
||||
openalex_index: str = "openalex-authors",
|
||||
handelsregister_index: str = "handelsregister",
|
||||
timeout: float = 30.0,
|
||||
transport: httpx.AsyncBaseTransport | None = None,
|
||||
):
|
||||
self.base_url = (
|
||||
base_url
|
||||
or config.settings.elasticsearch_url
|
||||
or ""
|
||||
).rstrip("/")
|
||||
self.api_key = (
|
||||
api_key
|
||||
if api_key is not None
|
||||
else config.settings.elasticsearch_api_key
|
||||
)
|
||||
self.openalex_index = openalex_index
|
||||
self.handelsregister_index = handelsregister_index
|
||||
self.timeout = timeout
|
||||
self.transport = transport
|
||||
|
||||
@staticmethod
|
||||
def openalex_doc_id(author_id: str) -> str:
|
||||
return author_id.strip().removeprefix("https://openalex.org/")
|
||||
|
||||
async def get_openalex_author(self, author_id: str) -> dict[str, Any] | None:
|
||||
if not self.api_key:
|
||||
raise MissingApiKeyError("Elasticsearch API key is not configured.")
|
||||
|
||||
doc_id = self.openalex_doc_id(author_id)
|
||||
|
||||
async with httpx.AsyncClient(
|
||||
base_url=self.base_url,
|
||||
timeout=self.timeout,
|
||||
transport=self.transport,
|
||||
) as client:
|
||||
response = await client.get(
|
||||
f"/{self.openalex_index}/_doc/{doc_id}",
|
||||
headers={"Authorization": f"ApiKey {self.api_key}"},
|
||||
)
|
||||
|
||||
if response.status_code == 404:
|
||||
return None
|
||||
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
async def search_handelsregister_by_officer_name(
|
||||
self,
|
||||
officer_name: str,
|
||||
size: int = 10000,
|
||||
track_total_hits: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
if not self.api_key:
|
||||
raise MissingApiKeyError("Elasticsearch API key is not configured.")
|
||||
|
||||
payload = self.handelsregister_officer_name_query(
|
||||
officer_name=officer_name,
|
||||
size=size,
|
||||
track_total_hits=track_total_hits,
|
||||
)
|
||||
|
||||
async with httpx.AsyncClient(
|
||||
base_url=self.base_url,
|
||||
timeout=self.timeout,
|
||||
transport=self.transport,
|
||||
) as client:
|
||||
response = await client.post(
|
||||
f"/{self.handelsregister_index}/_search",
|
||||
headers={"Authorization": f"ApiKey {self.api_key}"},
|
||||
json=payload,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
@staticmethod
|
||||
def handelsregister_officer_name_query(
|
||||
officer_name: str,
|
||||
size: int,
|
||||
track_total_hits: bool,
|
||||
) -> dict[str, Any]:
|
||||
return {
|
||||
"track_total_hits": track_total_hits,
|
||||
"size": size,
|
||||
"_source": [
|
||||
"company_number",
|
||||
"name",
|
||||
"current_status",
|
||||
"registered_address",
|
||||
"registered_office",
|
||||
"registrar",
|
||||
"register_art",
|
||||
"register_nummer",
|
||||
"native_company_number",
|
||||
"retrieved_at",
|
||||
"officers",
|
||||
],
|
||||
"query": {
|
||||
"nested": {
|
||||
"path": "officers",
|
||||
"query": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{"term": {"officers.type": "person"}},
|
||||
{"term": {"officers.name.keyword": officer_name}},
|
||||
]
|
||||
}
|
||||
},
|
||||
"inner_hits": {
|
||||
"size": 10,
|
||||
"_source": [
|
||||
"officers.name",
|
||||
"officers.firstname",
|
||||
"officers.lastname",
|
||||
"officers.city",
|
||||
"officers.position",
|
||||
"officers.start_date",
|
||||
"officers.type",
|
||||
"officers.flag",
|
||||
],
|
||||
},
|
||||
}
|
||||
},
|
||||
"sort": [{"company_number": {"order": "asc"}}],
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
REST API for possible company connections of OpenAlex authors.
|
||||
"""
|
||||
|
||||
from fastapi import APIRouter
|
||||
|
||||
from . import logic, model
|
||||
|
||||
router = APIRouter(
|
||||
prefix="/api/inse-service/authors",
|
||||
tags=["Company Connections"],
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{author_id}/company-connections",
|
||||
operation_id="getCompanyConnectionsByAuthor",
|
||||
response_model=model.CompanyConnectionsResponse,
|
||||
response_model_exclude_none=True,
|
||||
summary="Get possible company connections by OpenAlex author ID.",
|
||||
)
|
||||
async def get_company_connections_by_author(author_id: str):
|
||||
return await logic.get_company_connections_by_author_id(author_id)
|
||||
@@ -26,26 +26,27 @@ class Settings(BaseSettings):
|
||||
auth_disabled: bool = False
|
||||
auth_standalone: bool = True
|
||||
auth_secret: str = "change-me-to-a-secure-secret-key"
|
||||
# OpenAlex works search config
|
||||
openalex_works_search_base_url: str = "https://project.nes.uni-due.de/elastic"
|
||||
# IMPORTANT: wildcard * needed to query all work indices
|
||||
openalex_works_search_index: str = "openalex-works*"
|
||||
openalex_works_api_key: str = (
|
||||
"am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ=="
|
||||
)
|
||||
openalex_works_search_timeout_seconds: float = 30.0
|
||||
# OpenAlex public API config
|
||||
openalex_api_base_url: str = "https://api.openalex.org"
|
||||
openalex_api_key: Optional[str] = None
|
||||
openalex_api_timeout_seconds: float = 30.0
|
||||
|
||||
|
||||
# Patent Elasticsearch config
|
||||
patent_elasticsearch_url: str = "https://inse.nes.uni-due.de/elastic"
|
||||
patent_elasticsearch_api_key: Optional[str] = None
|
||||
|
||||
|
||||
# LLM config
|
||||
llm_api_url: Optional[str] = None
|
||||
llm_api_key: Optional[str] = None
|
||||
llm_model: Optional[str] = None
|
||||
|
||||
# elasticsearch config
|
||||
elasticsearch_url: Optional[str] = None
|
||||
# Elasticsearch config
|
||||
elasticsearch_url: str = "https://project.nes.uni-due.de/elastic"
|
||||
elasticsearch_api_key: Optional[str] = None
|
||||
elasticsearch_inse_url: Optional[str] = None
|
||||
elasticsearch_inse_api_key: Optional[str] = None
|
||||
@@ -58,9 +59,6 @@ class Settings(BaseSettings):
|
||||
{"url": "http://localhost:8000", "description": "Local development server"},
|
||||
]
|
||||
|
||||
elasticsearch_inse_url: Optional[str] = None
|
||||
elasticsearch_inse_api_key: Optional[str] = None
|
||||
|
||||
logging_level: str = "DEBUG"
|
||||
|
||||
|
||||
|
||||
@@ -23,9 +23,9 @@ class FundedPublicationsSearchClient:
|
||||
timeout: float | None = None,
|
||||
transport: httpx.AsyncBaseTransport | None = None,
|
||||
):
|
||||
self.base_url = (base_url or config.settings.openalex_works_search_base_url).rstrip("/")
|
||||
self.base_url = (base_url or config.settings.elasticsearch_url or "").rstrip("/")
|
||||
self.index = index or config.settings.openalex_works_search_index
|
||||
self.api_key = api_key if api_key is not None else config.settings.openalex_works_api_key
|
||||
self.api_key = api_key if api_key is not None else config.settings.elasticsearch_api_key
|
||||
self.timeout = timeout if timeout is not None else config.settings.openalex_works_search_timeout_seconds
|
||||
self.transport = transport
|
||||
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
import logging
|
||||
from typing import List, Set
|
||||
from typing import Any, Dict, Literal, Optional
|
||||
|
||||
|
||||
from inse.models.openalex.institution import Institution
|
||||
from inse.exceptions import NotFoundException
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.institutions.model import InstitutionPage
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -12,41 +15,151 @@ logger = logging.getLogger(__name__)
|
||||
class InstitutionsSearchClient:
|
||||
def __init__(self):
|
||||
"""
|
||||
Initializes the client. Credentials and URLs are handled by the
|
||||
Initializes the client. Credentials and URLs are handled by the
|
||||
centralized elasticsearch integration.
|
||||
"""
|
||||
pass
|
||||
|
||||
async def get_institution_by_id(self, raw_institution_id: str) -> Institution:
|
||||
"""
|
||||
Retrieves a single institution by its OpenAlex ID from the local Elasticsearch cluster.
|
||||
def get_institution_by_id(self, raw_oa_institution_id: str) -> Institution:
|
||||
"""Retrieves an institution by its raw OpenAlex institution ID.
|
||||
|
||||
Args:
|
||||
raw_oa_institution_id (str): The raw OpenAlex institution ID to search for.
|
||||
|
||||
Raises:
|
||||
NotFoundException: If no institution is found with the given ID or if the institution data cannot be parsed.
|
||||
|
||||
Returns:
|
||||
Institution: The institution corresponding to the given raw OpenAlex institution ID.
|
||||
"""
|
||||
query = {
|
||||
"match": {
|
||||
"id": f"https://openalex.org/{raw_institution_id.upper()}",
|
||||
"id": f"https://openalex.org/{raw_oa_institution_id.upper()}",
|
||||
}
|
||||
}
|
||||
|
||||
res = elasticsearch.search(
|
||||
index="openalex-institutions",
|
||||
query=query,
|
||||
size=1
|
||||
)
|
||||
|
||||
|
||||
res = elasticsearch.search(index="openalex-institutions", query=query, size=1)
|
||||
|
||||
hits = res.get("hits", {}).get("hits", [])
|
||||
if not hits:
|
||||
raise NotFoundException(f"Institution with ID '{raw_institution_id}' not found.")
|
||||
raise NotFoundException(
|
||||
f"Institution with ID '{raw_oa_institution_id}' not found."
|
||||
)
|
||||
|
||||
institution = self._convert_hit_to_institution(hits[0])
|
||||
if not institution:
|
||||
raise NotFoundException(
|
||||
f"Institution with ID '{raw_oa_institution_id}' could not be parsed."
|
||||
)
|
||||
|
||||
return institution
|
||||
|
||||
async def get_eu_organisation_id_by_oa_institution_id(
|
||||
self, raw_institution_id: str
|
||||
) -> Optional[str]:
|
||||
"""Retrieves the corresponding EU organisation ID for a given OpenAlex institution ID, if available.
|
||||
|
||||
Args:
|
||||
raw_institution_id (str): The raw OpenAlex institution ID for which to retrieve the EU organisation ID.
|
||||
|
||||
Returns:
|
||||
Optional[str]: The corresponding EU organisation ID, or None if not found.
|
||||
"""
|
||||
raw_institution_id = raw_institution_id.upper()
|
||||
cache = {
|
||||
"I62318514": "999843312",
|
||||
}
|
||||
# TODO: Implement actual retrieval of RCN from Elasticsearch or another source instead of using a hardcoded cache.
|
||||
return cache.get(raw_institution_id)
|
||||
|
||||
def get_institutions_by_name(
|
||||
self,
|
||||
name: str,
|
||||
page: int = 0,
|
||||
size: int = 10,
|
||||
sort_by: Literal[
|
||||
"relevance", "name", "works_count", "citations_count"
|
||||
] = "relevance",
|
||||
sorting_direction: Literal["asc", "desc"] = "asc",
|
||||
) -> InstitutionPage:
|
||||
sort_config: list = []
|
||||
|
||||
if sort_by == "relevance":
|
||||
sort_config.append(
|
||||
{
|
||||
"_score": {
|
||||
"order": sorting_direction if sorting_direction else "desc"
|
||||
}
|
||||
}
|
||||
)
|
||||
elif sort_by == "works_count":
|
||||
sort_config.append({"works_count": {"order": sorting_direction}})
|
||||
elif sort_by == "citations_count":
|
||||
sort_config.append({"cited_by_count": {"order": sorting_direction}})
|
||||
else:
|
||||
sort_config.append({"display_name.keyword": {"order": sorting_direction}})
|
||||
|
||||
query: Dict[str, Any] = {"match_all": {}}
|
||||
|
||||
if len(name) > 0:
|
||||
query = {
|
||||
"match_phrase_prefix": {
|
||||
"display_name": {
|
||||
"query": name,
|
||||
"max_expansions": 50,
|
||||
}
|
||||
}
|
||||
}
|
||||
elif sort_by == "relevance":
|
||||
sort_config = [{"display_name.keyword": {"order": sorting_direction}}]
|
||||
|
||||
authors = await self.get_authors_by_institution_id(raw_institution_id)
|
||||
logger.debug(
|
||||
"Retrieved authors for institution_id=%s: %s", raw_institution_id, authors
|
||||
"Searching institutions with name='%s', page=%d, size=%d, sorting_direction='%s', query: %s",
|
||||
name,
|
||||
page,
|
||||
size,
|
||||
sorting_direction,
|
||||
query,
|
||||
)
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
index="openalex-institutions",
|
||||
offset=page * size,
|
||||
size=size,
|
||||
sort=sort_config,
|
||||
query=query,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.exception("Error while searching for institutions: %s", e)
|
||||
raise
|
||||
|
||||
return self.response_to_institution_page(response, page, size)
|
||||
|
||||
def response_to_institution_page(
|
||||
self, response: Dict[str, Any], page: int, size: int
|
||||
) -> InstitutionPage:
|
||||
hits = response.get("hits", {}).get("hits", [])
|
||||
|
||||
institutions = []
|
||||
for hit in hits:
|
||||
institution = self._convert_hit_to_institution(hit)
|
||||
if institution:
|
||||
institutions.append(institution)
|
||||
|
||||
total = response.get("hits", {}).get("total", {}).get("value", 0)
|
||||
logger.debug(
|
||||
"Parsed institution page: page=%d, size=%d, total=%d", page, size, total
|
||||
)
|
||||
return InstitutionPage(
|
||||
elements=institutions,
|
||||
page=page,
|
||||
size=size,
|
||||
total=total,
|
||||
)
|
||||
|
||||
return Institution.from_dict(hits[0]["_source"])
|
||||
|
||||
async def get_authors_by_institution_id(self, raw_institution_id: str) -> List[str]:
|
||||
"""
|
||||
Fetches authors associated with an institution.
|
||||
Fetches authors associated with an institution.
|
||||
Note: This query is specifically looking for current affiliations (2026).
|
||||
"""
|
||||
query = {
|
||||
@@ -75,14 +188,19 @@ class InstitutionsSearchClient:
|
||||
raw_institution_id,
|
||||
query,
|
||||
)
|
||||
|
||||
|
||||
res = elasticsearch.search(index="openalex-authors", query=query)
|
||||
hits = res.get("hits", {}).get("hits", [])
|
||||
|
||||
|
||||
# Extracting display_name directly from the author document source
|
||||
authors = {hit["_source"].get("display_name") for hit in hits if hit["_source"].get("display_name")}
|
||||
authors = {
|
||||
hit["_source"].get("display_name")
|
||||
for hit in hits
|
||||
if hit["_source"].get("display_name")
|
||||
}
|
||||
return list(authors)
|
||||
async def search_institutions(
|
||||
|
||||
def search_institutions(
|
||||
self,
|
||||
query_text: str,
|
||||
country_code: str | None = None,
|
||||
@@ -98,37 +216,39 @@ class InstitutionsSearchClient:
|
||||
if query_text:
|
||||
stripped = query_text.strip()
|
||||
|
||||
must.append({
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"wildcard": {
|
||||
"display_name.keyword": {
|
||||
"value": f"*{stripped}*",
|
||||
"boost": 2
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"wildcard": {
|
||||
"display_name_alternatives.keyword": {
|
||||
"value": f"*{stripped}*",
|
||||
"boost": 2
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"wildcard": {
|
||||
"display_name_acronyms.keyword": {
|
||||
"value": f"*{stripped.upper()}*",
|
||||
"boost": 10
|
||||
}
|
||||
}
|
||||
must.append(
|
||||
{
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"wildcard": {
|
||||
"display_name.keyword": {
|
||||
"value": f"*{stripped}*",
|
||||
"boost": 2,
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"wildcard": {
|
||||
"display_name_alternatives.keyword": {
|
||||
"value": f"*{stripped}*",
|
||||
"boost": 2,
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"wildcard": {
|
||||
"display_name_acronyms.keyword": {
|
||||
"value": f"*{stripped.upper()}*",
|
||||
"boost": 10,
|
||||
}
|
||||
}
|
||||
},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
],
|
||||
"minimum_should_match": 1
|
||||
}
|
||||
})
|
||||
}
|
||||
)
|
||||
|
||||
filter_queries = []
|
||||
|
||||
@@ -153,42 +273,56 @@ class InstitutionsSearchClient:
|
||||
sort=[
|
||||
{"works_count": {"order": "desc"}},
|
||||
],
|
||||
source=["id", "display_name", "country_code", "type", "works_count", "cited_by_count", "geo"],
|
||||
source=[
|
||||
"id",
|
||||
"display_name",
|
||||
"country_code",
|
||||
"type",
|
||||
"works_count",
|
||||
"cited_by_count",
|
||||
"geo",
|
||||
],
|
||||
)
|
||||
|
||||
hits = res.get("hits", {}).get("hits", [])
|
||||
|
||||
return [Institution.from_dict(hit["_source"]) for hit in hits]
|
||||
|
||||
async def get_institution_aliases_by_id(self, raw_institution_id: str) -> List[str]:
|
||||
def get_institution_aliases_by_oa_institution_id(
|
||||
self, raw_oa_institution_id: str
|
||||
) -> List[str]:
|
||||
"""Get a list of institution aliases for a given institution ID, including both display name alternatives and predefined aliases.
|
||||
|
||||
Args:
|
||||
raw_institution_id (str): The raw institution ID for which to retrieve aliases.
|
||||
raw_oa_institution_id (str): The raw OpenAlex institution ID for which to retrieve aliases.
|
||||
|
||||
Returns:
|
||||
List[str]: A list of aliases for the given institution ID.
|
||||
"""
|
||||
institution = await self.get_institution_by_id(raw_institution_id)
|
||||
institution = self.get_institution_by_id(raw_oa_institution_id)
|
||||
aliases = list(
|
||||
self.augment_aliases(set(institution.display_name_alternatives or []))
|
||||
| self.get_predefined_institution_aliases(raw_institution_id)
|
||||
| self.get_predefined_institution_aliases(raw_oa_institution_id)
|
||||
)
|
||||
logger.debug(
|
||||
"Retrieved aliases for institution_id=%s: %s", raw_institution_id, aliases
|
||||
"Retrieved aliases for institution_id=%s: %s",
|
||||
raw_oa_institution_id,
|
||||
aliases,
|
||||
)
|
||||
return aliases
|
||||
|
||||
def get_predefined_institution_aliases(self, raw_institution_id: str) -> Set[str]:
|
||||
def get_predefined_institution_aliases(
|
||||
self, raw_oa_institution_id: str
|
||||
) -> Set[str]:
|
||||
"""Get predefined aliases for a given institution ID.
|
||||
|
||||
Args:
|
||||
raw_institution_id (str): The raw institution ID for which to retrieve predefined aliases.
|
||||
raw_oa_institution_id (str): The raw OpenAlex institution ID for which to retrieve predefined aliases.
|
||||
|
||||
Returns:
|
||||
Set[str]: A set of predefined aliases for the given institution ID.
|
||||
"""
|
||||
raw_institution_id = raw_institution_id.upper()
|
||||
raw_oa_institution_id = raw_oa_institution_id.upper()
|
||||
predefined_aliases = {
|
||||
"I62318514": [
|
||||
"universität duisburg-essen",
|
||||
@@ -199,7 +333,9 @@ class InstitutionsSearchClient:
|
||||
],
|
||||
}
|
||||
|
||||
return self.augment_aliases(set(predefined_aliases.get(raw_institution_id, [])))
|
||||
return self.augment_aliases(
|
||||
set(predefined_aliases.get(raw_oa_institution_id, []))
|
||||
)
|
||||
|
||||
def augment_aliases(self, aliases: Set[str]) -> Set[str]:
|
||||
"""Augment a set of aliases by applying the augment_alias function to each alias.
|
||||
@@ -246,3 +382,123 @@ class InstitutionsSearchClient:
|
||||
)
|
||||
aliases.append(alias.replace("-", " "))
|
||||
return aliases
|
||||
|
||||
def _convert_hit_to_institution(self, hit: Dict[str, Any]) -> Optional[Institution]:
|
||||
"""Convert an Elasticsearch hit to an Institution object, applying necessary data cleaning and validation.
|
||||
|
||||
Args:
|
||||
hit (Dict[str, Any]): The Elasticsearch hit to convert.
|
||||
|
||||
Returns:
|
||||
Optional[Institution]: The converted Institution object or None if conversion fails.
|
||||
"""
|
||||
source = hit.get("_source")
|
||||
if not source:
|
||||
return None
|
||||
|
||||
ALLOWED_TYPES = {
|
||||
"education",
|
||||
"healthcare",
|
||||
"company",
|
||||
"archive",
|
||||
"nonprofit",
|
||||
"government",
|
||||
"facility",
|
||||
"other",
|
||||
}
|
||||
|
||||
cleaned_source = {}
|
||||
for key, value in source.items():
|
||||
if isinstance(value, str) and "T" in value:
|
||||
cleaned_source[key] = value.split("T")[0]
|
||||
|
||||
elif key == "type" and value not in ALLOWED_TYPES:
|
||||
cleaned_source[key] = "other"
|
||||
|
||||
else:
|
||||
cleaned_source[key] = value
|
||||
|
||||
try:
|
||||
return Institution.model_validate(cleaned_source)
|
||||
except Exception as e:
|
||||
logger.exception(
|
||||
"Failed to validate institution hit ID %s: %s", hit.get("_id"), e
|
||||
)
|
||||
return None
|
||||
|
||||
def get_cordis_eu_organisation_ids_by_oa_institution_id(
|
||||
self, raw_oa_institution_id: str
|
||||
) -> Optional[List[str]]:
|
||||
"""Retrieves the corresponding EU organisation IDs for a given OpenAlex institution ID by searching for institution aliases and matching them against the Cordis EU organisations indices.
|
||||
|
||||
Args:
|
||||
raw_oa_institution_id (str): The raw OpenAlex institution ID for which to retrieve the corresponding EU organisation IDs.
|
||||
|
||||
Returns:
|
||||
Optional[List[str]]: A list of corresponding EU organisation IDs or None if the search fails.
|
||||
"""
|
||||
|
||||
institution_aliases = set(
|
||||
self.get_institution_aliases_by_oa_institution_id(
|
||||
raw_oa_institution_id=raw_oa_institution_id
|
||||
)
|
||||
)
|
||||
|
||||
body = {
|
||||
"size": 0,
|
||||
"query": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{
|
||||
"terms": {
|
||||
"name.keyword": [
|
||||
institution_alias.upper()
|
||||
for institution_alias in institution_aliases
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"aggs": {
|
||||
"organisation_ids": {
|
||||
"terms": {"field": "organisationID", "size": 10000}
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
logger.debug(
|
||||
"Searching for EU organisation IDs for raw_oa_institution_id=%s with aliases=%s and query: %s",
|
||||
raw_oa_institution_id,
|
||||
institution_aliases,
|
||||
body,
|
||||
)
|
||||
|
||||
try:
|
||||
# IMPORTANT: The indices are named organizations and not organisations. + 15 Minutes debugging why the search returns 0 results
|
||||
response = elasticsearch.search(
|
||||
index="cordis_eu_*_organizations", body=body, cluster="inse"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.exception("Error while searching for EU organisation IDs: %s", e)
|
||||
return None
|
||||
|
||||
logger.debug(
|
||||
"Received response for EU organisation ID search for raw_oa_institution_id=%s: %s",
|
||||
raw_oa_institution_id,
|
||||
response,
|
||||
)
|
||||
|
||||
aggregations = response.get("aggregations", {})
|
||||
organisation_ids_buckets = aggregations.get("organisation_ids", {}).get(
|
||||
"buckets", []
|
||||
)
|
||||
organisation_ids = [bucket.get("key") for bucket in organisation_ids_buckets]
|
||||
|
||||
logger.debug(
|
||||
"Extracted EU organisation IDs for raw_oa_institution_id=%s: %s",
|
||||
raw_oa_institution_id,
|
||||
organisation_ids,
|
||||
)
|
||||
|
||||
return organisation_ids
|
||||
|
||||
@@ -41,7 +41,7 @@ _VALID_INSTITUTION_TYPES = {
|
||||
async def get_institution_by_id(
|
||||
raw_institution_id: str, client: InstitutionsSearchClient
|
||||
) -> Institution:
|
||||
return await client.get_institution_by_id(raw_institution_id)
|
||||
return client.get_institution_by_id(raw_institution_id)
|
||||
|
||||
|
||||
async def list_institutions(
|
||||
@@ -117,10 +117,10 @@ async def autocomplete_institutions(
|
||||
client: InstitutionsSearchClient,
|
||||
) -> AutocompleteResponse:
|
||||
"""
|
||||
Returns institution options for autocomplete inputs using the local
|
||||
Returns institution options for autocomplete inputs using the local
|
||||
Elasticsearch cluster via the provided client.
|
||||
"""
|
||||
institutions = await client.search_institutions(
|
||||
institutions = client.search_institutions(
|
||||
query_text=query,
|
||||
country_code=country_code,
|
||||
institution_type=institution_type,
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
from typing import List
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from inse.models.openalex.institution import Institution
|
||||
|
||||
|
||||
class InstitutionPage(BaseModel):
|
||||
elements: List[Institution] = Field(
|
||||
default_factory=list, description="List of institutions in the current page."
|
||||
)
|
||||
page: int = Field(default=0, description="Current page number. (0-indexed)")
|
||||
size: int = Field(default=10, description="Number of institutions per page.")
|
||||
total: int = Field(
|
||||
default=0,
|
||||
description="Total number of institutions matching the search criteria.",
|
||||
)
|
||||
+83
-25
@@ -5,15 +5,15 @@ REST API for OpenAlex institutions.
|
||||
"""
|
||||
|
||||
from functools import lru_cache
|
||||
from typing import Annotated
|
||||
from typing import Annotated, Literal
|
||||
|
||||
from fastapi import APIRouter, Depends, status, Query
|
||||
|
||||
from inse.models.openalex.autocomplete_response import AutocompleteResponse
|
||||
from inse.models.openalex.institutions_list_response import InstitutionsListResponse
|
||||
from inse.tags import Tags
|
||||
from inse.config import get_settings
|
||||
from inse.models.openalex.institution import Institution
|
||||
from inse.institutions.model import InstitutionPage
|
||||
from . import logic
|
||||
from inse.institutions.institutions_search_client import InstitutionsSearchClient
|
||||
|
||||
@@ -25,6 +25,62 @@ router = APIRouter(prefix="/api/inse-service/institutions", tags=[Tags.INSTITUTI
|
||||
def get_institutions_search_client() -> InstitutionsSearchClient:
|
||||
return InstitutionsSearchClient()
|
||||
|
||||
|
||||
@router.get(
|
||||
"/search",
|
||||
summary="Searches for institutions by name.",
|
||||
description="Searches for institutions by name with pagination.",
|
||||
operation_id="searchInstitutionsByName",
|
||||
responses={
|
||||
status.HTTP_200_OK: {
|
||||
"description": "Successful Response",
|
||||
"model": InstitutionPage,
|
||||
},
|
||||
},
|
||||
response_model_exclude_none=True,
|
||||
)
|
||||
async def search_institutions_by_name(
|
||||
client: Annotated[
|
||||
InstitutionsSearchClient, Depends(get_institutions_search_client)
|
||||
],
|
||||
name: Annotated[
|
||||
str,
|
||||
Query(
|
||||
description="Institution name to search for, for example 'University of Duisburg Essen'.",
|
||||
),
|
||||
] = "",
|
||||
page: Annotated[
|
||||
int,
|
||||
Query(description="Page number (0-indexed).", ge=0),
|
||||
] = 0,
|
||||
size: Annotated[
|
||||
int,
|
||||
Query(description="Number of institutions per page.", ge=1, le=100),
|
||||
] = 10,
|
||||
sort_by: Annotated[
|
||||
Literal["relevance", "name", "works_count", "citations_count"],
|
||||
Query(
|
||||
description="Field to sort by, either 'relevance', 'name', 'works_count', or 'citations_count'.",
|
||||
regex="^(relevance|name|works_count|citations_count)$",
|
||||
),
|
||||
] = "name",
|
||||
sorting_direction: Annotated[
|
||||
Literal["asc", "desc"],
|
||||
Query(
|
||||
description="Sorting direction, either 'asc' or 'desc'.",
|
||||
regex="^(asc|desc)$",
|
||||
),
|
||||
] = "asc",
|
||||
) -> InstitutionPage:
|
||||
return client.get_institutions_by_name(
|
||||
name=name,
|
||||
page=page,
|
||||
size=size,
|
||||
sort_by=sort_by,
|
||||
sorting_direction=sorting_direction,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/autocomplete",
|
||||
operation_id="autocompleteInstitutions",
|
||||
@@ -52,7 +108,9 @@ async def autocomplete_institutions(
|
||||
int,
|
||||
Query(description="Maximum number of autocomplete options.", ge=1, le=25),
|
||||
] = 10,
|
||||
client: Annotated[InstitutionsSearchClient, Depends(get_institutions_search_client)] = None,
|
||||
client: Annotated[
|
||||
InstitutionsSearchClient, Depends(get_institutions_search_client)
|
||||
] = None,
|
||||
):
|
||||
return await logic.autocomplete_institutions(
|
||||
query=query,
|
||||
@@ -62,6 +120,28 @@ async def autocomplete_institutions(
|
||||
client=client,
|
||||
)
|
||||
|
||||
@router.get(
|
||||
"/{id}",
|
||||
summary="Returns a single institution by ID.",
|
||||
description="Returns a single institution by its OpenAlex ID.",
|
||||
operation_id="getInstitutionById",
|
||||
responses={
|
||||
status.HTTP_200_OK: {
|
||||
"description": "Successful Response",
|
||||
"model": Institution,
|
||||
},
|
||||
status.HTTP_404_NOT_FOUND: {"description": "Institution not found"},
|
||||
},
|
||||
)
|
||||
async def get_institution(
|
||||
id: str,
|
||||
client: Annotated[
|
||||
InstitutionsSearchClient, Depends(get_institutions_search_client)
|
||||
],
|
||||
) -> Institution:
|
||||
return await logic.get_institution_by_id(raw_institution_id=id, client=client)
|
||||
|
||||
|
||||
|
||||
@router.get(
|
||||
"",
|
||||
@@ -125,25 +205,3 @@ async def list_institutions(
|
||||
sample=sample,
|
||||
select=select,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{id}",
|
||||
summary="Returns a single institution by ID.",
|
||||
description="Returns a single institution by its OpenAlex ID.",
|
||||
operation_id="getInstitutionById",
|
||||
responses={
|
||||
status.HTTP_200_OK: {
|
||||
"description": "Successful Response",
|
||||
"model": Institution,
|
||||
},
|
||||
status.HTTP_404_NOT_FOUND: {"description": "Institution not found"},
|
||||
},
|
||||
)
|
||||
async def get_institution(
|
||||
id: str,
|
||||
client: Annotated[
|
||||
InstitutionsSearchClient, Depends(get_institutions_search_client)
|
||||
],
|
||||
) -> Institution:
|
||||
return await logic.get_institution_by_id(raw_institution_id=id, client=client)
|
||||
@@ -1,43 +1,143 @@
|
||||
from typing import Any, Optional
|
||||
import json
|
||||
import logging
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
import httpx
|
||||
|
||||
from inse.model import ESCluster, ESIndex
|
||||
from .. import config
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
def _cluster_credentials(cluster: str) -> tuple[str, str]:
|
||||
|
||||
if cluster == "nes":
|
||||
def _cluster_credentials(cluster: ESCluster) -> Tuple[str, str]:
|
||||
"""Retrieves the Elasticsearch URL and API key for the specified cluster from the configuration.
|
||||
|
||||
Args:
|
||||
cluster (ElasticsearchCluster): The cluster for which to retrieve credentials. Allowed values are "nes" and "inse".
|
||||
|
||||
Raises:
|
||||
ValueError: If the cluster is unknown or the credentials are not set in the configuration.
|
||||
|
||||
Returns:
|
||||
Tuple[str, str]: The Elasticsearch URL and API key for the specified cluster.
|
||||
"""
|
||||
|
||||
if cluster == ESCluster.NES:
|
||||
if (
|
||||
not config.settings.elasticsearch_url
|
||||
or not config.settings.elasticsearch_api_key
|
||||
):
|
||||
raise ValueError(
|
||||
"Elasticsearch URL and API key must be set in the configuration for cluster 'nes'"
|
||||
)
|
||||
return config.settings.elasticsearch_url, config.settings.elasticsearch_api_key
|
||||
elif cluster == "inse":
|
||||
return config.settings.elasticsearch_inse_url, config.settings.elasticsearch_inse_api_key
|
||||
elif cluster == ESCluster.INSE:
|
||||
if (
|
||||
not config.settings.elasticsearch_inse_url
|
||||
or not config.settings.elasticsearch_inse_api_key
|
||||
):
|
||||
raise ValueError(
|
||||
"Elasticsearch INSE URL and API key must be set in the configuration for cluster 'inse'"
|
||||
)
|
||||
|
||||
return (
|
||||
config.settings.elasticsearch_inse_url,
|
||||
config.settings.elasticsearch_inse_api_key,
|
||||
)
|
||||
else:
|
||||
raise ValueError(f"Unbekannter Cluster: {cluster!r} (erlaubt: 'nes', 'inse')")
|
||||
raise ValueError(f"Unknown cluster: {cluster!r} (allowed: 'nes', 'inse')")
|
||||
|
||||
|
||||
def _index_to_cluster(index: ESIndex) -> Optional[ESCluster]:
|
||||
"""Determines the Elasticsearch cluster to use based on the specified index.
|
||||
|
||||
Args:
|
||||
index (ESIndex): The Elasticsearch index for which to determine the cluster. Allowed values are defined in the ESIndex enum.
|
||||
|
||||
Raises:
|
||||
ValueError: If the index is unknown.
|
||||
|
||||
Returns:
|
||||
ESCluster: The Elasticsearch cluster to use for the specified index.
|
||||
"""
|
||||
|
||||
if index in {
|
||||
ESIndex.OPENALEX_WORKS,
|
||||
ESIndex.OPENALEX_AUTHORS,
|
||||
ESIndex.OPENALEX_INSTITUTIONS,
|
||||
ESIndex.OPENALEX_PUBLICATIONS,
|
||||
}:
|
||||
return ESCluster.NES
|
||||
elif index in {
|
||||
ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD,
|
||||
ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
|
||||
ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD,
|
||||
ESIndex.PROJECTS_BUND_V1,
|
||||
ESIndex.PROJECTS_DFG_ALL,
|
||||
}:
|
||||
return ESCluster.INSE
|
||||
else:
|
||||
return None
|
||||
|
||||
|
||||
def search(
|
||||
index: str,
|
||||
query_field: str = None,
|
||||
query_value: str = None,
|
||||
query: dict = None,
|
||||
source = None,
|
||||
size: int = None,
|
||||
offset:int = None,
|
||||
sort: list = None,
|
||||
body: dict = None,
|
||||
track_total_hits = False,
|
||||
cluster: str = "nes",
|
||||
) -> dict[str, Any]:
|
||||
index: ESIndex | List[ESIndex],
|
||||
query: Optional[Dict] = None,
|
||||
source: Optional[List] = None,
|
||||
size: Optional[int] = None,
|
||||
offset: Optional[int] = None,
|
||||
sort: Optional[List] = None,
|
||||
body: Optional[Dict] = None,
|
||||
track_total_hits=False,
|
||||
highlight: Optional[Dict] = None,
|
||||
cluster: ESCluster = ESCluster.NES,
|
||||
) -> Dict[str, Any]:
|
||||
"""Searches the specified Elasticsearch index using either a simple query string or a full query body.
|
||||
|
||||
Args:
|
||||
index (ElasticsearchIndex): The Elasticsearch index to search.
|
||||
query (Optional[Dict], optional): The full query body. Defaults to None.
|
||||
source (Optional[List], optional): The fields to include in the response. Defaults to None.
|
||||
size (Optional[int], optional): The maximum number of results to return. Defaults to None.
|
||||
offset (Optional[int], optional): The number of results to skip. Defaults to None.
|
||||
sort (Optional[List], optional): The fields to sort by. Defaults to None.
|
||||
body (Optional[Dict], optional): The full query body. Defaults to None.
|
||||
track_total_hits (bool, optional): Whether to track the total number of hits. Defaults to False.
|
||||
cluster (ElasticsearchCluster, optional): The Elasticsearch cluster to search. Defaults to ElasticsearchCluster.NES.
|
||||
|
||||
Returns:
|
||||
Dict[str, Any]: The search results.
|
||||
"""
|
||||
|
||||
clusters = set()
|
||||
if isinstance(index, list):
|
||||
for idx in index:
|
||||
cluster_for_index = _index_to_cluster(idx)
|
||||
if cluster_for_index is not None:
|
||||
clusters.add(cluster_for_index)
|
||||
else:
|
||||
cluster_for_index = _index_to_cluster(index)
|
||||
if cluster_for_index is not None:
|
||||
clusters.add(cluster_for_index)
|
||||
|
||||
if len(clusters) > 1:
|
||||
raise ValueError(
|
||||
f"All indices in the search request must belong to the same cluster, but found clusters: {clusters}"
|
||||
)
|
||||
elif len(clusters) == 1:
|
||||
cluster = clusters.pop()
|
||||
|
||||
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
||||
|
||||
headers = {
|
||||
"Authorization": f"ApiKey {api_key}",
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
|
||||
|
||||
payload: Dict[str, Any] = {}
|
||||
|
||||
if body is not None:
|
||||
payload = body
|
||||
elif query is not None:
|
||||
payload = {"query": query}
|
||||
else:
|
||||
if query is not None:
|
||||
payload["query"] = query
|
||||
if source is not None:
|
||||
payload["_source"] = source
|
||||
if size is not None:
|
||||
@@ -48,39 +148,40 @@ def search(
|
||||
payload["sort"] = sort
|
||||
if track_total_hits:
|
||||
payload["track_total_hits"] = True
|
||||
else:
|
||||
payload = {
|
||||
"query": {
|
||||
"query_string": {
|
||||
"default_field": query_field,
|
||||
"query": query_value
|
||||
}
|
||||
}
|
||||
}
|
||||
if highlight is not None:
|
||||
payload["highlight"] = highlight
|
||||
|
||||
if len(payload) == 0:
|
||||
raise ValueError(
|
||||
"At least one of 'query', 'body', 'source', 'size', 'offset', 'sort' must be provided"
|
||||
)
|
||||
|
||||
with httpx.Client(timeout=httpx.Timeout(30.0)) as client:
|
||||
logger.debug(
|
||||
f"Sending search request to Elasticsearch cluster '{cluster}' at {elasticsearch_url} for {index} with payload: {json.dumps(payload)}"
|
||||
)
|
||||
if isinstance(index, list):
|
||||
index_str = ",".join(index)
|
||||
else:
|
||||
index_str = index
|
||||
|
||||
response = client.post(
|
||||
f"{elasticsearch_url}/{index}/_search",
|
||||
json=payload,
|
||||
headers=headers
|
||||
f"{elasticsearch_url}/{index_str}/_search", json=payload, headers=headers
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
|
||||
def get(
|
||||
index: str,
|
||||
index: ESIndex,
|
||||
doc_id: str,
|
||||
source: list = None,
|
||||
cluster: str = "nes",
|
||||
source: Optional[list] = None,
|
||||
cluster: ESCluster = ESCluster.NES,
|
||||
) -> dict[str, Any]:
|
||||
|
||||
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
||||
|
||||
headers = {
|
||||
"Authorization": f"ApiKey {api_key}",
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
|
||||
|
||||
params = {}
|
||||
if source is not None:
|
||||
@@ -88,9 +189,7 @@ def get(
|
||||
|
||||
with httpx.Client() as client:
|
||||
response = client.get(
|
||||
f"{elasticsearch_url}/{index}/_doc/{doc_id}",
|
||||
params=params,
|
||||
headers=headers
|
||||
f"{elasticsearch_url}/{index}/_doc/{doc_id}", params=params, headers=headers
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
@@ -7,23 +7,33 @@ webapp.
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.responses import JSONResponse, RedirectResponse
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import JSONResponse, RedirectResponse
|
||||
|
||||
from inse.collaboration_network.router import router as collaboration_network_router
|
||||
from inse.institutions.service import router as institutions_service_router
|
||||
from inse.topics.service import router as topics_service_router
|
||||
from inse.works.service import router as works_service_router
|
||||
from inse.persons.service import router as persons_service_router
|
||||
from inse.company_connections.service import router as company_connections_router
|
||||
from inse.exceptions import NotFoundException
|
||||
from inse.funders.service import router as funders_service_router
|
||||
from inse.projects.router import router as projects_router
|
||||
from inse.university_ranking.router import router as university_ranking_router
|
||||
# caching
|
||||
from inse.middleware.etag_cache import ETagCacheMiddleware
|
||||
from inse.exceptions import NotFoundException
|
||||
from inse.persons.service import router as persons_service_router
|
||||
from inse.projects.router import router as projects_router
|
||||
from inse.topics.service import router as topics_service_router
|
||||
from inse.works.service import router as works_service_router
|
||||
from inse.persons.service import router as persons_service_router
|
||||
from inse.funders.service import router as funders_service_router
|
||||
from inse.news.service import router as news_service_router
|
||||
from inse.projects.router import router as projects_router
|
||||
from inse.patents.service import router as patents_service_router
|
||||
|
||||
from inse.institutions.router import router as institutions_router
|
||||
from . import config
|
||||
from .service import router as service_router
|
||||
from .account.service import router as account_router
|
||||
from .service import router as service_router
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -39,13 +49,16 @@ app = FastAPI(
|
||||
servers=settings.servers,
|
||||
)
|
||||
app.include_router(collaboration_network_router)
|
||||
app.include_router(institutions_service_router)
|
||||
app.include_router(institutions_router)
|
||||
app.include_router(topics_service_router)
|
||||
app.include_router(works_service_router)
|
||||
app.include_router(persons_service_router)
|
||||
app.include_router(funders_service_router)
|
||||
app.include_router(news_service_router)
|
||||
app.include_router(company_connections_router)
|
||||
app.include_router(service_router)
|
||||
app.include_router(account_router)
|
||||
app.include_router(patents_service_router)
|
||||
app.include_router(university_ranking_router)
|
||||
app.include_router(projects_router)
|
||||
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
This module defines the model classes returned from
|
||||
our api using pydantic.
|
||||
This module defines the model classes returned from
|
||||
our api using pydantic.
|
||||
"""
|
||||
|
||||
from enum import StrEnum
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic import ConfigDict
|
||||
from pydantic import Field
|
||||
@@ -13,28 +16,49 @@ from typing import Generic
|
||||
from typing import Optional
|
||||
|
||||
|
||||
T = TypeVar('T', bound=BaseModel)
|
||||
T = TypeVar("T", bound=BaseModel)
|
||||
|
||||
|
||||
class Entity(BaseModel):
|
||||
id: int = Field(description="The id of the entity.")
|
||||
|
||||
|
||||
class Item(Entity):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
name: str = Field(description="The name of the item.")
|
||||
description: str = Field(description="The description of the item.")
|
||||
|
||||
|
||||
class ItemCreate(BaseModel):
|
||||
name: str = Field(description="The name of the item.")
|
||||
description: str = Field(description="The description of the item.")
|
||||
|
||||
|
||||
class Page(BaseModel, Generic[T]):
|
||||
elements: List[T] = Field(default=[], description="The elements of the page.")
|
||||
offset: int = Field(default=0, description="The page offset in elements.")
|
||||
total: int = Field(default=0, description="The total number of elements.")
|
||||
size: int = Field(default=20, description="The page size in elements.")
|
||||
|
||||
|
||||
class ItemPage(Page[Item]):
|
||||
pass
|
||||
|
||||
|
||||
class ESCluster(StrEnum):
|
||||
NES = "nes"
|
||||
INSE = "inse"
|
||||
|
||||
|
||||
class ESIndex(StrEnum):
|
||||
OPENALEX_WORKS = "openalex-works"
|
||||
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"
|
||||
|
||||
PROJECTS_BUND_V1 = "projects_bund_v1"
|
||||
PROJECTS_DFG_ALL = "projects_dfg_all"
|
||||
@@ -0,0 +1,337 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
Bund Project Clean Model
|
||||
|
||||
Summary model that consolidates scattered fields from the raw projects_bund index
|
||||
into clean, semantic field names with proper native Python types.
|
||||
"""
|
||||
|
||||
from datetime import date, datetime
|
||||
from typing import Optional, List, Set, Any
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
|
||||
|
||||
class BundProjectDetails(BaseModel):
|
||||
"""
|
||||
Clean summary model for a Bund (federal) project, consolidating all fields
|
||||
into semantic English names with proper native types.
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(
|
||||
populate_by_name=True,
|
||||
validate_assignment=True,
|
||||
)
|
||||
|
||||
# Core identifiers
|
||||
id: str = Field(description="The ID of the Bund project")
|
||||
funding_reference: Optional[str] = Field(
|
||||
default=None,
|
||||
|
||||
description="The funding reference number (Förderkennzeichen)",
|
||||
)
|
||||
|
||||
# Project metadata
|
||||
title: Optional[str] = Field(
|
||||
default=None,
|
||||
|
||||
description="The project topic/title",
|
||||
)
|
||||
description: Optional[str] = Field(
|
||||
default=None,
|
||||
|
||||
description="Plain text description of the performance plan classification",
|
||||
)
|
||||
joint_project: Optional[str] = Field(
|
||||
default=None,
|
||||
|
||||
description="Parent joint project if this is a sub-project",
|
||||
)
|
||||
|
||||
# Funding information
|
||||
funding_type: Optional[str] = Field(
|
||||
default=None,
|
||||
|
||||
description="Type of funding (Förderart)",
|
||||
)
|
||||
funding_profile: Optional[str] = Field(
|
||||
default=None,
|
||||
|
||||
description="Funding profile (Förderprofil)",
|
||||
)
|
||||
funding_amount: Optional[float] = Field(
|
||||
default=None,
|
||||
|
||||
description="Funding amount in EUR",
|
||||
)
|
||||
funding_start_date: Optional[date] = Field(
|
||||
default=None,
|
||||
description="Funding start date",
|
||||
)
|
||||
funding_end_date: Optional[date] = Field(
|
||||
default=None,
|
||||
description="Funding end date",
|
||||
)
|
||||
duration: Optional[str] = Field(
|
||||
default=None,
|
||||
|
||||
description="Project duration (Laufzeit)",
|
||||
)
|
||||
|
||||
# Classification
|
||||
performance_plan_code: Optional[str] = Field(
|
||||
default=None,
|
||||
|
||||
description="Performance plan classification code",
|
||||
)
|
||||
performance_plan_fullname: Optional[str] = Field(
|
||||
default=None,
|
||||
|
||||
description="Full name of the performance plan classification",
|
||||
)
|
||||
|
||||
# Organizational
|
||||
executing_agency: Optional[str] = Field(
|
||||
default=None,
|
||||
|
||||
description="Executing agency",
|
||||
)
|
||||
funding_recipient: Optional[str] = Field(
|
||||
default=None,
|
||||
|
||||
description="Funding recipient",
|
||||
)
|
||||
project_agency: Optional[str] = Field(
|
||||
default=None,
|
||||
|
||||
description="Project management agency",
|
||||
)
|
||||
project_agency_fullname: Optional[str] = Field(
|
||||
default=None,
|
||||
|
||||
description="Full name of the project management agency",
|
||||
)
|
||||
|
||||
# Government hierarchy
|
||||
department: Optional[str] = Field(
|
||||
default=None,
|
||||
|
||||
description="Government department code",
|
||||
)
|
||||
department_fullname: Optional[str] = Field(
|
||||
default=None,
|
||||
|
||||
description="Full name of the government department",
|
||||
)
|
||||
division: Optional[str] = Field(
|
||||
default=None,
|
||||
|
||||
description="Division/unit reference",
|
||||
)
|
||||
|
||||
# Location
|
||||
location: Optional[str] = Field(
|
||||
default=None,
|
||||
|
||||
description="Location/city",
|
||||
)
|
||||
municipality: Optional[str] = Field(
|
||||
default=None,
|
||||
|
||||
description="City/Municipality",
|
||||
)
|
||||
state: Optional[str] = Field(
|
||||
default=None,
|
||||
|
||||
description="Federal state",
|
||||
)
|
||||
country: Optional[str] = Field(
|
||||
default=None,
|
||||
|
||||
description="Country",
|
||||
)
|
||||
municipality_code: Optional[str] = Field(
|
||||
default=None,
|
||||
|
||||
description="Municipality code",
|
||||
)
|
||||
|
||||
# Publication
|
||||
publication_date: Optional[str] = Field(
|
||||
default=None,
|
||||
|
||||
description="Publication date",
|
||||
)
|
||||
|
||||
# Additional
|
||||
is_new: Optional[bool] = Field(
|
||||
default=None,
|
||||
|
||||
description="Flag indicating if the project is new",
|
||||
)
|
||||
record_date: Optional[str] = Field(
|
||||
default=None,
|
||||
|
||||
description="Record date",
|
||||
)
|
||||
unix_timestamp: Optional[int] = Field(
|
||||
default=None,
|
||||
description="Unix timestamp of the record",
|
||||
)
|
||||
|
||||
# Unified lists for aggregation
|
||||
associated_persons: List[str] = Field(
|
||||
default_factory=list,
|
||||
description="All persons associated with the Bund project (from nested Arb object)",
|
||||
)
|
||||
institutions: List[str] = Field(
|
||||
default_factory=list,
|
||||
description="All institutions associated with the Bund project",
|
||||
)
|
||||
|
||||
# --- Validators for type coercion ---
|
||||
|
||||
@field_validator("funding_amount", mode="before")
|
||||
@classmethod
|
||||
def parse_funding_amount(cls, v: Any) -> Optional[float]:
|
||||
"""Parse funding amount from string or number."""
|
||||
if v is None:
|
||||
return None
|
||||
if isinstance(v, (int, float)):
|
||||
return float(v)
|
||||
if isinstance(v, str):
|
||||
# Remove thousands separators and trim
|
||||
cleaned = v.replace(".", "").replace(",", ".").strip()
|
||||
try:
|
||||
return float(cleaned)
|
||||
except ValueError:
|
||||
return None
|
||||
return None
|
||||
|
||||
@field_validator("funding_start_date", "funding_end_date", mode="before")
|
||||
@classmethod
|
||||
def parse_german_date(cls, v: Any) -> Optional[date]:
|
||||
"""Parse date from German format (dd.MM.yyyy) or date/datetime object."""
|
||||
if v is None:
|
||||
return None
|
||||
if isinstance(v, datetime):
|
||||
return v.date()
|
||||
if isinstance(v, date):
|
||||
return v
|
||||
if isinstance(v, str):
|
||||
v = v.strip()
|
||||
# Try German format first: dd.MM.yyyy
|
||||
try:
|
||||
return datetime.strptime(v, "%d.%m.%Y").date()
|
||||
except ValueError:
|
||||
pass
|
||||
# Try ISO format: yyyy-MM-dd
|
||||
try:
|
||||
return datetime.strptime(v, "%Y-%m-%d").date()
|
||||
except ValueError:
|
||||
pass
|
||||
# Try with time component
|
||||
try:
|
||||
return datetime.fromisoformat(v).date()
|
||||
except ValueError:
|
||||
pass
|
||||
return None
|
||||
|
||||
@field_validator("is_new", mode="before")
|
||||
@classmethod
|
||||
def parse_is_new(cls, v: Any) -> Optional[bool]:
|
||||
"""Parse is_new from bool or string."""
|
||||
if v is None:
|
||||
return None
|
||||
if isinstance(v, bool):
|
||||
return v
|
||||
if isinstance(v, str):
|
||||
return v.lower() in ("true", "1", "yes", "ja")
|
||||
if isinstance(v, (int, float)):
|
||||
return bool(v)
|
||||
return None
|
||||
|
||||
@field_validator("unix_timestamp", mode="before")
|
||||
@classmethod
|
||||
def parse_unix_timestamp(cls, v: Any) -> Optional[int]:
|
||||
"""Parse unix timestamp from int, float, or string."""
|
||||
if v is None:
|
||||
return None
|
||||
if isinstance(v, (int, float)):
|
||||
return int(v)
|
||||
if isinstance(v, str):
|
||||
try:
|
||||
return int(v)
|
||||
except ValueError:
|
||||
return None
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def from_elastic_hit(cls, hit: dict) -> "BundProject":
|
||||
"""
|
||||
Create a BundProject from an Elasticsearch hit, consolidating all fields.
|
||||
"""
|
||||
source = hit.get("_source", {})
|
||||
|
||||
# --- Extract persons from nested Arb object ---
|
||||
persons: Set[str] = set()
|
||||
arb = source.get("Arb")
|
||||
if arb and isinstance(arb, dict):
|
||||
for key, value in arb.items():
|
||||
if isinstance(value, str) and value.strip():
|
||||
for person in value.split(";"):
|
||||
person = person.strip()
|
||||
if person:
|
||||
persons.add(person)
|
||||
|
||||
# --- Extract institutions ---
|
||||
institutions: Set[str] = set()
|
||||
inst_fields = [
|
||||
"Ausführende Stelle",
|
||||
"Zuwendungsempfänger",
|
||||
"Projektträger",
|
||||
]
|
||||
for field in inst_fields:
|
||||
if field in source and source[field]:
|
||||
for inst in source[field].split(";"):
|
||||
inst = inst.strip()
|
||||
if inst:
|
||||
institutions.add(inst)
|
||||
|
||||
if source.get("PT_fullname"):
|
||||
institutions.add(source["PT_fullname"].strip())
|
||||
|
||||
return cls(
|
||||
id=hit["_id"],
|
||||
funding_reference=source.get("Förderkennzeichen"),
|
||||
title=source.get("Thema"),
|
||||
description=source.get("Klartext Leistungsplansystematik"),
|
||||
joint_project=source.get("Verbundprojekt"),
|
||||
funding_type=source.get("Förderart"),
|
||||
funding_profile=source.get("Förderprofil"),
|
||||
funding_amount=source.get("Fördersumme"),
|
||||
funding_start_date=source.get("funding_start"),
|
||||
funding_end_date=source.get("funding_end"),
|
||||
duration=source.get("Laufzeit"),
|
||||
performance_plan_code=source.get("Leistungsplansystematik"),
|
||||
performance_plan_fullname=source.get("Leistungsplansystematik_fullname"),
|
||||
executing_agency=source.get("Ausführende Stelle"),
|
||||
funding_recipient=source.get("Zuwendungsempfänger"),
|
||||
project_agency=source.get("Projektträger"),
|
||||
project_agency_fullname=source.get("PT_fullname"),
|
||||
department=source.get("Ressort"),
|
||||
department_fullname=source.get("Ressort_fullname"),
|
||||
division=source.get("Referat"),
|
||||
location=source.get("Ort"),
|
||||
municipality=source.get("Stadt/Gemeinde"),
|
||||
state=source.get("Bundesland"),
|
||||
country=source.get("Staat"),
|
||||
municipality_code=source.get("Gemeindekennziffer"),
|
||||
publication_date=source.get("Publikationsdatum"),
|
||||
is_new=source.get("new"),
|
||||
record_date=source.get("datum"),
|
||||
unix_timestamp=source.get("unix_timestamp"),
|
||||
associated_persons=sorted(persons),
|
||||
institutions=sorted(institutions),
|
||||
)
|
||||
@@ -0,0 +1,62 @@
|
||||
from datetime import datetime
|
||||
from typing import Optional, List, Union
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class CordisEuProject(BaseModel):
|
||||
id: str = Field(
|
||||
description="Unique identifier for the project, typically the CORDIS ID"
|
||||
)
|
||||
rcn: Optional[str] = Field(
|
||||
None, description="Research and Innovation project number (CORDIS RCN)"
|
||||
)
|
||||
acronym: Optional[str] = Field(None, description="Acronym for the project")
|
||||
title: Optional[str] = Field(None, description="Title of the project")
|
||||
objective: Optional[str] = Field(None, description="Objective of the project")
|
||||
|
||||
frameworkProgramme: Optional[str] = Field(
|
||||
None, description="Framework Programme under which the project was funded"
|
||||
)
|
||||
fundingScheme: Optional[str] = Field(
|
||||
None, description="Funding scheme of the project"
|
||||
)
|
||||
legalBasis: Optional[str] = Field(
|
||||
None, description="Legal basis for the project funding"
|
||||
)
|
||||
masterCall: Optional[str] = Field(
|
||||
None, description="Master call identifier if applicable"
|
||||
)
|
||||
subCall: Optional[str] = Field(
|
||||
None, description="Sub call identifier if applicable"
|
||||
)
|
||||
topics: Optional[Union[str, List[str]]] = (
|
||||
None # Elastic keyword can map to a single string or list of strings
|
||||
)
|
||||
nature: Optional[str] = Field(None, description="Nature of the project")
|
||||
status: Optional[str] = Field(None, description="Status of the project")
|
||||
|
||||
ecMaxContribution: Optional[float] = Field(
|
||||
None, description="Maximum European Commission contribution"
|
||||
)
|
||||
totalCost: Optional[float] = Field(None, description="Total cost of the project")
|
||||
|
||||
startDate: Optional[datetime] = Field(None, description="Start date of the project")
|
||||
endDate: Optional[datetime] = Field(None, description="End date of the project")
|
||||
ecSignatureDate: Optional[datetime] = Field(
|
||||
None, description="Date of the European Commission signature"
|
||||
)
|
||||
contentUpdateDate: Optional[datetime] = Field(
|
||||
None, description="Date when the project content was last updated"
|
||||
)
|
||||
|
||||
grantDoi: Optional[str] = Field(None, description="DOI for the project grant")
|
||||
humanValidated: Optional[bool] = Field(
|
||||
None,
|
||||
description="Indicates if the project information has been human validated",
|
||||
)
|
||||
keywords: Optional[Union[str, List[str]]] = Field(
|
||||
None, description="Keywords associated with the project"
|
||||
)
|
||||
|
||||
class Config:
|
||||
populate_by_name = True
|
||||
@@ -0,0 +1,275 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
DFG Project Clean Model
|
||||
|
||||
Summary model that consolidates all scattered person and institution fields
|
||||
from the raw projects_dfg_all index into clean, unified lists.
|
||||
"""
|
||||
|
||||
from typing import Optional, List, Set
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
|
||||
class DfgProjectDetails(BaseModel):
|
||||
"""
|
||||
Clean summary model for a DFG project, consolidating all person roles
|
||||
and institution references into unified lists.
|
||||
"""
|
||||
model_config = ConfigDict(
|
||||
populate_by_name=True,
|
||||
validate_assignment=True,
|
||||
)
|
||||
|
||||
id: str = Field(description="The ID of the DFG project")
|
||||
link: Optional[str] = Field(default=None, description="The link to the DFG project")
|
||||
title: Optional[str] = Field(
|
||||
default=None, description="The title of the DFG project"
|
||||
)
|
||||
description: Optional[str] = Field(
|
||||
default=None, description="The description of the DFG project"
|
||||
)
|
||||
|
||||
project_identifier: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The project identifier of the DFG project",
|
||||
)
|
||||
|
||||
funding_start_date: Optional[str] = Field(
|
||||
default=None, description="The funding start date of the DFG project"
|
||||
)
|
||||
funding_end_date: Optional[str] = Field(
|
||||
default=None, description="The funding end date of the DFG project"
|
||||
)
|
||||
|
||||
dfg_procedure: Optional[str] = Field(
|
||||
default=None, description="The DFG procedure"
|
||||
)
|
||||
subject_area: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The subject area classification",
|
||||
)
|
||||
funding_type: Optional[str] = Field(
|
||||
default=None, description="The type of funding"
|
||||
)
|
||||
international_reference: Optional[str] = Field(
|
||||
default=None,
|
||||
|
||||
description="International reference",
|
||||
)
|
||||
|
||||
website: Optional[str] = Field(
|
||||
default=None, description="The project website"
|
||||
)
|
||||
|
||||
# Unified person list: all person names from any role
|
||||
associated_persons: List[str] = Field(
|
||||
default_factory=list,
|
||||
description="All persons associated with the DFG project (any role)",
|
||||
)
|
||||
|
||||
# Unified institution list: all institutions involved
|
||||
institutions: List[str] = Field(
|
||||
default_factory=list,
|
||||
description="All institutions associated with the DFG project",
|
||||
)
|
||||
|
||||
# Sub-project reference
|
||||
subproject_of: Optional[str] = Field(
|
||||
default=None,
|
||||
description="Parent project this is a sub-project of",
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def from_elastic_hit(cls, hit: dict) -> "DfgProjectDetails":
|
||||
"""
|
||||
Create a DfgProject from an Elasticsearch hit, consolidating all
|
||||
person and institution fields into unified lists.
|
||||
"""
|
||||
|
||||
source = hit.get("_source", {})
|
||||
|
||||
associated_persons: Set[str] = set()
|
||||
institutions: Set[str] = set()
|
||||
|
||||
# --- Collect all persons from every person-related field ---
|
||||
|
||||
# Applicant fields
|
||||
_add_persons(source, associated_persons, "Antragsteller") # semicolon-separated
|
||||
_add_person(source, associated_persons, "Antragstellerin")
|
||||
_add_persons(
|
||||
source, associated_persons, "Antragstellerinnen"
|
||||
) # semicolon-separated
|
||||
_add_persons(
|
||||
source, associated_persons, "Antragstellerinnen / Antragsteller"
|
||||
) # semicolon-separated
|
||||
|
||||
# Co-applicant fields
|
||||
_add_persons(source, associated_persons, "Mitantragsteller")
|
||||
_add_person(source, associated_persons, "Mitantragstellerin")
|
||||
_add_persons(source, associated_persons, "Mitantragstellerinnen")
|
||||
_add_persons(
|
||||
source, associated_persons, "Mitantragstellerinnen / Mitantragsteller"
|
||||
)
|
||||
|
||||
# Former applicant fields
|
||||
_add_persons(source, associated_persons, "Ehemalige Antragsteller")
|
||||
_add_person(source, associated_persons, "Ehemalige Antragstellerin")
|
||||
_add_persons(source, associated_persons, "Ehemalige Antragstellerinnen")
|
||||
_add_persons(
|
||||
source,
|
||||
associated_persons,
|
||||
"Ehemalige Antragstellerinnen / Ehemalige Antragsteller",
|
||||
)
|
||||
_add_person(source, associated_persons, "Ehemaliger Antragsteller")
|
||||
|
||||
# Speaker / coordinator fields
|
||||
_add_person(source, associated_persons, "Sprecher")
|
||||
_add_person(source, associated_persons, "Sprecherin")
|
||||
_add_persons(source, associated_persons, "Sprecherinnen")
|
||||
_add_persons(source, associated_persons, "Sprecherinnen / Sprecher")
|
||||
_add_person(source, associated_persons, "Co-Sprecher")
|
||||
_add_persons(source, associated_persons, "Co-Sprecherinnen / Co-Sprecher")
|
||||
|
||||
# IGK partner speaker fields
|
||||
_add_person(source, associated_persons, "Sprecher (IGK-Partner)")
|
||||
_add_person(source, associated_persons, "Sprecherin (IGK-Partner)")
|
||||
_add_persons(
|
||||
source,
|
||||
associated_persons,
|
||||
"Sprecherinnen (IGK-Partner) / Sprecher (IGK-Partner)",
|
||||
)
|
||||
|
||||
# Leader fields
|
||||
_add_person(source, associated_persons, "Leiter")
|
||||
_add_person(source, associated_persons, "Leiterin")
|
||||
_add_persons(source, associated_persons, "Leiterinnen")
|
||||
_add_persons(source, associated_persons, "Leiterinnen / Leiter")
|
||||
|
||||
# Sub-project leader fields
|
||||
_add_persons(source, associated_persons, "Teilprojektleiter")
|
||||
_add_person(source, associated_persons, "Teilprojektleiterin")
|
||||
_add_persons(source, associated_persons, "Teilprojektleiterinnen")
|
||||
_add_persons(
|
||||
source, associated_persons, "Teilprojektleiterinnen / Teilprojektleiter"
|
||||
)
|
||||
|
||||
# Participating scientist fields
|
||||
_add_persons(source, associated_persons, "beteiligte Wissenschaftler")
|
||||
_add_person(source, associated_persons, "beteiligte Wissenschaftlerin")
|
||||
_add_persons(source, associated_persons, "beteiligte Wissenschaftlerinnen")
|
||||
_add_persons(
|
||||
source,
|
||||
associated_persons,
|
||||
"beteiligte Wissenschaftlerinnen / beteiligte Wissenschaftler",
|
||||
)
|
||||
_add_person(source, associated_persons, "beteiligter Wissenschaftler")
|
||||
|
||||
# Participating person fields
|
||||
_add_person(source, associated_persons, "Beteiligte Person")
|
||||
_add_persons(source, associated_persons, "Beteiligte Personen")
|
||||
|
||||
# Host fields (for guest researchers)
|
||||
_add_person(source, associated_persons, "Gastgeber")
|
||||
_add_person(source, associated_persons, "Gastgeberin")
|
||||
_add_persons(source, associated_persons, "Gastgeberinnen")
|
||||
_add_persons(source, associated_persons, "Gastgeberinnen / Gastgeber")
|
||||
|
||||
# Cooperation partner fields
|
||||
_add_person(source, associated_persons, "Kooperationspartner")
|
||||
_add_person(source, associated_persons, "Kooperationspartnerin")
|
||||
_add_persons(source, associated_persons, "Kooperationspartnerinnen")
|
||||
_add_persons(
|
||||
source, associated_persons, "Kooperationspartnerinnen / Kooperationspartner"
|
||||
)
|
||||
|
||||
# Co-responsible fields
|
||||
_add_person(source, associated_persons, "Mitverantwortlich")
|
||||
_add_person(source, associated_persons, "Mitverantwortlich(e)")
|
||||
_add_persons(source, associated_persons, "Mitverantwortliche")
|
||||
|
||||
# Application partner
|
||||
_add_person(source, associated_persons, "Anwendungspartner")
|
||||
|
||||
# Foreign co-applicant fields
|
||||
_add_persons(source, associated_persons, "ausländische Mitantragsteller")
|
||||
_add_person(source, associated_persons, "ausländischer Mitantragsteller")
|
||||
|
||||
# Person creator (from nested fields)
|
||||
if "person_creater_name" in source and source["person_creater_name"]:
|
||||
associated_persons.add(source["person_creater_name"].strip())
|
||||
|
||||
# Deputy (stellvertr) - nested object
|
||||
stellvertr = source.get("stellvertr")
|
||||
if stellvertr and isinstance(stellvertr, dict):
|
||||
for field in ["stellvertreter", "stellvertreterin"]:
|
||||
if field in stellvertr and stellvertr[field]:
|
||||
associated_persons.add(stellvertr[field].strip())
|
||||
|
||||
# --- Collect all institutions ---
|
||||
|
||||
_add_institution(source, institutions, "Antragstellende Institution")
|
||||
_add_institution(source, institutions, "Mitantragstellende Institution")
|
||||
_add_institution(source, institutions, "Beteiligte Einrichtung")
|
||||
_add_institution(source, institutions, "Beteiligte Hochschule")
|
||||
_add_institution(source, institutions, "Beteiligte Institution")
|
||||
_add_institution(source, institutions, "IGK-Partnerinstitution")
|
||||
_add_institution(source, institutions, "Partnerorganisation")
|
||||
_add_institution(source, institutions, "Unternehmen")
|
||||
|
||||
# Foreign institution (nested object)
|
||||
auslaend = source.get("ausländ")
|
||||
if auslaend and isinstance(auslaend, dict):
|
||||
for field in [
|
||||
"auslaendischeInstitution",
|
||||
"auslaendischeInstitution2",
|
||||
"auslaendischesUnternehmen",
|
||||
"auslaendischesUnternehmen2",
|
||||
]:
|
||||
if field in auslaend and auslaend[field]:
|
||||
institutions.add(auslaend[field].strip())
|
||||
return cls(
|
||||
id=hit["_id"],
|
||||
link=source.get("link"),
|
||||
title=source.get("title"),
|
||||
description=source.get("description"),
|
||||
project_identifier=source.get("Projektkennung"),
|
||||
funding_start_date=source.get("funding_start"),
|
||||
funding_end_date=source.get("funding_end"),
|
||||
dfg_procedure=source.get("DFG-Verfahren"),
|
||||
subject_area=source.get("Fachliche Zuordnung"),
|
||||
funding_type=source.get("Förderung"),
|
||||
international_reference=source.get("Internationaler Bezug"),
|
||||
website=source.get("Webseite"),
|
||||
associated_persons=sorted(associated_persons), # sorted for consistency
|
||||
institutions=sorted(institutions),
|
||||
subproject_of=source.get("Teilprojekt zu"),
|
||||
)
|
||||
|
||||
|
||||
# --- Helper functions for parsing source fields ---
|
||||
|
||||
def _add_person(source: dict, persons: Set[str], field: str) -> None:
|
||||
"""Add a single person value from a field."""
|
||||
if field in source and source[field]:
|
||||
value = source[field].strip()
|
||||
if value:
|
||||
persons.add(value)
|
||||
|
||||
|
||||
def _add_persons(source: dict, persons: Set[str], field: str) -> None:
|
||||
"""Add persons from a semicolon-separated field."""
|
||||
if field in source and source[field]:
|
||||
for person in source[field].split(";"):
|
||||
cleaned = person.strip()
|
||||
if cleaned:
|
||||
persons.add(cleaned)
|
||||
|
||||
|
||||
def _add_institution(source: dict, institutions: Set[str], field: str) -> None:
|
||||
"""Add a single institution value from a field."""
|
||||
if field in source and source[field]:
|
||||
value = source[field].strip()
|
||||
if value:
|
||||
institutions.add(value)
|
||||
@@ -0,0 +1,274 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Business logic for the "aktuell" news index on the INSE cluster.
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import HTTPException
|
||||
from starlette.status import HTTP_500_INTERNAL_SERVER_ERROR
|
||||
|
||||
from ..integrations import elasticsearch
|
||||
from ..persons.logic import find_ude_author_by_name, get_author_name_by_id
|
||||
from .model import MentionedPerson, NewsArticle, NewsArticleDetail, NewsPage
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def get_news_page(page: int, page_size: int, sort_order: str = "desc") -> NewsPage:
|
||||
offset = (page - 1) * page_size
|
||||
|
||||
response = _run_search(
|
||||
query={"match_all": {}},
|
||||
source=["date", "maintitle", "author", "url"],
|
||||
size=page_size,
|
||||
offset=offset,
|
||||
sort=[{"date_full": sort_order}],
|
||||
)
|
||||
|
||||
return _build_page(response, page, page_size)
|
||||
|
||||
|
||||
def search_news(query_text: str, page: int, page_size: int) -> NewsPage:
|
||||
offset = (page - 1) * page_size
|
||||
|
||||
highlight = {
|
||||
"fields": {"full_content": {"fragment_size": 200, "number_of_fragments": 1}},
|
||||
"pre_tags": ["<em>"],
|
||||
"post_tags": ["</em>"],
|
||||
"encoder": "html",
|
||||
}
|
||||
|
||||
response = _run_search(
|
||||
query={"match": {"full_content": query_text}},
|
||||
source=["date", "maintitle", "author", "url"],
|
||||
size=page_size,
|
||||
offset=offset,
|
||||
sort=None,
|
||||
highlight=highlight,
|
||||
)
|
||||
|
||||
return _build_page(response, page, page_size)
|
||||
|
||||
def get_news_by_author(
|
||||
author_id: str,
|
||||
page: int = 1,
|
||||
page_size: int = 10,
|
||||
sort_order: str = "desc",
|
||||
query_text: str | None = None,
|
||||
) -> NewsPage:
|
||||
|
||||
author_name = get_author_name_by_id(author_id)
|
||||
if not author_name:
|
||||
return _empty_page(page, page_size)
|
||||
|
||||
news_ids = _find_news_ids_for_author(author_name)
|
||||
if not news_ids:
|
||||
return _empty_page(page, page_size)
|
||||
|
||||
es_query = {"bool": {"filter": [{"ids": {"values": news_ids}}]}}
|
||||
if query_text:
|
||||
es_query["bool"]["must"] = [
|
||||
{"multi_match": {"query": query_text, "fields": ["maintitle", "author"]}}
|
||||
]
|
||||
|
||||
offset = (page - 1) * page_size
|
||||
response = _run_search(
|
||||
query=es_query,
|
||||
source=["date", "maintitle", "author", "url"],
|
||||
size=page_size,
|
||||
offset=offset,
|
||||
sort=[{"date_full": sort_order}],
|
||||
)
|
||||
|
||||
return _build_page(response, page, page_size)
|
||||
|
||||
|
||||
def _find_news_ids_for_author(author_name: str) -> list:
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
index="aktuell_postproc",
|
||||
query={"term": {"authors.keyword": author_name}},
|
||||
source=["news_id"],
|
||||
size=1000,
|
||||
cluster="inse",
|
||||
)
|
||||
except Exception:
|
||||
logger.exception(f"Postproc-search: Finding news IDs for author '{author_name}' failed.")
|
||||
return []
|
||||
|
||||
news_ids = []
|
||||
for hit in response.get("hits", {}).get("hits", []):
|
||||
news_id = hit.get("_source", {}).get("news_id")
|
||||
if news_id:
|
||||
news_ids.append(news_id)
|
||||
|
||||
return news_ids
|
||||
|
||||
|
||||
def _empty_page(page: int = 1, page_size: int = 0) -> NewsPage:
|
||||
return NewsPage(total=0, page=page, page_size=page_size, results=[])
|
||||
|
||||
|
||||
def get_news_by_id(news_id: str) -> NewsArticleDetail:
|
||||
try:
|
||||
response = elasticsearch.get(
|
||||
index="aktuell",
|
||||
doc_id=news_id,
|
||||
source=["date", "maintitle", "author", "url", "full_content"],
|
||||
cluster="inse",
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.exception("Abruf des News-Artikels fehlgeschlagen.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail="Etwas ist schiefgelaufen.",
|
||||
) from exc
|
||||
|
||||
source = response.get("_source", {})
|
||||
|
||||
relevant, authors = _get_postproc_labels(news_id)
|
||||
|
||||
return NewsArticleDetail(
|
||||
id=response.get("_id"),
|
||||
date=source.get("date"),
|
||||
maintitle=source.get("maintitle"),
|
||||
author=source.get("author"),
|
||||
url=source.get("url"),
|
||||
full_content=source.get("full_content"),
|
||||
relevant=relevant,
|
||||
authors=_build_mentioned_persons(authors),
|
||||
)
|
||||
|
||||
|
||||
def _build_mentioned_persons(author_names: list) -> list:
|
||||
|
||||
ude_persons = []
|
||||
other_persons = []
|
||||
|
||||
for name in author_names:
|
||||
match = find_ude_author_by_name(name)
|
||||
if match:
|
||||
ude_persons.append(
|
||||
MentionedPerson(name=name, is_ude=True, person_id=match["id"])
|
||||
)
|
||||
else:
|
||||
other_persons.append(MentionedPerson(name=name))
|
||||
|
||||
return ude_persons + other_persons
|
||||
|
||||
|
||||
def _get_postproc_labels(news_id: str) -> tuple[bool | None, list]:
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
index="aktuell_postproc",
|
||||
query={"term": {"news_id.keyword": news_id}},
|
||||
source=["relevant", "authors"],
|
||||
size=1,
|
||||
cluster="inse",
|
||||
)
|
||||
except Exception:
|
||||
logger.exception(f"Postproc-Lookup for {news_id} failed.")
|
||||
return None, []
|
||||
|
||||
hits = response.get("hits", {}).get("hits", [])
|
||||
if not hits:
|
||||
return None, []
|
||||
|
||||
postproc_source = hits[0].get("_source", {})
|
||||
relevant = bool(postproc_source.get("relevant", 0))
|
||||
authors = postproc_source.get("authors") or []
|
||||
|
||||
return relevant, authors
|
||||
|
||||
|
||||
def _run_search(query: dict, source: list, size: int, offset: int, sort, highlight: dict = None) -> dict:
|
||||
try:
|
||||
return elasticsearch.search(
|
||||
index="aktuell",
|
||||
query=query,
|
||||
source=source,
|
||||
size=size,
|
||||
offset=offset,
|
||||
sort=sort,
|
||||
track_total_hits=True,
|
||||
highlight=highlight,
|
||||
cluster="inse",
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.exception("Elasticsearch-Anfrage an Index 'aktuell' fehlgeschlagen.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail="Etwas ist schiefgelaufen.",
|
||||
) from exc
|
||||
|
||||
|
||||
def _build_page(response: dict, page: int, page_size: int) -> NewsPage:
|
||||
hits_section = response.get("hits", {})
|
||||
total = hits_section.get("total", {}).get("value", 0)
|
||||
hits = hits_section.get("hits", [])
|
||||
|
||||
news_ids = []
|
||||
for hit in hits:
|
||||
news_id = hit.get("_id")
|
||||
if news_id:
|
||||
news_ids.append(news_id)
|
||||
|
||||
relevance_map = _get_relevance_map(news_ids)
|
||||
|
||||
articles = []
|
||||
for hit in hits:
|
||||
article = _parse_hit(hit)
|
||||
article.relevant = relevance_map.get(article.id)
|
||||
articles.append(article)
|
||||
|
||||
return NewsPage(
|
||||
total=total,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
results=articles,
|
||||
)
|
||||
|
||||
|
||||
def _get_relevance_map(news_ids: list) -> dict:
|
||||
if not news_ids:
|
||||
return {}
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
index="aktuell_postproc",
|
||||
query={"terms": {"news_id.keyword": news_ids}},
|
||||
source=["news_id", "relevant"],
|
||||
size=len(news_ids),
|
||||
cluster="inse",
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Postproc-Relevanz-Lookup fehlgeschlagen.")
|
||||
return {}
|
||||
|
||||
relevance_map = {}
|
||||
for hit in response.get("hits", {}).get("hits", []):
|
||||
postproc_source = hit.get("_source", {})
|
||||
news_id = postproc_source.get("news_id")
|
||||
if news_id is not None:
|
||||
relevance_map[news_id] = bool(postproc_source.get("relevant", 0))
|
||||
|
||||
return relevance_map
|
||||
|
||||
|
||||
def _parse_hit(hit: dict) -> NewsArticle:
|
||||
source = hit.get("_source", {})
|
||||
|
||||
fragments = hit.get("highlight", {}).get("full_content")
|
||||
snippet = fragments[0] if fragments else None
|
||||
|
||||
return NewsArticle(
|
||||
id=hit.get("_id"),
|
||||
date=source.get("date"),
|
||||
maintitle=source.get("maintitle"),
|
||||
author=source.get("author"),
|
||||
url=source.get("url"),
|
||||
snippet=snippet,
|
||||
)
|
||||
@@ -0,0 +1,35 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from typing import List, Optional
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class NewsArticle(BaseModel):
|
||||
id: str
|
||||
date: Optional[str] = None
|
||||
maintitle: Optional[str] = None
|
||||
author: Optional[str] = None
|
||||
url: Optional[str] = None
|
||||
relevant: Optional[bool] = None
|
||||
snippet: Optional[str] = None
|
||||
|
||||
|
||||
class MentionedPerson(BaseModel):
|
||||
name: str
|
||||
is_ude: bool = False
|
||||
person_id: Optional[str] = None
|
||||
|
||||
|
||||
class NewsArticleDetail(NewsArticle):
|
||||
full_content: Optional[str] = None
|
||||
relevant: Optional[bool] = None
|
||||
authors: List[MentionedPerson] = []
|
||||
|
||||
|
||||
class NewsPage(BaseModel):
|
||||
total: int
|
||||
page: int
|
||||
page_size: int
|
||||
results: List[NewsArticle]
|
||||
@@ -0,0 +1,105 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
REST API for the "aktuell" news index.
|
||||
"""
|
||||
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter
|
||||
from fastapi import Path
|
||||
from fastapi import Query
|
||||
|
||||
from inse.tags import Tags
|
||||
from . import logic
|
||||
from .model import NewsArticleDetail, NewsPage
|
||||
|
||||
router = APIRouter(prefix="/api/news", tags=[Tags.NEWS])
|
||||
|
||||
|
||||
@router.get(
|
||||
"",
|
||||
operation_id="listNews",
|
||||
response_model=NewsPage,
|
||||
response_model_exclude_none=True,
|
||||
summary="Returns a page of news articles, newest first.",
|
||||
tags=[Tags.NEWS],
|
||||
)
|
||||
def list_news(
|
||||
page: Annotated[
|
||||
int, Query(description="Page number (1-based).", ge=1)
|
||||
] = 1,
|
||||
page_size: Annotated[
|
||||
int, Query(alias="pageSize", description="Articles per page.", ge=1, le=100)
|
||||
] = 10,
|
||||
sort_order: Annotated[
|
||||
str, Query(alias="sortOrder", description="Sort order: 'desc' (newest first) or 'asc' (oldest first).", pattern="^(asc|desc)$")
|
||||
] = "desc",
|
||||
):
|
||||
return logic.get_news_page(page, page_size, sort_order)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/search",
|
||||
operation_id="searchNews",
|
||||
response_model=NewsPage,
|
||||
response_model_exclude_none=True,
|
||||
summary="Searches news articles by full text (full_content).",
|
||||
tags=[Tags.NEWS],
|
||||
)
|
||||
def search_news(
|
||||
query: Annotated[
|
||||
str, Query(description="Search term, matched against the full text (full_content).", min_length=1)
|
||||
],
|
||||
page: Annotated[
|
||||
int, Query(description="Page number (1-based).", ge=1)
|
||||
] = 1,
|
||||
page_size: Annotated[
|
||||
int, Query(alias="pageSize", description="Articles per page.", ge=1, le=100)
|
||||
] = 10,
|
||||
):
|
||||
return logic.search_news(query, page, page_size)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/by-author",
|
||||
operation_id="getNewsByAuthor",
|
||||
response_model=NewsPage,
|
||||
response_model_exclude_none=True,
|
||||
summary="Returns news articles in which the given person is mentioned.",
|
||||
tags=[Tags.NEWS],
|
||||
)
|
||||
def get_news_by_author(
|
||||
author_id: Annotated[
|
||||
str, Query(alias="authorId", description="OpenAlex author id, e.g. A5034365278.")
|
||||
],
|
||||
page: Annotated[
|
||||
int, Query(description="Page number (1-based).", ge=1)
|
||||
] = 1,
|
||||
page_size: Annotated[
|
||||
int, Query(alias="pageSize", description="Articles per page.", ge=1, le=100)
|
||||
] = 10,
|
||||
sort_order: Annotated[
|
||||
str, Query(alias="sortOrder", description="Sort order: 'desc' (newest first) or 'asc' (oldest first).", pattern="^(asc|desc)$")
|
||||
] = "desc",
|
||||
query: Annotated[
|
||||
str | None, Query(description="Optional search term, matched against title/author.")
|
||||
] = None,
|
||||
):
|
||||
return logic.get_news_by_author(author_id, page, page_size, sort_order, query)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{news_id}",
|
||||
operation_id="getNewsById",
|
||||
response_model=NewsArticleDetail,
|
||||
response_model_exclude_none=True,
|
||||
summary="Returns a single news article including its full content.",
|
||||
tags=[Tags.NEWS],
|
||||
)
|
||||
def get_news_by_id(
|
||||
news_id: Annotated[
|
||||
str, Path(description="The unique id of the news article (Elasticsearch _id).")
|
||||
],
|
||||
):
|
||||
return logic.get_news_by_id(news_id)
|
||||
@@ -0,0 +1,5 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Patents domain package.
|
||||
"""
|
||||
@@ -0,0 +1,182 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
HTTP client for patent searches in EPO and USPTO Elasticsearch indices.
|
||||
"""
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
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
|
||||
|
||||
|
||||
def _match_name_field(field: str, name: str) -> dict[str, Any]:
|
||||
"""Match a name field, including transliterated variants (Müller/Mueller)."""
|
||||
variants = search_name_variants(name)
|
||||
if len(variants) <= 1:
|
||||
return {"match": {field: variants[0] if variants else name}}
|
||||
return {
|
||||
"bool": {
|
||||
"should": [{"match": {field: variant}} for variant in variants],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class MissingApiKeyError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class PatentSearchClient:
|
||||
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_by_inventor(
|
||||
self,
|
||||
last_name: str,
|
||||
first_name: str | None = None,
|
||||
size: int = DEFAULT_SEARCH_SIZE,
|
||||
) -> dict[str, Any]:
|
||||
"""Search EPO index: first AND last name in the SAME inventor entry."""
|
||||
if first_name:
|
||||
query = {
|
||||
"nested": {
|
||||
"path": "inventors_name_nested",
|
||||
"query": {
|
||||
"bool": {
|
||||
"must": [
|
||||
_match_name_field("inventors_name_nested.inventor", last_name),
|
||||
_match_name_field("inventors_name_nested.inventor", first_name),
|
||||
]
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
else:
|
||||
query = {
|
||||
"nested": {
|
||||
"path": "inventors_name_nested",
|
||||
"query": _match_name_field("inventors_name_nested.inventor", last_name),
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
"size": size,
|
||||
"track_total_hits": True,
|
||||
"sort": [
|
||||
{"_score": {"order": "desc"}},
|
||||
{"date_publication": {"order": "desc", "missing": "_last"}},
|
||||
"_doc",
|
||||
],
|
||||
"_source": [
|
||||
"doc_number",
|
||||
"country",
|
||||
"kind",
|
||||
"date_publication",
|
||||
"date_publication_year",
|
||||
"title_en",
|
||||
"title_de",
|
||||
"abstract",
|
||||
"inventors_name",
|
||||
"applicants_name",
|
||||
"ipc",
|
||||
"ipc_text",
|
||||
],
|
||||
"query": query,
|
||||
}
|
||||
|
||||
def uspto_query_by_inventor(
|
||||
self,
|
||||
last_name: str,
|
||||
first_name: str | None = None,
|
||||
size: int = DEFAULT_SEARCH_SIZE,
|
||||
) -> dict[str, Any]:
|
||||
"""Search USPTO index: first AND last name in the SAME inventor entry."""
|
||||
if first_name:
|
||||
query = {
|
||||
"nested": {
|
||||
"path": "inventors",
|
||||
"query": {
|
||||
"bool": {
|
||||
"must": [
|
||||
_match_name_field("inventors.name", last_name),
|
||||
_match_name_field("inventors.name", first_name),
|
||||
]
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
else:
|
||||
query = {
|
||||
"nested": {
|
||||
"path": "inventors",
|
||||
"query": _match_name_field("inventors.name", last_name),
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
"size": size,
|
||||
"track_total_hits": True,
|
||||
"sort": [
|
||||
{"_score": {"order": "desc"}},
|
||||
{"publication_date": {"order": "desc", "missing": "_last"}},
|
||||
"_doc",
|
||||
],
|
||||
"_source": [
|
||||
"publication_number",
|
||||
"country",
|
||||
"publication_date",
|
||||
"publication_year",
|
||||
"title",
|
||||
"abstract",
|
||||
"inventors_names",
|
||||
"inventors_names_text",
|
||||
"assignees_orgs",
|
||||
"ipcr",
|
||||
"ipcr_text",
|
||||
],
|
||||
"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()
|
||||
@@ -0,0 +1,156 @@
|
||||
#!/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
|
||||
@@ -0,0 +1,20 @@
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class PatentEntry(BaseModel):
|
||||
patent_id: str
|
||||
source: str # "EPO" or "USPTO"
|
||||
title: str | None = None
|
||||
abstract: str | None = None
|
||||
publication_date: str | None = None
|
||||
publication_year: str | None = None
|
||||
inventors: list[str] = Field(default_factory=list)
|
||||
assignees: list[str] = Field(default_factory=list)
|
||||
ipc: list[str] = 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]
|
||||
@@ -0,0 +1,242 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Name normalization and matching for patent inventor lookup.
|
||||
|
||||
Handles umlauts, diacritics, and common Latin transliterations so that
|
||||
e.g. 'Müller' matches 'Mueller' and 'Muller'.
|
||||
"""
|
||||
import re
|
||||
import unicodedata
|
||||
|
||||
# Characters that NFKD does not map to ASCII-friendly forms.
|
||||
_CHAR_REPLACEMENTS: dict[str, str] = {
|
||||
"ß": "ss",
|
||||
"ẞ": "ss",
|
||||
"æ": "ae",
|
||||
"Æ": "ae",
|
||||
"œ": "oe",
|
||||
"Œ": "oe",
|
||||
"ø": "o",
|
||||
"Ø": "o",
|
||||
"đ": "d",
|
||||
"Đ": "d",
|
||||
"ð": "d",
|
||||
"Ð": "d",
|
||||
"þ": "th",
|
||||
"Þ": "th",
|
||||
"ł": "l",
|
||||
"Ł": "l",
|
||||
"ı": "i",
|
||||
"ſ": "s",
|
||||
}
|
||||
|
||||
# German patent transliterations: ae/oe/ue often stand in for ä/ö/ü.
|
||||
_DIGRAPH_COLLAPSES: tuple[tuple[str, str], ...] = (
|
||||
("ae", "a"),
|
||||
("oe", "o"),
|
||||
("ue", "u"),
|
||||
)
|
||||
|
||||
# Common ASCII spellings in patent records for umlaut-derived vowels.
|
||||
_PATENT_VOWEL_EXPANSIONS: tuple[tuple[str, str], ...] = (
|
||||
(r"u([lmnrt])", r"ue\1"),
|
||||
(r"o([lmnrt])", r"oe\1"),
|
||||
(r"a([lmnrt])", r"ae\1"),
|
||||
)
|
||||
|
||||
|
||||
def normalize_name_part(value: str | None) -> str:
|
||||
"""
|
||||
Normalize a single name token for comparison.
|
||||
|
||||
Steps: transliteration map -> NFKD -> strip diacritics -> lowercase
|
||||
-> remove apostrophes/punctuation -> collapse whitespace.
|
||||
"""
|
||||
if not value:
|
||||
return ""
|
||||
|
||||
text = value.strip()
|
||||
for src, dst in _CHAR_REPLACEMENTS.items():
|
||||
text = text.replace(src, dst)
|
||||
|
||||
text = unicodedata.normalize("NFKD", text)
|
||||
text = "".join(c for c in text if not unicodedata.combining(c))
|
||||
text = text.lower()
|
||||
text = re.sub(r"[''`´]", "", text)
|
||||
text = re.sub(r"[^\w\s-]", "", text)
|
||||
text = re.sub(r"\s+", " ", text).strip()
|
||||
return text
|
||||
|
||||
|
||||
def name_token_variants(value: str | None) -> set[str]:
|
||||
"""
|
||||
Return equivalent forms of a name token.
|
||||
|
||||
Includes the normalized base plus German digraph collapses
|
||||
(Mueller -> muller) and hyphen Relaxed forms (Jean-Pierre -> jean pierre).
|
||||
"""
|
||||
base = normalize_name_part(value)
|
||||
if not base:
|
||||
return set()
|
||||
|
||||
variants = {base}
|
||||
|
||||
for src, dst in _DIGRAPH_COLLAPSES:
|
||||
if src in base:
|
||||
variants.add(base.replace(src, dst))
|
||||
|
||||
if "-" in base:
|
||||
variants.add(base.replace("-", ""))
|
||||
variants.add(base.replace("-", " "))
|
||||
|
||||
return {v for v in variants if v}
|
||||
|
||||
|
||||
def _patent_transliteration_expansions(normalized: str) -> set[str]:
|
||||
"""
|
||||
ASCII spellings used in patent records (e.g. Müller indexed as Mueller).
|
||||
|
||||
Used for Elasticsearch recall only; post-filter applies stricter matching.
|
||||
"""
|
||||
expanded = {normalized}
|
||||
for pattern, repl in _PATENT_VOWEL_EXPANSIONS:
|
||||
if re.search(pattern, normalized):
|
||||
expanded.add(re.sub(pattern, repl, normalized))
|
||||
return expanded
|
||||
|
||||
|
||||
def tokens_equal(
|
||||
left: str | None,
|
||||
right: str | None,
|
||||
*,
|
||||
allow_initial: bool = True,
|
||||
) -> bool:
|
||||
"""True when two name tokens are equivalent after normalization."""
|
||||
left_variants = name_token_variants(left)
|
||||
right_variants = name_token_variants(right)
|
||||
if not left_variants or not right_variants:
|
||||
return False
|
||||
if left_variants & right_variants:
|
||||
return True
|
||||
|
||||
if not allow_initial:
|
||||
return False
|
||||
|
||||
return _initial_tokens_match(left, right)
|
||||
|
||||
|
||||
def _initial_letter(token: str | None) -> str | None:
|
||||
normalized = normalize_name_part(token)
|
||||
if len(normalized) == 1 and normalized.isalpha():
|
||||
return normalized
|
||||
return None
|
||||
|
||||
|
||||
def _initial_tokens_match(left: str | None, right: str | None) -> bool:
|
||||
"""True when one token is a single-letter initial matching the other token."""
|
||||
left_initial = _initial_letter(left)
|
||||
right_initial = _initial_letter(right)
|
||||
left_full = normalize_name_part(left)
|
||||
right_full = normalize_name_part(right)
|
||||
|
||||
if left_initial and right_full and len(right_full) > 1:
|
||||
return right_full.startswith(left_initial)
|
||||
if right_initial and left_full and len(left_full) > 1:
|
||||
return left_full.startswith(right_initial)
|
||||
if left_initial and right_initial:
|
||||
return left_initial == right_initial
|
||||
return False
|
||||
|
||||
|
||||
def _inventor_first_token(inventor_name: str) -> str:
|
||||
if "," in inventor_name:
|
||||
_, first_part = [p.strip() for p in inventor_name.split(",", 1)]
|
||||
return first_part.split()[0] if first_part else ""
|
||||
parts = inventor_name.split()
|
||||
return parts[0] if parts else ""
|
||||
|
||||
|
||||
def first_name_match_kind(
|
||||
inventor_name: str,
|
||||
first_name: str,
|
||||
last_name: str,
|
||||
) -> str:
|
||||
"""
|
||||
Match quality for the inventor first name: 'full', 'initial', or 'none'.
|
||||
"""
|
||||
if not name_matches(inventor_name, first_name, last_name):
|
||||
return "none"
|
||||
|
||||
inventor_first = _inventor_first_token(inventor_name)
|
||||
if tokens_equal(inventor_first, first_name, allow_initial=False):
|
||||
return "full"
|
||||
return "initial"
|
||||
|
||||
|
||||
def search_name_variants(value: str | None) -> list[str]:
|
||||
"""
|
||||
Distinct search strings for Elasticsearch, preserving original casing
|
||||
where useful but including normalized and transliterated forms.
|
||||
"""
|
||||
if not value or not value.strip():
|
||||
return []
|
||||
|
||||
seen: set[str] = set()
|
||||
ordered: list[str] = []
|
||||
|
||||
def _add(candidate: str) -> None:
|
||||
key = candidate.casefold()
|
||||
if candidate.strip() and key not in seen:
|
||||
seen.add(key)
|
||||
ordered.append(candidate.strip())
|
||||
|
||||
_add(value.strip())
|
||||
|
||||
normalized = normalize_name_part(value)
|
||||
if normalized:
|
||||
_add(normalized.title())
|
||||
|
||||
for variant in name_token_variants(value):
|
||||
_add(variant.title())
|
||||
|
||||
for variant in _patent_transliteration_expansions(normalized):
|
||||
_add(variant.title())
|
||||
|
||||
if normalized and len(normalized) > 1:
|
||||
_add(normalized[0].upper())
|
||||
|
||||
return ordered
|
||||
|
||||
|
||||
def name_matches(inventor_name: str, first_name: str, last_name: str) -> bool:
|
||||
"""
|
||||
True when an inventor entry matches first_name + last_name.
|
||||
|
||||
Supports:
|
||||
- USPTO: 'Christian Weber', 'Christian Hans Weber'
|
||||
- EPO: 'Weber, Christian', 'Weber, Christian Hans'
|
||||
"""
|
||||
if not inventor_name or not last_name:
|
||||
return False
|
||||
|
||||
name = inventor_name.strip()
|
||||
|
||||
if "," in name:
|
||||
last_part, first_part = [p.strip() for p in name.split(",", 1)]
|
||||
first_token = first_part.split()[0] if first_part else ""
|
||||
return (
|
||||
tokens_equal(last_part, last_name, allow_initial=False)
|
||||
and bool(first_name)
|
||||
and tokens_equal(first_token, first_name)
|
||||
)
|
||||
|
||||
parts = name.split()
|
||||
if len(parts) < 2:
|
||||
return False
|
||||
|
||||
return (
|
||||
tokens_equal(parts[-1], last_name, allow_initial=False)
|
||||
and bool(first_name)
|
||||
and tokens_equal(parts[0], first_name)
|
||||
)
|
||||
@@ -0,0 +1,20 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
REST API for patent matching by author.
|
||||
"""
|
||||
from fastapi import APIRouter
|
||||
from . import logic
|
||||
from . import model
|
||||
|
||||
router = APIRouter(prefix="/api/inse-service/authors", tags=["Patents"])
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{author_id}/patents",
|
||||
operation_id="getPatentsByAuthor",
|
||||
response_model=model.PatentsByAuthorResponse,
|
||||
summary="Get patents matched to an author by name.",
|
||||
)
|
||||
async def get_patents_by_author(author_id: str):
|
||||
return await logic.get_patents_by_author_id(author_id)
|
||||
@@ -0,0 +1,49 @@
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from inse.patents.elastic_search_client import (
|
||||
DEFAULT_SEARCH_SIZE,
|
||||
EPO_INDEX,
|
||||
PatentSearchClient,
|
||||
USPTO_INDEX,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def anyio_backend():
|
||||
return "asyncio"
|
||||
|
||||
|
||||
def test_epo_query_uses_nested_search_and_name_variants():
|
||||
client = PatentSearchClient(api_key="test-key")
|
||||
payload = client.epo_query_by_inventor("Müller", "Christian")
|
||||
|
||||
assert payload["size"] == DEFAULT_SEARCH_SIZE
|
||||
assert payload["sort"][0] == {"_score": {"order": "desc"}}
|
||||
nested = payload["query"]["nested"]
|
||||
assert nested["path"] == "inventors_name_nested"
|
||||
must = nested["query"]["bool"]["must"]
|
||||
assert len(must) == 2
|
||||
assert "should" in must[0]["bool"]
|
||||
|
||||
|
||||
def test_uspto_index_is_3_0():
|
||||
assert USPTO_INDEX == "uspto_patents_3.0"
|
||||
assert EPO_INDEX == "epo_index_1.0"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_search_epo_posts_to_correct_index():
|
||||
requests: list[str] = []
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
requests.append(request.url.path)
|
||||
return httpx.Response(200, json={"hits": {"hits": []}})
|
||||
|
||||
transport = httpx.MockTransport(handler)
|
||||
client = PatentSearchClient(api_key="test-key", transport=transport)
|
||||
|
||||
await client.search_epo(client.epo_query_by_inventor("Weber", "Christian"))
|
||||
|
||||
assert len(requests) == 1
|
||||
assert requests[0].endswith(f"/{EPO_INDEX}/_search")
|
||||
@@ -0,0 +1,123 @@
|
||||
import pytest
|
||||
|
||||
from inse.patents.name_matching import (
|
||||
first_name_match_kind,
|
||||
name_matches,
|
||||
name_token_variants,
|
||||
normalize_name_part,
|
||||
search_name_variants,
|
||||
tokens_equal,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("left", "right"),
|
||||
[
|
||||
("Müller", "Mueller"),
|
||||
("Müller", "Muller"),
|
||||
("Schöning", "Schoening"),
|
||||
("François", "Francois"),
|
||||
("José", "Jose"),
|
||||
("García", "Garcia"),
|
||||
("Bräun", "Braun"),
|
||||
("Straß", "Strass"),
|
||||
("Grøn", "Gron"),
|
||||
("Małgorzata", "Malgorzata"),
|
||||
("Øystein", "Oystein"),
|
||||
],
|
||||
)
|
||||
def test_tokens_equal_transliteration(left: str, right: str) -> None:
|
||||
assert tokens_equal(left, right)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("left", "right"),
|
||||
[
|
||||
("Christian", "Marc"),
|
||||
("Weber", "Wagner"),
|
||||
("Müller", "Meier"),
|
||||
],
|
||||
)
|
||||
def test_tokens_equal_rejects_different_names(left: str, right: str) -> None:
|
||||
assert not tokens_equal(left, right)
|
||||
|
||||
|
||||
def test_hyphenated_first_name() -> None:
|
||||
assert tokens_equal("Jean-Pierre", "Jean Pierre")
|
||||
assert tokens_equal("Jean-Pierre", "JeanPierre")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("inventor", "first", "last", "expected"),
|
||||
[
|
||||
("Christian Weber", "Christian", "Weber", True),
|
||||
("Weber, Christian", "Christian", "Weber", True),
|
||||
("Marc Christian Weber", "Christian", "Weber", False),
|
||||
("Müller, Hans", "Hans", "Müller", True),
|
||||
("Mueller, Hans", "Hans", "Müller", True),
|
||||
("Hans Mueller", "Hans", "Müller", True),
|
||||
("Weber, Christian Hans", "Christian", "Weber", True),
|
||||
("Schoening, Klaus", "Klaus", "Schöning", True),
|
||||
],
|
||||
)
|
||||
def test_name_matches(inventor: str, first: str, last: str, expected: bool) -> None:
|
||||
assert name_matches(inventor, first, last) is expected
|
||||
|
||||
|
||||
def test_normalize_name_part_strips_diacritics() -> None:
|
||||
assert normalize_name_part("François") == "francois"
|
||||
assert normalize_name_part(" O'Brien ") == "obrien"
|
||||
|
||||
|
||||
def test_search_name_variants_includes_transliterations() -> None:
|
||||
variants = search_name_variants("Müller")
|
||||
folded = {v.casefold() for v in variants}
|
||||
assert "müller" in folded or "Müller".casefold() in folded
|
||||
assert "mueller" in folded
|
||||
assert "muller" in folded
|
||||
|
||||
|
||||
def test_name_token_variants_mueller() -> None:
|
||||
variants = name_token_variants("Mueller")
|
||||
assert "mueller" in variants
|
||||
assert "muller" in variants
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("left", "right"),
|
||||
[
|
||||
("C", "Christian"),
|
||||
("C.", "Christian"),
|
||||
("Christian", "C"),
|
||||
],
|
||||
)
|
||||
def test_tokens_equal_initials(left: str, right: str) -> None:
|
||||
assert tokens_equal(left, right)
|
||||
|
||||
|
||||
def test_tokens_equal_initials_not_for_last_names_by_default() -> None:
|
||||
assert not tokens_equal("W", "Weber", allow_initial=False)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("inventor", "first", "last", "expected"),
|
||||
[
|
||||
("C. Weber", "Christian", "Weber", True),
|
||||
("Weber, C.", "Christian", "Weber", True),
|
||||
("Weber, C", "Christian", "Weber", True),
|
||||
],
|
||||
)
|
||||
def test_name_matches_initials(inventor: str, first: str, last: str, expected: bool) -> None:
|
||||
assert name_matches(inventor, first, last) is expected
|
||||
|
||||
|
||||
def test_first_name_match_kind() -> None:
|
||||
assert first_name_match_kind("Christian Weber", "Christian", "Weber") == "full"
|
||||
assert first_name_match_kind("C. Weber", "Christian", "Weber") == "initial"
|
||||
assert first_name_match_kind("Marc Christian Weber", "Christian", "Weber") == "none"
|
||||
|
||||
|
||||
def test_search_name_variants_includes_initial() -> None:
|
||||
variants = search_name_variants("Christian")
|
||||
assert "C" in variants
|
||||
|
||||
@@ -7,10 +7,14 @@ Business logic for persons / authors.
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
from datetime import datetime
|
||||
from typing import Optional, Callable, Any, List
|
||||
from elasticsearch import ApiError, NotFoundError
|
||||
import hashlib
|
||||
import httpx
|
||||
from fastapi import HTTPException
|
||||
|
||||
from inse.model import ESIndex
|
||||
from .. import config
|
||||
from .. import util
|
||||
from ..integrations import llm
|
||||
@@ -24,10 +28,65 @@ from inse.persons.model import (
|
||||
CustomAuthor,
|
||||
CustomAuthorsListResponse,
|
||||
PersonSearchRequest,
|
||||
CareerMetrics,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
INDEX_NAME = "openalex-authors"
|
||||
UDE_INSTITUTION_ID = "https://openalex.org/I62318514" # Universität Duisburg-Essen
|
||||
|
||||
def find_ude_author_by_name(display_name: str) -> Optional[dict]:
|
||||
query = {
|
||||
"_source": ["display_name"],
|
||||
"query": {
|
||||
"bool": {
|
||||
"must": [
|
||||
{
|
||||
"match_phrase": {
|
||||
"display_name": display_name
|
||||
}
|
||||
},
|
||||
{
|
||||
"nested": {
|
||||
"path": "affiliations",
|
||||
"query": {
|
||||
"term": {
|
||||
"affiliations.institution.id": UDE_INSTITUTION_ID
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
]
|
||||
}
|
||||
},
|
||||
"size": 10,
|
||||
}
|
||||
|
||||
try:
|
||||
data = elasticsearch.search(index=INDEX_NAME, body=query)
|
||||
except Exception:
|
||||
logger.exception(f"UDE-Lookup für '{display_name}' fehlgeschlagen.")
|
||||
return None
|
||||
|
||||
hits = data.get("hits", {}).get("hits", [])
|
||||
|
||||
display_name = display_name.strip().lower()
|
||||
exact_matches = []
|
||||
|
||||
for hit in hits:
|
||||
hit_display_name = hit.get("_source", {}).get("display_name", "")
|
||||
if hit_display_name.strip().lower() == display_name:
|
||||
exact_matches.append(hit)
|
||||
|
||||
if not exact_matches:
|
||||
return None
|
||||
|
||||
hit = exact_matches[0]
|
||||
|
||||
return {
|
||||
"id": hit.get("_id"),
|
||||
"display_name": hit.get("_source", {}).get("display_name"),
|
||||
}
|
||||
|
||||
|
||||
def get_author_name_by_id(author_id: str) -> Optional[str]:
|
||||
@@ -53,20 +112,26 @@ def get_author_name_by_id(author_id: str) -> Optional[str]:
|
||||
def search_persons(
|
||||
author_id: Optional[str] = None,
|
||||
query: Optional[str] = None,
|
||||
include: Optional[set[str]] = None,
|
||||
) -> AuthorsListResponse:
|
||||
if author_id:
|
||||
query_field = "_id"
|
||||
query_value = author_id
|
||||
query_ = {
|
||||
"query_string": {
|
||||
"default_field": "_id",
|
||||
"query": author_id,
|
||||
}
|
||||
}
|
||||
|
||||
elif query:
|
||||
query_field = "display_name"
|
||||
query_value = query
|
||||
query_ = {
|
||||
"query_string": {
|
||||
"default_field": "display_name",
|
||||
"query": query,
|
||||
}
|
||||
}
|
||||
else:
|
||||
return AuthorsListResponse(results=[], meta=Meta(count=0))
|
||||
|
||||
data = elasticsearch.search(
|
||||
index="openalex-authors", query_field=query_field, query_value=query_value
|
||||
)
|
||||
data = elasticsearch.search(index=ESIndex.OPENALEX_AUTHORS, query=query_)
|
||||
|
||||
authors = []
|
||||
for hit in data.get("hits", {}).get("hits", []):
|
||||
@@ -186,6 +251,119 @@ def _fetch_works_and_topics(author_id: str) -> tuple[list, list]:
|
||||
return works, topics
|
||||
|
||||
|
||||
def _get_publication_years_for_author(author_id: str) -> list[int]:
|
||||
author_url = f"https://openalex.org/{author_id.strip()}"
|
||||
|
||||
body = {
|
||||
"size": 0,
|
||||
"query": {
|
||||
"nested": {
|
||||
"path": "authorships",
|
||||
"query": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{"term": {"authorships.author.id": author_url}},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
"aggs": {
|
||||
"publication_years": {
|
||||
"terms": {
|
||||
"field": "publication_year",
|
||||
"size": 1000,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
response = elasticsearch.search(
|
||||
index=config.settings.openalex_works_search_index,
|
||||
body=body,
|
||||
)
|
||||
|
||||
buckets = (
|
||||
response.get("aggregations", {}).get("publication_years", {}).get("buckets", [])
|
||||
)
|
||||
|
||||
publication_years: list[int] = []
|
||||
|
||||
for bucket in buckets:
|
||||
year = bucket.get("key")
|
||||
count = bucket.get("doc_count", 0)
|
||||
|
||||
if isinstance(year, int):
|
||||
publication_years.extend([year] * count)
|
||||
|
||||
return publication_years
|
||||
|
||||
|
||||
def _classify_career_stage(active_years: int) -> str:
|
||||
if active_years <= 0:
|
||||
return "unknown"
|
||||
|
||||
if active_years <= 4:
|
||||
return "Early Researcher"
|
||||
|
||||
if active_years <= 10:
|
||||
return "Emerging Researcher"
|
||||
|
||||
if active_years <= 20:
|
||||
return "Established Researcher"
|
||||
|
||||
return "Senior Researcher"
|
||||
|
||||
|
||||
def _compute_career_metrics(publication_years: list[int]) -> CareerMetrics:
|
||||
current_year = datetime.now().year
|
||||
|
||||
if not publication_years:
|
||||
return CareerMetrics()
|
||||
|
||||
sorted_years = sorted(publication_years)
|
||||
unique_years = sorted(set(publication_years))
|
||||
|
||||
first_year = sorted_years[0]
|
||||
last_year = sorted_years[-1]
|
||||
|
||||
publication_count = len(sorted_years)
|
||||
active_years = len(unique_years)
|
||||
career_stage = _classify_career_stage(active_years)
|
||||
career_age = last_year - first_year
|
||||
career_span = last_year - first_year + 1
|
||||
|
||||
publications_per_active_year = (
|
||||
publication_count / active_years if active_years > 0 else None
|
||||
)
|
||||
|
||||
publications_per_career_year = (
|
||||
publication_count / career_span if career_span > 0 else None
|
||||
)
|
||||
|
||||
years_since_last_publication = current_year - last_year
|
||||
has_suspicious_publication_years = first_year < 1970 or career_span > 60
|
||||
|
||||
return CareerMetrics(
|
||||
first_publication_year=first_year,
|
||||
last_publication_year=last_year,
|
||||
career_age=career_age,
|
||||
career_span=career_span,
|
||||
career_stage=career_stage,
|
||||
active_years=active_years,
|
||||
publication_count=publication_count,
|
||||
publications_per_active_year=publications_per_active_year,
|
||||
publications_per_career_year=publications_per_career_year,
|
||||
years_since_last_publication=years_since_last_publication,
|
||||
has_suspicious_publication_years=has_suspicious_publication_years,
|
||||
)
|
||||
|
||||
|
||||
def get_career_metrics_for_author(author_id: str) -> CareerMetrics:
|
||||
publication_years = _get_publication_years_for_author(author_id)
|
||||
return _compute_career_metrics(publication_years)
|
||||
|
||||
|
||||
def _build_papers(works: list) -> list:
|
||||
|
||||
papers = []
|
||||
@@ -254,23 +432,33 @@ def generate_person_bio(author_id: str, include: Optional[set[str]] = None) -> s
|
||||
|
||||
def get_person_by_id(
|
||||
author_id: str, include: Optional[str] = None
|
||||
) -> AuthorsListResponse:
|
||||
) -> CustomAuthorsListResponse:
|
||||
body = {
|
||||
"_source": include.split(",") if include else True,
|
||||
}
|
||||
|
||||
try:
|
||||
hit = elasticsearch.get(index="openalex-authors", body=body, doc_id=author_id)
|
||||
hit = elasticsearch.get(
|
||||
index="openalex-authors",
|
||||
body=body,
|
||||
doc_id=author_id,
|
||||
)
|
||||
except NotFoundError:
|
||||
raise HTTPException(
|
||||
status_code=404, detail=f"Person with id {author_id} not found"
|
||||
)
|
||||
|
||||
except ApiError as e:
|
||||
raise HTTPException(status_code=500, detail=f"Elasticsearch error: {str(e)}")
|
||||
persons = [util.get_persons_data(hit)]
|
||||
|
||||
return AuthorsListResponse(results=persons)
|
||||
author = util.get_persons_data(hit)
|
||||
career_metrics = get_career_metrics_for_author(author_id)
|
||||
|
||||
custom_author = CustomAuthor(
|
||||
**author.model_dump(),
|
||||
career_metrics=career_metrics,
|
||||
)
|
||||
|
||||
return CustomAuthorsListResponse(results=[custom_author])
|
||||
|
||||
|
||||
def search_persons_by_name(
|
||||
|
||||
@@ -13,20 +13,59 @@ from inse.models.openalex.authors_list_response import AuthorsListResponse
|
||||
|
||||
from inse.models.openalex.group_by_result import GroupByResult
|
||||
|
||||
class CareerMetrics(BaseModel):
|
||||
first_publication_year: Optional[int] = Field(
|
||||
default=None, description="First publication year of the author."
|
||||
)
|
||||
last_publication_year: Optional[int] = Field(
|
||||
default=None, description="Last publication year of the author."
|
||||
)
|
||||
career_age: Optional[int] = Field(
|
||||
default=None, description="Difference between last and first publication year."
|
||||
)
|
||||
career_span: Optional[int] = Field(
|
||||
default=None, description="Inclusive span from first to last publication year."
|
||||
)
|
||||
career_stage: Optional[str] = Field(
|
||||
default=None,
|
||||
description="Threshold-based career stage derived from active publication years.",
|
||||
)
|
||||
active_years: int = Field(
|
||||
default=0, description="Number of distinct years with at least one publication."
|
||||
)
|
||||
publication_count: int = Field(
|
||||
default=0, description="Number of publications used for career metrics."
|
||||
)
|
||||
publications_per_active_year: Optional[float] = Field(
|
||||
default=None, description="Average publications per active publication year."
|
||||
)
|
||||
publications_per_career_year: Optional[float] = Field(
|
||||
default=None, description="Average publications per year over the full career span."
|
||||
)
|
||||
years_since_last_publication: Optional[int] = Field(
|
||||
default=None, description="Years since the last publication."
|
||||
)
|
||||
has_suspicious_publication_years: bool = Field(
|
||||
default=False, description="True if publication years look suspicious."
|
||||
)
|
||||
|
||||
|
||||
class CustomAuthor(Author):
|
||||
relevance_rating: Optional[str] = Field(
|
||||
default=None, description="The relevance suitability rating."
|
||||
)
|
||||
career_metrics: Optional[CareerMetrics] = Field(
|
||||
default=None, description="Publication-history-based career metrics."
|
||||
)
|
||||
|
||||
|
||||
class CustomAuthorsListResponse(AuthorsListResponse):
|
||||
placeholder: Optional[CustomAuthor] = Field(
|
||||
default=None, description="A placeholder field for generation."
|
||||
)
|
||||
# meta: Optional[Meta] = None
|
||||
# results: Optional[List[CustomAuthor]] = None
|
||||
# group_by: Optional[List[GroupByResult]] = None
|
||||
results: Optional[List[CustomAuthor]] = None
|
||||
meta: Optional[Meta] = None
|
||||
group_by: Optional[List[GroupByResult]] = None
|
||||
|
||||
|
||||
class PersonBio(BaseModel):
|
||||
|
||||
@@ -53,7 +53,7 @@ def search_persons(
|
||||
if include
|
||||
else None
|
||||
)
|
||||
return logic.search_persons(author_id, query, include_set)
|
||||
return logic.search_persons(author_id, query)
|
||||
|
||||
|
||||
@router.get(
|
||||
@@ -85,7 +85,7 @@ def generate_person_bio(
|
||||
@router.get(
|
||||
"/person/{id}",
|
||||
operation_id="getPersonByID",
|
||||
response_model=AuthorsListResponse,
|
||||
response_model=model.CustomAuthorsListResponse,
|
||||
summary="Searches for person by ID.",
|
||||
tags=["Persons"],
|
||||
)
|
||||
@@ -102,7 +102,7 @@ def get_person_by_id(
|
||||
),
|
||||
example="topics_full,topic_share",
|
||||
),
|
||||
],
|
||||
] = None,
|
||||
):
|
||||
return logic.get_person_by_id(author_id=id, include=include)
|
||||
|
||||
|
||||
@@ -1,9 +1,61 @@
|
||||
from datetime import date
|
||||
import datetime
|
||||
from enum import StrEnum
|
||||
from typing import List, Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
|
||||
from inse.models.bund_project import BundProject
|
||||
from inse.models.eu_project import EuProject
|
||||
from inse.models.cordis_eu_project import CordisEuProject
|
||||
from inse.model import ESIndex
|
||||
|
||||
|
||||
class ProjectType(StrEnum):
|
||||
BUND = "bund"
|
||||
EU = "eu"
|
||||
DFG = "dfg"
|
||||
|
||||
def to_es_index(self) -> ESIndex:
|
||||
mapping = {
|
||||
self.BUND: ESIndex.PROJECTS_BUND_V1,
|
||||
self.EU: ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
|
||||
self.DFG: ESIndex.PROJECTS_DFG_ALL,
|
||||
}
|
||||
index = mapping.get(self)
|
||||
if index is None:
|
||||
raise ValueError(f"Unsupported project type: {self}")
|
||||
return index
|
||||
|
||||
|
||||
class ProjectsSortBy(StrEnum):
|
||||
TITLE = "title"
|
||||
FUNDING_START = "funding_start"
|
||||
FUNDING_END = "funding_end"
|
||||
FUNDING_AMOUNT = "funding_amount"
|
||||
|
||||
def to_cordis_eu_project_sort_field(self) -> str:
|
||||
mapping = {
|
||||
self.TITLE: "title.keyword",
|
||||
self.FUNDING_START: "startDate",
|
||||
self.FUNDING_END: "endDate",
|
||||
self.FUNDING_AMOUNT: "ecMaxContribution",
|
||||
}
|
||||
return mapping.get(self, "title.keyword")
|
||||
|
||||
def to_bund_project_sort_field(self) -> str:
|
||||
mapping = {
|
||||
self.TITLE: "Thema.keyword",
|
||||
self.FUNDING_START: "funding_start",
|
||||
self.FUNDING_END: "funding_end",
|
||||
self.FUNDING_AMOUNT: "Fördersumme",
|
||||
}
|
||||
return mapping.get(self, "Thema.keyword")
|
||||
|
||||
|
||||
class SortDirection(StrEnum):
|
||||
ASC = "asc"
|
||||
DESC = "desc"
|
||||
|
||||
|
||||
class Page(BaseModel):
|
||||
@@ -73,3 +125,192 @@ class DfgProjectPage(Page):
|
||||
elements: List[DfgProjectSummary] = Field(
|
||||
default_factory=list, description="The DFG projects on this page."
|
||||
)
|
||||
|
||||
|
||||
class InstitutionFunderSummary(BaseModel):
|
||||
type: ProjectType = Field(
|
||||
description="The type of funding data (e.g., 'bund', 'eu', 'dfg')."
|
||||
)
|
||||
funding_per_year: dict = Field(
|
||||
default_factory=dict,
|
||||
description="A dictionary mapping years to total funding amounts for that year.",
|
||||
)
|
||||
annual_average_over_period: float = Field(
|
||||
default=0.0,
|
||||
description="The average annual funding over the continuous period covered by the data.",
|
||||
)
|
||||
|
||||
|
||||
class ProjectsFilteringProperties(BaseModel):
|
||||
project_type: ProjectType = Field(description="The type of projects to filter by.")
|
||||
page: int = Field(description="The page number for pagination.")
|
||||
size: int = Field(description="The page size for pagination.")
|
||||
raw_oa_institution_id: Optional[str] = Field(
|
||||
default=None, description="The raw OA institution ID to filter by."
|
||||
)
|
||||
query: Optional[str] = Field(
|
||||
default=None, description="The query string to filter projects by."
|
||||
)
|
||||
sort_by: ProjectsSortBy = Field(
|
||||
default=ProjectsSortBy.TITLE, description="The field to sort by."
|
||||
)
|
||||
sort_direction: SortDirection = Field(
|
||||
default=SortDirection.ASC, description="The sort direction (asc or desc)."
|
||||
)
|
||||
|
||||
|
||||
class CordisEuProjectPage(Page):
|
||||
elements: List[CordisEuProject] = Field(
|
||||
default_factory=list, description="The CORDIS EU projects on this page."
|
||||
)
|
||||
|
||||
|
||||
class FundingProject(BaseModel):
|
||||
type: ProjectType = Field(
|
||||
description="The type of the project.",
|
||||
examples=[ProjectType.BUND, ProjectType.EU, ProjectType.DFG],
|
||||
)
|
||||
id: str = Field(description="The unique identifier of the project.")
|
||||
title: Optional[str] = Field(default=None, description="The title of the project.")
|
||||
acronym: Optional[str] = Field(
|
||||
default=None, description="The acronym of the project (if available)."
|
||||
)
|
||||
start_date: Optional[date] = Field(
|
||||
default=None, description="The funding start date of the project."
|
||||
)
|
||||
end_date: Optional[date] = Field(
|
||||
default=None, description="The funding end date of the project."
|
||||
)
|
||||
funding_amount: Optional[float] = Field(
|
||||
default=None, description="The total funding amount for the project."
|
||||
)
|
||||
|
||||
@field_validator("start_date", "end_date", mode="before")
|
||||
@classmethod
|
||||
def parse_all_date_formats(cls, value):
|
||||
if isinstance(value, str):
|
||||
value = value.strip()
|
||||
|
||||
if len(value) == 4 and value.isdigit():
|
||||
return f"{value}-01-01"
|
||||
|
||||
if "." in value:
|
||||
return datetime.datetime.strptime(value, "%d.%m.%Y").date()
|
||||
|
||||
return value
|
||||
|
||||
return value
|
||||
|
||||
@classmethod
|
||||
def from_cordis_projects_hit(cls, hit: dict) -> "FundingProject":
|
||||
if not hit.get("_index", "").startswith("cordis_eu_") and not hit.get(
|
||||
"_index", ""
|
||||
).endswith("_projects"):
|
||||
raise ValueError(
|
||||
"The provided hit does not belong to an index starting with 'cordis_eu_' and ending with '_projects'."
|
||||
)
|
||||
|
||||
source = hit.get("_source", {})
|
||||
return cls(
|
||||
type=ProjectType.EU,
|
||||
id=hit.get("_id", ""),
|
||||
title=source.get("title"),
|
||||
start_date=source.get("startDate"),
|
||||
end_date=source.get("endDate"),
|
||||
funding_amount=source.get("ecMaxContribution"),
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def from_bund_projects_hit(cls, hit: dict) -> "FundingProject":
|
||||
if hit.get("_index") != "projects_bund_v1":
|
||||
raise ValueError(
|
||||
"The provided hit does not belong to the 'projects_bund_v1' index."
|
||||
)
|
||||
|
||||
source = hit.get("_source", {})
|
||||
return cls(
|
||||
type=ProjectType.BUND,
|
||||
id=source.get("Förderkennzeichen", ""),
|
||||
title=source.get("Thema"),
|
||||
start_date=source.get("funding_start"),
|
||||
end_date=source.get("funding_end"),
|
||||
funding_amount=source.get("Fördersumme"),
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def from_dfg_projects_hit(cls, hit: dict) -> "FundingProject":
|
||||
if hit.get("_index") != "projects_dfg_all":
|
||||
raise ValueError(
|
||||
"The provided hit does not belong to the 'projects_dfg_all' index."
|
||||
)
|
||||
|
||||
source = hit.get("_source", {})
|
||||
return cls(
|
||||
type=ProjectType.DFG,
|
||||
id=hit.get("_id", ""),
|
||||
title=source.get("title"),
|
||||
start_date=source.get("funding_start"),
|
||||
end_date=source.get("funding_end"),
|
||||
acronym=source.get("acronym"),
|
||||
)
|
||||
|
||||
|
||||
class FundingProjectPage(Page):
|
||||
elements: List[FundingProject] = Field(
|
||||
default_factory=list, description="The funding projects on this page."
|
||||
)
|
||||
|
||||
|
||||
class EuOrganizationShort(BaseModel):
|
||||
project_id: str = Field(description="The unique identifier of the project.")
|
||||
organization_id: str = Field(
|
||||
description="The unique identifier of the organization."
|
||||
)
|
||||
ec_contribution: Optional[float] = Field(
|
||||
default=None,
|
||||
description="The EC contribution amount for the organization in the project.",
|
||||
)
|
||||
|
||||
|
||||
class EuProjectShort(BaseModel):
|
||||
id: str = Field(description="The unique identifier of the EU project.")
|
||||
title: Optional[str] = Field(
|
||||
default=None, description="The title of the EU project."
|
||||
)
|
||||
start_date: Optional[date] = Field(
|
||||
default=None, description="The funding start date of the EU project."
|
||||
)
|
||||
end_date: Optional[date] = Field(
|
||||
default=None, description="The funding end date of the EU project."
|
||||
)
|
||||
acronym: Optional[str] = Field(
|
||||
default=None, description="The acronym of the EU project."
|
||||
)
|
||||
|
||||
|
||||
class EuOrganizationProjectSummary(BaseModel):
|
||||
organization_id: str = Field(
|
||||
description="The unique identifier of the organization."
|
||||
)
|
||||
project_id: str = Field(description="The unique identifier of the project.")
|
||||
title: Optional[str] = Field(default=None, description="The title of the project.")
|
||||
start_date: Optional[date] = Field(
|
||||
default=None, description="The funding start date of the project."
|
||||
)
|
||||
end_date: Optional[date] = Field(
|
||||
default=None, description="The funding end date of the project."
|
||||
)
|
||||
acronym: Optional[str] = Field(
|
||||
default=None, description="The acronym of the project."
|
||||
)
|
||||
ec_contribution: Optional[float] = Field(
|
||||
default=None,
|
||||
description="The EC contribution amount for the organization in the project.",
|
||||
)
|
||||
|
||||
|
||||
class EuOrganizationProjectSummaryPage(Page):
|
||||
elements: List[EuOrganizationProjectSummary] = Field(
|
||||
default_factory=list,
|
||||
description="The organization project summaries on this page.",
|
||||
)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,47 +1,66 @@
|
||||
from functools import lru_cache
|
||||
import logging
|
||||
from typing import Annotated, Optional
|
||||
from typing import Annotated, Optional, Set
|
||||
|
||||
from fastapi import APIRouter, Depends, Query, status
|
||||
from fastapi import APIRouter, Body, Depends, Path, Query, status
|
||||
|
||||
from inse.projects.model import BundProjectPage, DfgProjectPage, EuProjectPage
|
||||
from inse.projects.model import (
|
||||
BundProjectPage,
|
||||
CordisEuProjectPage,
|
||||
DfgProjectPage,
|
||||
EuOrganizationProjectSummaryPage,
|
||||
FundingProjectPage,
|
||||
InstitutionFunderSummary,
|
||||
ProjectType,
|
||||
ProjectsFilteringProperties,
|
||||
ProjectsSortBy,
|
||||
SortDirection,
|
||||
)
|
||||
from inse.models.dfg_project_details import DfgProjectDetails
|
||||
from inse.models.bund_project_details import BundProjectDetails
|
||||
from inse.tags import Tags
|
||||
from inse.projects import service as projects_service
|
||||
from inse.projects.projects_search_client import (
|
||||
BundProjectsSearchClient,
|
||||
DfgProjectsSearchClient,
|
||||
EuProjectsSearchClient,
|
||||
)
|
||||
|
||||
from inse.institutions.institutions_search_client import (
|
||||
InstitutionsSearchClient,
|
||||
)
|
||||
from inse.institutions.service import get_institutions_search_client
|
||||
from inse.institutions.router import get_institutions_search_client
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/api/projects", tags=[Tags.PROJECTS])
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_bund_search_client() -> BundProjectsSearchClient:
|
||||
return BundProjectsSearchClient()
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_eu_search_client() -> EuProjectsSearchClient:
|
||||
return EuProjectsSearchClient()
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_dfg_search_client() -> DfgProjectsSearchClient:
|
||||
return DfgProjectsSearchClient()
|
||||
|
||||
|
||||
@router.get(
|
||||
"/author/{raw_oa_author_id}/eu",
|
||||
summary="Get EU projects for an author.",
|
||||
description="Returns a list of EU projects associated with the specified author ID.",
|
||||
operation_id="getEuProjectsForAuthor",
|
||||
responses={
|
||||
status.HTTP_200_OK: {
|
||||
"description": "Successful Response",
|
||||
"model": CordisEuProjectPage,
|
||||
},
|
||||
status.HTTP_404_NOT_FOUND: {"description": "Author not found"},
|
||||
},
|
||||
response_model_by_alias=False,
|
||||
)
|
||||
def get_eu_projects_for_author(
|
||||
raw_oa_author_id: Annotated[str, Path(description="The author ID to filter by.")],
|
||||
) -> CordisEuProjectPage:
|
||||
logger.debug(
|
||||
f"Received request to get EU projects for author_id={raw_oa_author_id}"
|
||||
)
|
||||
return projects_service.search_cordis_eu_projects_for_author_id(
|
||||
raw_oa_author_id=raw_oa_author_id,
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/institution/bund/search",
|
||||
summary="Get bund projects.",
|
||||
description="Returns a page of bund projects based on the provided pagination parameters and optional institution filter.",
|
||||
operation_id="getBundProjects",
|
||||
operation_id="searchBundProjects",
|
||||
responses={
|
||||
status.HTTP_200_OK: {
|
||||
"description": "Successful Response",
|
||||
@@ -51,79 +70,149 @@ def get_dfg_search_client() -> DfgProjectsSearchClient:
|
||||
},
|
||||
response_model_by_alias=False,
|
||||
)
|
||||
async def get_bund_projects(
|
||||
bund_search_client: Annotated[
|
||||
BundProjectsSearchClient, Depends(get_bund_search_client)
|
||||
],
|
||||
async def search_bund_projects(
|
||||
institutions_search_client: Annotated[
|
||||
InstitutionsSearchClient, Depends(get_institutions_search_client)
|
||||
],
|
||||
institution_id: Annotated[
|
||||
str, Query(description="The institution ID to filter by.")
|
||||
filtering_properties: Annotated[
|
||||
ProjectsFilteringProperties,
|
||||
Body(description="The filtering properties for the projects search."),
|
||||
],
|
||||
topic: Annotated[
|
||||
Optional[str], Query(description="The topic to filter by.")
|
||||
] = None,
|
||||
page: Annotated[int, Query(description="The page number.", ge=0)] = 0,
|
||||
size: Annotated[int, Query(description="The page size.", ge=1)] = 20,
|
||||
sort_by: Annotated[str, Query(description="The field to sort by.")] = "topic",
|
||||
sort_direction: Annotated[
|
||||
str, Query(description="The sort direction (asc or desc).")
|
||||
] = "asc",
|
||||
) -> BundProjectPage:
|
||||
return await projects_service.get_bund_projects_by_institution_id(
|
||||
bund_search_client=bund_search_client,
|
||||
return projects_service.search_bund_projects(
|
||||
institutions_search_client=institutions_search_client,
|
||||
institution_id=institution_id,
|
||||
page=page,
|
||||
size=size,
|
||||
topic=topic,
|
||||
sort_by=sort_by,
|
||||
sort_direction=sort_direction,
|
||||
filtering_properties=filtering_properties,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/institution/eu/search",
|
||||
summary="Get EU projects.",
|
||||
description="Returns a page of EU projects based on the provided pagination parameters and optional institution filter.",
|
||||
operation_id="getEuProjects",
|
||||
"/dfg/{id}",
|
||||
summary="Get a single DFG project.",
|
||||
description="Returns a single DFG project based on its ID.",
|
||||
operation_id="getSingleDfgProject",
|
||||
responses={
|
||||
status.HTTP_200_OK: {
|
||||
"description": "Successful Response",
|
||||
"model": EuProjectPage,
|
||||
"model": DfgProjectDetails,
|
||||
},
|
||||
status.HTTP_404_NOT_FOUND: {"description": "Project not found"},
|
||||
},
|
||||
response_model_by_alias=False,
|
||||
)
|
||||
def get_single_dfg_project(
|
||||
id: Annotated[str, Path(description="The ID of the DFG project to retrieve.")],
|
||||
) -> DfgProjectDetails:
|
||||
logger.debug(f"Received request to get single DFG project for id={id}")
|
||||
return projects_service.get_single_dfg_project(
|
||||
project_id=id,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/bund/{id}",
|
||||
summary="Get a single BUND project.",
|
||||
description="Returns a single BUND project based on its ID.",
|
||||
operation_id="getSingleBundProject",
|
||||
responses={
|
||||
status.HTTP_200_OK: {
|
||||
"description": "Successful Response",
|
||||
"model": BundProjectDetails,
|
||||
},
|
||||
status.HTTP_404_NOT_FOUND: {"description": "Project not found"},
|
||||
},
|
||||
response_model_by_alias=False,
|
||||
)
|
||||
def get_single_bund_project(
|
||||
id: Annotated[str, Path(description="The ID of the BUND project to retrieve.")],
|
||||
) -> BundProjectDetails:
|
||||
logger.debug(f"Received request to get single BUND project for id={id}")
|
||||
return projects_service.get_single_bund_project(
|
||||
project_id=id,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/institution/bund/funding-over-time",
|
||||
summary="Get funding over time for bund projects.",
|
||||
description="Returns the funding over time for bund projects associated with the specified institution.",
|
||||
operation_id="getInstitutionBundProjectsFundingOverTime",
|
||||
responses={
|
||||
status.HTTP_200_OK: {
|
||||
"description": "Successful Response",
|
||||
"model": InstitutionFunderSummary,
|
||||
},
|
||||
status.HTTP_404_NOT_FOUND: {"description": "Institution not found"},
|
||||
},
|
||||
response_model_by_alias=False,
|
||||
)
|
||||
async def get_eu_projects(
|
||||
eu_search_client: Annotated[EuProjectsSearchClient, Depends(get_eu_search_client)],
|
||||
def get_institution_bund_projects_funding_over_time(
|
||||
institutions_search_client: Annotated[
|
||||
InstitutionsSearchClient, Depends(get_institutions_search_client)
|
||||
],
|
||||
institution_id: Annotated[
|
||||
raw_oa_institution_id: Annotated[
|
||||
str, Query(description="The institution ID to filter by.")
|
||||
],
|
||||
topic: Annotated[
|
||||
Optional[str], Query(description="The topic to filter by.")
|
||||
] = None,
|
||||
page: Annotated[int, Query(description="The page number.", ge=0)] = 0,
|
||||
size: Annotated[int, Query(description="The page size.", ge=1)] = 20,
|
||||
sort_by: Annotated[str, Query(description="The field to sort by.")] = "topic",
|
||||
sort_direction: Annotated[
|
||||
str, Query(description="The sort direction (asc or desc).")
|
||||
] = "asc",
|
||||
) -> EuProjectPage:
|
||||
return await projects_service.get_eu_projects_by_institution_id(
|
||||
eu_search_client=eu_search_client,
|
||||
) -> InstitutionFunderSummary:
|
||||
return projects_service.get_institution_bund_projects_funding_over_time(
|
||||
institutions_search_client=institutions_search_client,
|
||||
institution_id=institution_id,
|
||||
topic=topic,
|
||||
page=page,
|
||||
size=size,
|
||||
sort_by=sort_by,
|
||||
sort_direction=sort_direction,
|
||||
raw_oa_institution_id=raw_oa_institution_id,
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/institution/eu/search",
|
||||
summary="Get EU projects.",
|
||||
description="Returns a page of EU projects based on the provided pagination parameters and optional institution filter.",
|
||||
operation_id="searchCordisEuProjects",
|
||||
responses={
|
||||
status.HTTP_200_OK: {
|
||||
"description": "Successful Response",
|
||||
"model": EuOrganizationProjectSummaryPage,
|
||||
},
|
||||
status.HTTP_404_NOT_FOUND: {"description": "Institution not found"},
|
||||
},
|
||||
response_model_by_alias=False,
|
||||
)
|
||||
async def search_cordis_eu_projects(
|
||||
institutions_search_client: Annotated[
|
||||
InstitutionsSearchClient, Depends(get_institutions_search_client)
|
||||
],
|
||||
projects_filtering_properties: Annotated[
|
||||
ProjectsFilteringProperties,
|
||||
Body(description="The filtering properties for the projects search."),
|
||||
],
|
||||
) -> EuOrganizationProjectSummaryPage:
|
||||
return projects_service.search_cordis_eu_projects(
|
||||
institutions_search_client=institutions_search_client,
|
||||
projects_filtering_properties=projects_filtering_properties,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/institution/eu/funding-over-time",
|
||||
summary="Get funding over time for EU projects.",
|
||||
description="Returns the funding over time for EU projects associated with the specified institution.",
|
||||
operation_id="getInstitutionCordisEuProjectsFundingOverTime",
|
||||
responses={
|
||||
status.HTTP_200_OK: {
|
||||
"description": "Successful Response",
|
||||
"model": InstitutionFunderSummary,
|
||||
},
|
||||
status.HTTP_404_NOT_FOUND: {"description": "Institution not found"},
|
||||
},
|
||||
response_model_by_alias=False,
|
||||
)
|
||||
async def get_institution_cordis_eu_projects_funding_over_time(
|
||||
institutions_search_client: Annotated[
|
||||
InstitutionsSearchClient, Depends(get_institutions_search_client)
|
||||
],
|
||||
raw_oa_institution_id: Annotated[
|
||||
str, Query(description="The institution ID to filter by.")
|
||||
],
|
||||
) -> InstitutionFunderSummary:
|
||||
return await projects_service.get_institution_cordis_eu_projects_funding_over_time(
|
||||
institutions_search_client=institutions_search_client,
|
||||
raw_oa_institution_id=raw_oa_institution_id,
|
||||
)
|
||||
|
||||
|
||||
@@ -142,9 +231,6 @@ async def get_eu_projects(
|
||||
response_model_by_alias=False,
|
||||
)
|
||||
async def get_dfg_projects(
|
||||
dfg_search_client: Annotated[
|
||||
DfgProjectsSearchClient, Depends(get_dfg_search_client)
|
||||
],
|
||||
author_id: Annotated[str, Query(description="The author ID to filter by.")],
|
||||
topic: Annotated[
|
||||
Optional[str], Query(description="The topic to filter by.")
|
||||
@@ -166,7 +252,6 @@ async def get_dfg_projects(
|
||||
sort_direction,
|
||||
)
|
||||
return await projects_service.get_dfg_projects_by_author_id(
|
||||
dfg_search_client=dfg_search_client,
|
||||
author_id=author_id,
|
||||
topic=topic,
|
||||
page=page,
|
||||
@@ -174,3 +259,45 @@ async def get_dfg_projects(
|
||||
sort_by=sort_by,
|
||||
sort_direction=sort_direction,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/search",
|
||||
summary="Search projects across all funders.",
|
||||
description="Returns a page of projects across all funders based on the provided pagination parameters and optional institution filter.",
|
||||
operation_id="searchProjects",
|
||||
responses={
|
||||
status.HTTP_200_OK: {
|
||||
"description": "Successful Response",
|
||||
"model": FundingProjectPage,
|
||||
},
|
||||
},
|
||||
response_model_by_alias=False,
|
||||
)
|
||||
def search_projects(
|
||||
page: Annotated[int, Query(description="The page number.", ge=0)] = 0,
|
||||
size: Annotated[int, Query(description="The page size.", ge=1)] = 10,
|
||||
selected_project_types: Annotated[
|
||||
Optional[Set[ProjectType]],
|
||||
Query(
|
||||
description="The set of project types to filter by (e.g., 'bund', 'eu', 'dfg'). If not provided, projects of all types will be included."
|
||||
),
|
||||
] = None,
|
||||
title: Annotated[
|
||||
Optional[str], Query(description="The title to filter by.")
|
||||
] = None,
|
||||
sort_by: Annotated[
|
||||
ProjectsSortBy, Query(description="The field to sort by.")
|
||||
] = ProjectsSortBy.TITLE,
|
||||
sort_direction: Annotated[
|
||||
SortDirection, Query(description="The sort direction (asc or desc).")
|
||||
] = SortDirection.ASC,
|
||||
) -> FundingProjectPage:
|
||||
return projects_service.search_all_projects(
|
||||
page=page,
|
||||
size=size,
|
||||
selected_project_types=selected_project_types,
|
||||
title=title,
|
||||
sort_by=sort_by,
|
||||
sort_direction=sort_direction,
|
||||
)
|
||||
|
||||
@@ -1,109 +1,149 @@
|
||||
import datetime
|
||||
import logging
|
||||
from typing import List, Optional
|
||||
from typing import Any, Dict, List, Optional, Set
|
||||
|
||||
from inse.projects import projects_search_client
|
||||
from inse.projects.projects_search_client import (
|
||||
BundProjectsSearchClient,
|
||||
DfgProjectsSearchClient,
|
||||
EuProjectsSearchClient,
|
||||
get_eu_organization_project_contributions,
|
||||
)
|
||||
from inse.projects.model import BundProjectPage, DfgProjectPage, EuProjectPage
|
||||
from inse.projects.model import (
|
||||
BundProjectPage,
|
||||
CordisEuProjectPage,
|
||||
DfgProjectPage,
|
||||
EuOrganizationProjectSummaryPage,
|
||||
FundingProjectPage,
|
||||
InstitutionFunderSummary,
|
||||
ProjectType,
|
||||
ProjectsFilteringProperties,
|
||||
ProjectsSortBy,
|
||||
SortDirection,
|
||||
)
|
||||
from inse.models.dfg_project_details import DfgProjectDetails
|
||||
from inse.models.bund_project_details import BundProjectDetails
|
||||
from inse.institutions.institutions_search_client import (
|
||||
InstitutionsSearchClient,
|
||||
)
|
||||
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
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def get_bund_projects_by_institution_id(
|
||||
bund_search_client: BundProjectsSearchClient,
|
||||
institutions_search_client: InstitutionsSearchClient,
|
||||
institution_id: str,
|
||||
def search_all_projects(
|
||||
page: int,
|
||||
size: int,
|
||||
topic: Optional[str],
|
||||
sort_by: str = "topic",
|
||||
sort_direction: str = "asc",
|
||||
sort_by: ProjectsSortBy,
|
||||
sort_direction: SortDirection,
|
||||
selected_project_types: Optional[Set[ProjectType]] = None,
|
||||
title: Optional[str] = None,
|
||||
) -> FundingProjectPage:
|
||||
return projects_search_client.search_all_projects(
|
||||
projects_filtering_properties=ProjectsFilteringProperties(
|
||||
project_type=ProjectType.EU, # placeholder, shall be ignored in search_all_projects
|
||||
page=page,
|
||||
size=size,
|
||||
sort_by=sort_by,
|
||||
sort_direction=sort_direction,
|
||||
query=title,
|
||||
),
|
||||
selected_project_types=selected_project_types,
|
||||
)
|
||||
|
||||
|
||||
def search_bund_projects(
|
||||
institutions_search_client: InstitutionsSearchClient,
|
||||
filtering_properties: ProjectsFilteringProperties,
|
||||
) -> BundProjectPage:
|
||||
if filtering_properties.project_type != "bund":
|
||||
raise ValueError(
|
||||
f"Invalid project type: {filtering_properties.project_type}. Expected 'bund'."
|
||||
)
|
||||
|
||||
logger.debug(
|
||||
f"search_bund_projects called with filtering_properties: {filtering_properties}"
|
||||
)
|
||||
|
||||
return get_bund_projects_by_institution_id(
|
||||
institutions_search_client=institutions_search_client,
|
||||
filtering_properties=filtering_properties,
|
||||
)
|
||||
|
||||
|
||||
def get_bund_projects_by_institution_id(
|
||||
institutions_search_client: InstitutionsSearchClient,
|
||||
filtering_properties: ProjectsFilteringProperties,
|
||||
) -> BundProjectPage:
|
||||
if filtering_properties.raw_oa_institution_id is None:
|
||||
raise ValueError("raw_oa_institution_id must be provided")
|
||||
|
||||
logger.info(
|
||||
f"Fetching bund projects for institution_id={institution_id}, page={page}, size={size}"
|
||||
f"Fetching bund projects for institution_id={filtering_properties.raw_oa_institution_id}, page={filtering_properties.page}, size={filtering_properties.size}"
|
||||
)
|
||||
institution_aliases = (
|
||||
await institutions_search_client.get_institution_aliases_by_id(institution_id)
|
||||
institutions_search_client.get_institution_aliases_by_oa_institution_id(
|
||||
filtering_properties.raw_oa_institution_id
|
||||
)
|
||||
)
|
||||
logger.debug(
|
||||
f"Found institution aliases for institution_id={institution_id}: {institution_aliases}"
|
||||
f"get_bund_projects_by_institution_id: Found institution aliases for institution_id={filtering_properties.raw_oa_institution_id}: {institution_aliases}"
|
||||
)
|
||||
response = await bund_search_client.search_bund_projects(
|
||||
page=page,
|
||||
size=size,
|
||||
response = projects_search_client.search_bund_projects(
|
||||
institution_names=institution_aliases,
|
||||
topic=topic,
|
||||
sort_by=sort_by,
|
||||
sort_direction=sort_direction,
|
||||
filter_properties=filtering_properties,
|
||||
)
|
||||
logger.debug(f"get_bund_projects_by_institution_id response: {response}")
|
||||
return response
|
||||
|
||||
|
||||
async def get_eu_projects_by_institution_id(
|
||||
eu_search_client: EuProjectsSearchClient,
|
||||
def search_cordis_eu_projects(
|
||||
institutions_search_client: InstitutionsSearchClient,
|
||||
institution_id: str,
|
||||
topic: Optional[str],
|
||||
page: int,
|
||||
size: int,
|
||||
sort_by: str = "topic",
|
||||
sort_direction: str = "asc",
|
||||
) -> EuProjectPage:
|
||||
projects_filtering_properties: ProjectsFilteringProperties,
|
||||
) -> EuOrganizationProjectSummaryPage:
|
||||
if projects_filtering_properties.project_type != "eu":
|
||||
raise ValueError(
|
||||
f"Invalid project type: {projects_filtering_properties.project_type}. Expected 'eu'."
|
||||
)
|
||||
|
||||
return get_cordis_eu_projects_by_institution_id(
|
||||
institutions_search_client=institutions_search_client,
|
||||
projects_filtering_properties=projects_filtering_properties,
|
||||
)
|
||||
|
||||
|
||||
def get_cordis_eu_projects_by_institution_id(
|
||||
institutions_search_client: InstitutionsSearchClient,
|
||||
projects_filtering_properties: ProjectsFilteringProperties,
|
||||
) -> EuOrganizationProjectSummaryPage:
|
||||
if not projects_filtering_properties.raw_oa_institution_id:
|
||||
raise ValueError(
|
||||
"raw_oa_institution_id must be provided to fetch CORDIS EU projects by institution ID"
|
||||
)
|
||||
|
||||
logger.info(
|
||||
f"Fetching EU projects for institution_id={institution_id}, page={page}, size={size}"
|
||||
f"Fetching CORDIS EU projects for institution_id={projects_filtering_properties.raw_oa_institution_id}, page={projects_filtering_properties.page}, size={projects_filtering_properties.size}"
|
||||
)
|
||||
institution_aliases = (
|
||||
await institutions_search_client.get_institution_aliases_by_id(institution_id)
|
||||
institutions_search_client.get_institution_aliases_by_oa_institution_id(
|
||||
projects_filtering_properties.raw_oa_institution_id
|
||||
)
|
||||
)
|
||||
logger.debug(
|
||||
f"Found institution aliases for institution_id={institution_id}: {institution_aliases}"
|
||||
)
|
||||
response = await eu_search_client.search_eu_projects(
|
||||
page=page,
|
||||
size=size,
|
||||
institution_names=institution_aliases,
|
||||
topic=topic,
|
||||
sort_by=sort_by,
|
||||
sort_direction=sort_direction,
|
||||
)
|
||||
logger.debug(f"get_eu_projects_by_institution_id response: {response}")
|
||||
return response
|
||||
|
||||
|
||||
async def get_bund_projects_by_institution_name(
|
||||
bund_search_client: BundProjectsSearchClient,
|
||||
page: int,
|
||||
size: int,
|
||||
institution_names: List[str] = [],
|
||||
sort_by: str = "topic",
|
||||
sort_direction: str = "asc",
|
||||
) -> BundProjectPage:
|
||||
logger.info(
|
||||
f"Fetching bund projects for institution_names={institution_names}, page={page}, size={size}"
|
||||
)
|
||||
response = await bund_search_client.search_bund_projects(
|
||||
page=page,
|
||||
size=size,
|
||||
institution_names=institution_names,
|
||||
sort_by=sort_by,
|
||||
sort_direction=sort_direction,
|
||||
f"Found institution aliases for institution_id={projects_filtering_properties.raw_oa_institution_id}: {institution_aliases}"
|
||||
)
|
||||
|
||||
logger.debug(f"get_bund_projects_by_institution_name response: {response}")
|
||||
page = get_eu_organization_project_contributions(
|
||||
organization_names=institution_aliases,
|
||||
projects_filtering_properties=projects_filtering_properties,
|
||||
)
|
||||
|
||||
return response
|
||||
logger.debug(f"get_cordis_eu_projects_by_institution_id response: {page}")
|
||||
|
||||
return page
|
||||
|
||||
|
||||
async def get_dfg_projects_by_author_id(
|
||||
dfg_search_client: DfgProjectsSearchClient,
|
||||
author_id: str,
|
||||
topic: Optional[str],
|
||||
page: int,
|
||||
@@ -122,7 +162,7 @@ async def get_dfg_projects_by_author_id(
|
||||
)
|
||||
logger.debug(f"Found author name for author_id={author_id}: {name}")
|
||||
|
||||
response = await dfg_search_client.search_dfg_projects(
|
||||
response = projects_search_client.search_dfg_projects(
|
||||
page=page,
|
||||
size=size,
|
||||
names=[name],
|
||||
@@ -131,3 +171,179 @@ async def get_dfg_projects_by_author_id(
|
||||
sort_direction=sort_direction,
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
async def get_institution_cordis_eu_projects_funding_over_time(
|
||||
institutions_search_client: InstitutionsSearchClient,
|
||||
raw_oa_institution_id: str,
|
||||
) -> InstitutionFunderSummary:
|
||||
institution_aliases = (
|
||||
institutions_search_client.get_institution_aliases_by_oa_institution_id(
|
||||
raw_oa_institution_id
|
||||
)
|
||||
)
|
||||
page = get_eu_organization_project_contributions(
|
||||
organization_names=institution_aliases,
|
||||
projects_filtering_properties=ProjectsFilteringProperties(
|
||||
project_type=ProjectType.EU,
|
||||
page=0,
|
||||
size=10000,
|
||||
),
|
||||
)
|
||||
|
||||
return _calculate_funding_over_time(
|
||||
project_type=ProjectType.EU,
|
||||
projects=page.elements,
|
||||
funding_start_attr="start_date",
|
||||
funding_end_attr="end_date",
|
||||
funding_amount_attr="ec_contribution",
|
||||
)
|
||||
|
||||
|
||||
def get_institution_bund_projects_funding_over_time(
|
||||
institutions_search_client: InstitutionsSearchClient,
|
||||
raw_oa_institution_id: str,
|
||||
) -> InstitutionFunderSummary:
|
||||
logger.info(
|
||||
f"Fetching funding over time for institution_id={raw_oa_institution_id}"
|
||||
)
|
||||
institution_aliases = (
|
||||
institutions_search_client.get_institution_aliases_by_oa_institution_id(
|
||||
raw_oa_institution_id
|
||||
)
|
||||
)
|
||||
logger.debug(
|
||||
f"Found institution aliases for institution_id={raw_oa_institution_id}: {institution_aliases}"
|
||||
)
|
||||
response = projects_search_client.search_bund_projects(
|
||||
filter_properties=ProjectsFilteringProperties(
|
||||
project_type=ProjectType.BUND,
|
||||
page=0,
|
||||
size=10000,
|
||||
),
|
||||
institution_names=institution_aliases,
|
||||
)
|
||||
|
||||
return _calculate_funding_over_time(
|
||||
project_type=ProjectType.BUND,
|
||||
projects=response.elements,
|
||||
funding_start_attr="funding_start",
|
||||
funding_end_attr="funding_end",
|
||||
funding_amount_attr="grant_amount",
|
||||
)
|
||||
|
||||
|
||||
def _calculate_funding_over_time(
|
||||
project_type: ProjectType,
|
||||
projects: List[Any],
|
||||
funding_start_attr: str,
|
||||
funding_end_attr: str,
|
||||
funding_amount_attr: str,
|
||||
) -> InstitutionFunderSummary:
|
||||
funding_per_year: Dict[int, float] = {}
|
||||
|
||||
for project in projects:
|
||||
funding_start = getattr(project, funding_start_attr)
|
||||
funding_end = getattr(project, funding_end_attr)
|
||||
funding_amount = getattr(project, funding_amount_attr)
|
||||
if not funding_start or not funding_end or not funding_amount:
|
||||
continue
|
||||
|
||||
if hasattr(funding_start, "date"):
|
||||
funding_start = funding_start.date()
|
||||
if hasattr(funding_end, "date"):
|
||||
funding_end = funding_end.date()
|
||||
|
||||
delta = (funding_end - funding_start).days + 1
|
||||
if delta <= 0:
|
||||
continue
|
||||
|
||||
amount_per_day = funding_amount / delta
|
||||
start_year = funding_start.year
|
||||
end_year = funding_end.year
|
||||
|
||||
for year in range(start_year, end_year + 1):
|
||||
if year == start_year:
|
||||
year_start = funding_start
|
||||
else:
|
||||
year_start = datetime.date(year, 1, 1)
|
||||
|
||||
if year == end_year:
|
||||
year_end = funding_end
|
||||
else:
|
||||
year_end = datetime.date(year, 12, 31)
|
||||
|
||||
days_in_year = (year_end - year_start).days + 1
|
||||
proportional_share = days_in_year * amount_per_day
|
||||
|
||||
funding_per_year[year] = (
|
||||
funding_per_year.get(year, 0.0) + proportional_share
|
||||
)
|
||||
|
||||
sorted_funding_per_year: Dict[int, float] = {}
|
||||
|
||||
if funding_per_year:
|
||||
min_year = min(funding_per_year.keys())
|
||||
max_year = max(funding_per_year.keys())
|
||||
|
||||
for year in range(min_year, max_year + 1):
|
||||
sorted_funding_per_year[year] = funding_per_year.get(year, 0.0)
|
||||
|
||||
total_sum = sum(sorted_funding_per_year.values())
|
||||
annual_average_over_period = total_sum / len(sorted_funding_per_year)
|
||||
else:
|
||||
annual_average_over_period = 0.0
|
||||
|
||||
return InstitutionFunderSummary(
|
||||
type=project_type,
|
||||
funding_per_year=sorted_funding_per_year,
|
||||
annual_average_over_period=annual_average_over_period,
|
||||
)
|
||||
|
||||
|
||||
def get_single_dfg_project(
|
||||
project_id: str,
|
||||
) -> DfgProjectDetails:
|
||||
logger.debug(f"Fetching single DFG project for id={project_id}")
|
||||
|
||||
project = projects_search_client.get_dfg_project_by_id(project_id)
|
||||
if not project:
|
||||
raise NotFoundException(f"DFG project with id {project_id} not found")
|
||||
return project
|
||||
|
||||
|
||||
def get_single_bund_project(
|
||||
project_id: str,
|
||||
) -> BundProjectDetails:
|
||||
logger.debug(f"Fetching single BUND project for id={project_id}")
|
||||
|
||||
project = projects_search_client.get_bund_project_by_id(project_id)
|
||||
if not project:
|
||||
raise NotFoundException(f"BUND project with id {project_id} not found")
|
||||
return project
|
||||
|
||||
|
||||
def search_cordis_eu_projects_for_author_id(
|
||||
raw_oa_author_id: str,
|
||||
) -> CordisEuProjectPage:
|
||||
|
||||
# Direct search not possible -> multi stage search
|
||||
# 1. Exisiting author has publications with DOIs
|
||||
# 2. CORDIS EU projects have associated publications with DOIs
|
||||
# 3. Matching DOIs of author publications with DOIs of CORDIS EU project publications -> projects with associated publications of the author
|
||||
|
||||
dois = get_publication_dois_of_author(raw_oa_author_id=raw_oa_author_id)
|
||||
|
||||
logger.debug(f"Found DOIs for author_id={raw_oa_author_id}: {dois}")
|
||||
|
||||
project_ids = projects_search_client.get_cordis_eu_project_ids_by_dois(dois=dois)
|
||||
|
||||
logger.debug(
|
||||
f"Found project IDs {project_ids} for author_id={raw_oa_author_id} and dois={dois}"
|
||||
)
|
||||
|
||||
funding_project_page = projects_search_client.get_cordis_eu_projects_by_project_ids(
|
||||
project_ids=project_ids
|
||||
)
|
||||
|
||||
return funding_project_page
|
||||
|
||||
@@ -7,4 +7,5 @@ class Tags(Enum):
|
||||
INSTITUTIONS = "Institutions"
|
||||
TOPICS = "Topics"
|
||||
WORKS = "Works"
|
||||
NEWS = "News"
|
||||
PROJECTS = "Projects"
|
||||
|
||||
@@ -6,7 +6,7 @@ Business logic for publication works.
|
||||
|
||||
import logging
|
||||
from time import time
|
||||
from typing import List
|
||||
from typing import Any, List
|
||||
|
||||
import httpx
|
||||
from fastapi import HTTPException
|
||||
@@ -328,6 +328,30 @@ async def get_topics_by_time_by_author(
|
||||
target_publications: int = 300,
|
||||
include_all: bool = False,
|
||||
client: OpenAlexWorksSearchClient | None = None,
|
||||
) -> TopicsByTime:
|
||||
if client is not None:
|
||||
return await _get_topics_by_time_by_author_from_work_pages(
|
||||
author_id,
|
||||
max_topics_per_year=max_topics_per_year,
|
||||
target_publications=target_publications,
|
||||
include_all=include_all,
|
||||
client=client,
|
||||
)
|
||||
|
||||
return _get_topics_by_time_by_author_from_es(
|
||||
author_id,
|
||||
max_topics_per_year=max_topics_per_year,
|
||||
target_publications=target_publications,
|
||||
include_all=include_all,
|
||||
)
|
||||
|
||||
|
||||
async def _get_topics_by_time_by_author_from_work_pages(
|
||||
author_id: str,
|
||||
max_topics_per_year: int = 3,
|
||||
target_publications: int = 300,
|
||||
include_all: bool = False,
|
||||
client: OpenAlexWorksSearchClient | None = None,
|
||||
) -> TopicsByTime:
|
||||
if include_all:
|
||||
works = await get_all_author_works(author_id, client=client)
|
||||
@@ -459,6 +483,297 @@ async def get_topics_by_time_by_author(
|
||||
)
|
||||
|
||||
|
||||
def _get_topics_by_time_by_author_from_es(
|
||||
author_id: str,
|
||||
max_topics_per_year: int = 3,
|
||||
target_publications: int = 300,
|
||||
include_all: bool = False,
|
||||
) -> TopicsByTime:
|
||||
year_buckets, total_publications = _get_publication_year_counts_from_es(author_id)
|
||||
selected_years, is_limited = _select_complete_timeline_years(
|
||||
year_buckets,
|
||||
target_publications=target_publications,
|
||||
include_all=include_all,
|
||||
)
|
||||
|
||||
if not selected_years:
|
||||
return TopicsByTime(
|
||||
elements=[],
|
||||
total=0,
|
||||
is_limited=False,
|
||||
used_publications=0,
|
||||
total_publications=total_publications,
|
||||
)
|
||||
|
||||
year_topic_buckets = _get_timeline_topic_counts_from_es(
|
||||
author_id,
|
||||
years=selected_years,
|
||||
max_topics_per_year=max_topics_per_year,
|
||||
)
|
||||
topic_ids = _collect_topic_ids_from_year_buckets(year_topic_buckets)
|
||||
topic_details = _get_topic_details(list(topic_ids))
|
||||
|
||||
elements = _build_timeline_elements_from_aggregations(
|
||||
year_topic_buckets,
|
||||
topic_details=topic_details,
|
||||
max_topics_per_year=max_topics_per_year,
|
||||
)
|
||||
|
||||
return TopicsByTime(
|
||||
elements=elements,
|
||||
total=len(elements),
|
||||
is_limited=is_limited,
|
||||
used_publications=sum(element.publication_count for element in elements),
|
||||
total_publications=total_publications,
|
||||
)
|
||||
|
||||
|
||||
def _get_publication_year_counts_from_es(author_id: str) -> tuple[list[dict], int]:
|
||||
body = {
|
||||
"size": 0,
|
||||
"track_total_hits": True,
|
||||
"query": _author_works_query(author_id),
|
||||
"aggs": {
|
||||
"publication_years": {
|
||||
"terms": {
|
||||
"field": "publication_year",
|
||||
"size": 300,
|
||||
"order": {"_key": "desc"},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
index=config.settings.openalex_works_search_index,
|
||||
body=body,
|
||||
)
|
||||
except httpx.HTTPError as exc:
|
||||
logger.exception("OpenAlex publication year aggregation request failed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex works search request failed.",
|
||||
) from exc
|
||||
|
||||
return _parse_year_count_buckets(response), _parse_total_hits(response)
|
||||
|
||||
|
||||
def _get_timeline_topic_counts_from_es(
|
||||
author_id: str,
|
||||
years: list[int],
|
||||
max_topics_per_year: int,
|
||||
) -> list[dict]:
|
||||
body = {
|
||||
"size": 0,
|
||||
"query": {
|
||||
"bool": {
|
||||
"must": [_author_works_query(author_id)],
|
||||
"filter": [{"terms": {"publication_year": years}}],
|
||||
},
|
||||
},
|
||||
"aggs": {
|
||||
"by_year": {
|
||||
"terms": {
|
||||
"field": "publication_year",
|
||||
"size": len(years),
|
||||
"order": {"_key": "asc"},
|
||||
},
|
||||
"aggs": {
|
||||
"primary_topics": {
|
||||
"terms": {
|
||||
"field": "primary_topic.id",
|
||||
"size": max_topics_per_year,
|
||||
"order": [
|
||||
{"_count": "desc"},
|
||||
{"_key": "asc"},
|
||||
],
|
||||
},
|
||||
},
|
||||
"topics_nested": {
|
||||
"nested": {"path": "topics"},
|
||||
"aggs": {
|
||||
"topics": {
|
||||
"terms": {
|
||||
"field": "topics.id",
|
||||
"size": max_topics_per_year,
|
||||
"order": [
|
||||
{"_count": "desc"},
|
||||
{"_key": "asc"},
|
||||
],
|
||||
},
|
||||
"aggs": {
|
||||
"works": {
|
||||
"reverse_nested": {},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
index=config.settings.openalex_works_search_index,
|
||||
body=body,
|
||||
)
|
||||
except httpx.HTTPError as exc:
|
||||
logger.exception("OpenAlex timeline topic aggregation request failed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex works search request failed.",
|
||||
) from exc
|
||||
|
||||
return response.get("aggregations", {}).get("by_year", {}).get("buckets", [])
|
||||
|
||||
|
||||
def _author_works_query(author_id: str) -> dict[str, Any]:
|
||||
indexed_author_id = f"https://openalex.org/{author_id.strip()}"
|
||||
|
||||
return {
|
||||
"nested": {
|
||||
"path": "authorships",
|
||||
"query": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{"term": {"authorships.author.id": indexed_author_id}},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _parse_year_count_buckets(response: dict) -> list[dict]:
|
||||
return (
|
||||
response.get("aggregations", {}).get("publication_years", {}).get("buckets", [])
|
||||
)
|
||||
|
||||
|
||||
def _parse_total_hits(response: dict) -> int:
|
||||
total = response.get("hits", {}).get("total", 0)
|
||||
|
||||
if isinstance(total, dict):
|
||||
return total.get("value", 0)
|
||||
|
||||
return total
|
||||
|
||||
|
||||
def _select_complete_timeline_years(
|
||||
year_buckets: list[dict],
|
||||
target_publications: int,
|
||||
include_all: bool,
|
||||
) -> tuple[list[int], bool]:
|
||||
if include_all:
|
||||
return [bucket["key"] for bucket in year_buckets], False
|
||||
|
||||
selected_years: list[int] = []
|
||||
selected_publications = 0
|
||||
|
||||
for bucket in year_buckets:
|
||||
selected_years.append(bucket["key"])
|
||||
selected_publications += bucket.get("doc_count", 0)
|
||||
|
||||
if selected_publications >= target_publications:
|
||||
break
|
||||
|
||||
is_limited = len(selected_years) < len(year_buckets)
|
||||
|
||||
return selected_years, is_limited
|
||||
|
||||
|
||||
def _collect_topic_ids_from_year_buckets(year_buckets: list[dict]) -> set[str]:
|
||||
topic_ids: set[str] = set()
|
||||
|
||||
for year_bucket in year_buckets:
|
||||
primary_buckets = year_bucket.get("primary_topics", {}).get("buckets", [])
|
||||
topic_buckets = (
|
||||
year_bucket.get("topics_nested", {}).get("topics", {}).get("buckets", [])
|
||||
)
|
||||
|
||||
for bucket in primary_buckets + topic_buckets:
|
||||
topic_id = bucket.get("key")
|
||||
|
||||
if topic_id:
|
||||
topic_ids.add(topic_id)
|
||||
|
||||
return topic_ids
|
||||
|
||||
|
||||
def _build_timeline_elements_from_aggregations(
|
||||
year_buckets: list[dict],
|
||||
topic_details: dict[str, dict],
|
||||
max_topics_per_year: int,
|
||||
) -> list[TopicsByYear]:
|
||||
elements: list[TopicsByYear] = []
|
||||
|
||||
for year_bucket in year_buckets:
|
||||
year = year_bucket.get("key")
|
||||
|
||||
if year is None:
|
||||
continue
|
||||
|
||||
topics = _build_topic_counts_from_buckets(
|
||||
year_bucket.get("topics_nested", {}).get("topics", {}).get("buckets", []),
|
||||
topic_details=topic_details,
|
||||
max_topics_per_year=max_topics_per_year,
|
||||
use_reverse_nested_count=True,
|
||||
)
|
||||
primary_topics = _build_topic_counts_from_buckets(
|
||||
year_bucket.get("primary_topics", {}).get("buckets", []),
|
||||
topic_details=topic_details,
|
||||
max_topics_per_year=max_topics_per_year,
|
||||
use_reverse_nested_count=False,
|
||||
)
|
||||
|
||||
elements.append(
|
||||
TopicsByYear(
|
||||
year=year,
|
||||
publication_count=year_bucket.get("doc_count", 0),
|
||||
topics=topics,
|
||||
primary_topics=primary_topics,
|
||||
)
|
||||
)
|
||||
|
||||
return elements
|
||||
|
||||
|
||||
def _build_topic_counts_from_buckets(
|
||||
buckets: list[dict],
|
||||
topic_details: dict[str, dict],
|
||||
max_topics_per_year: int,
|
||||
use_reverse_nested_count: bool,
|
||||
) -> list[TopicCount]:
|
||||
topics: list[TopicCount] = []
|
||||
|
||||
for bucket in buckets[:max_topics_per_year]:
|
||||
topic_id = bucket.get("key")
|
||||
|
||||
if not topic_id:
|
||||
continue
|
||||
|
||||
info = topic_details.get(topic_id, {})
|
||||
display_name = info.get("display_name") or topic_id
|
||||
count = bucket.get("doc_count", 0)
|
||||
|
||||
if use_reverse_nested_count:
|
||||
count = bucket.get("works", {}).get("doc_count", count)
|
||||
|
||||
topics.append(
|
||||
TopicCount(
|
||||
id=topic_id,
|
||||
name=display_name,
|
||||
count=count,
|
||||
description=info.get("description"),
|
||||
)
|
||||
)
|
||||
|
||||
return topics
|
||||
|
||||
|
||||
async def _search_author_works_data(
|
||||
search_client: OpenAlexWorksSearchClient,
|
||||
author_id: str,
|
||||
@@ -539,3 +854,49 @@ def _parse_full_work_search_response(data: dict) -> tuple[list[Work], int]:
|
||||
) from exc
|
||||
|
||||
return elements, total
|
||||
|
||||
|
||||
def get_publication_dois_of_author(
|
||||
raw_oa_author_id: str,
|
||||
) -> List[str]:
|
||||
query = {
|
||||
"bool": {
|
||||
"must": [
|
||||
{
|
||||
"nested": {
|
||||
"path": "authorships",
|
||||
"query": {
|
||||
"term": {
|
||||
"authorships.author.id": f"https://openalex.org/{raw_oa_author_id.strip().upper()}"
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
],
|
||||
"filter": [{"exists": {"field": "doi"}}],
|
||||
}
|
||||
}
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
index="openalex-works",
|
||||
source=["doi"],
|
||||
size=10000,
|
||||
query=query,
|
||||
cluster="nes",
|
||||
)
|
||||
except httpx.HTTPError as exc:
|
||||
logger.exception("Request for publication DOIs of author failed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="Request for publication DOIs of author failed.",
|
||||
) from exc
|
||||
|
||||
dois = []
|
||||
for hit in response.get("hits", {}).get("hits", []):
|
||||
source = hit.get("_source", {})
|
||||
doi = source.get("doi")
|
||||
if doi:
|
||||
dois.append(doi)
|
||||
|
||||
return dois
|
||||
|
||||
@@ -26,12 +26,13 @@ class OpenAlexWorksSearchClient:
|
||||
timeout: float | None = None,
|
||||
transport: httpx.AsyncBaseTransport | None = None,
|
||||
):
|
||||
self.base_url = (base_url or config.settings.openalex_works_search_base_url).rstrip("/")
|
||||
self.base_url = (base_url or config.settings.elasticsearch_url or "").rstrip("/")
|
||||
self.index = index or config.settings.openalex_works_search_index
|
||||
self.api_key = api_key if api_key is not None else config.settings.openalex_works_api_key
|
||||
self.api_key = api_key if api_key is not None else config.settings.elasticsearch_api_key
|
||||
self.timeout = timeout if timeout is not None else config.settings.openalex_works_search_timeout_seconds
|
||||
self.transport = transport
|
||||
|
||||
|
||||
def author_works_query(
|
||||
self,
|
||||
author_id: str,
|
||||
|
||||
+575
-17
@@ -13,10 +13,335 @@ Content-Type: application/json
|
||||
}
|
||||
|
||||
###
|
||||
GET https://inse.nes.uni-due.de/elastic/projects_dfg_all/_search
|
||||
GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_publications/_search
|
||||
Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"size": 100,
|
||||
"query": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{
|
||||
"terms": {
|
||||
"projectID": ["287661"]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
###
|
||||
GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_organizations/_mapping
|
||||
Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
|
||||
Content-Type: application/json
|
||||
|
||||
###
|
||||
GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_projects/_mapping
|
||||
Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
|
||||
Content-Type: application/json
|
||||
|
||||
###
|
||||
GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_projects/_search
|
||||
Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"size": 100,
|
||||
"query": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{
|
||||
"terms": {
|
||||
"id": ["604123", "101003555"]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# 10.1371/journal.pone.0018216
|
||||
|
||||
###
|
||||
GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_publications/_mapping
|
||||
Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
|
||||
Content-Type: application/json
|
||||
|
||||
###
|
||||
GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_publications/_search
|
||||
Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
|
||||
Content-Type: application/json
|
||||
|
||||
###
|
||||
GET https://inse.nes.uni-due.de/elastic/cordis_eu_fp7_project_iprs/_search
|
||||
Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
|
||||
Content-Type: application/json
|
||||
|
||||
###
|
||||
GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_publications/_search
|
||||
Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"query": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{
|
||||
"terms": {
|
||||
"qaProcessedDoi": [
|
||||
"10.5555/3234847.3234861",
|
||||
"10.1145/1858367.1858373",
|
||||
"10.1145/3583120.3586961",
|
||||
"10.1109/ipin.2017.8115906",
|
||||
"10.1145/3274783.3275217",
|
||||
"10.1007/978-3-031-20716-7_7",
|
||||
"10.1109/percomw.2012.6197554",
|
||||
"10.1016/j.pmcj.2012.12.002",
|
||||
"10.1007/978-3-658-32266-3_30",
|
||||
"10.1109/percomw.2013.6529502",
|
||||
"10.1109/ie.2010.40",
|
||||
"10.18419/opus-2650",
|
||||
"10.1007/s00138-024-01553-z",
|
||||
"10.1007/978-3-030-90439-5_15",
|
||||
"10.1201/9781003338659-4",
|
||||
"10.1016/j.pmcj.2013.10.013",
|
||||
"10.1109/percom.2009.4912852",
|
||||
"10.1109/icra55743.2025.11128432",
|
||||
"10.1145/2494091.2497327",
|
||||
"10.1007/978-3-658-46485-1_31",
|
||||
"10.1109/ie.2017.22",
|
||||
"10.1109/jiot.2016.2554146",
|
||||
"10.1145/2493432.2493459",
|
||||
"10.3233/ais-160416",
|
||||
"10.1109/percomw.2007.111",
|
||||
"10.5194/asr-17-183-2020",
|
||||
"10.1007/978-3-658-36430-4_37",
|
||||
"10.1007/978-3-030-64559-5_50"
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
###
|
||||
GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_organizations/_search
|
||||
Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"size": 0,
|
||||
"query": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{
|
||||
"term": {
|
||||
"organisationID": "999843312"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"aggs": {
|
||||
"associated_project_ids": {
|
||||
"terms": {
|
||||
"field": "projectID"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
###
|
||||
GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_organizations/_search
|
||||
Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"size": 1000,
|
||||
"query": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{
|
||||
"term": {
|
||||
"name.keyword": "UNIVERSITAET DUISBURG-ESSEN"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
###
|
||||
GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_organizations/_search
|
||||
Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"size": 0,
|
||||
"query": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{
|
||||
"term": {
|
||||
"name.keyword": "UNIVERSITAET DUISBURG-ESSEN"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"aggs": {
|
||||
"associated_project_ids": {
|
||||
"terms": {
|
||||
"field": "projectID"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
###
|
||||
GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_projects/_mapping
|
||||
Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
|
||||
Content-Type: application/json
|
||||
|
||||
###
|
||||
GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_organizations/_search
|
||||
Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"query": {
|
||||
"terms": {
|
||||
"name": [
|
||||
"UNIVERSITÄT DUISBURG-ESSEN",
|
||||
"UNIVERSITY OF DUISBURG-ESSEN",
|
||||
"UNIVERSITAT DUISBURG-ESSEN",
|
||||
"UNIVERSITY OF DUISBURG ESSEN",
|
||||
"UNIVERSITAT DUISBURG-ESSEN",
|
||||
"UNIVERSITAET DUISBURG ESSEN",
|
||||
"UNIVERSITÄT DUISBURG ESSEN",
|
||||
"UNIVERSITAT DUISBURG ESSEN",
|
||||
"UNIVERSITÄT DUISBURG-ESSEN",
|
||||
"UNIVERSITAET DUISBURG-ESSEN",
|
||||
"UNIVERSITY OF DUISBURG-ESSEN"
|
||||
]
|
||||
}
|
||||
},
|
||||
"_source": ["projectID", "organisationID", "ecContribution"]
|
||||
}
|
||||
|
||||
|
||||
###
|
||||
GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_organizations/_search
|
||||
Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"size": 10,
|
||||
"query": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{
|
||||
"term": {
|
||||
"name.keyword": "UNIVERSITAET DUISBURG-ESSEN"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
###
|
||||
GET https://inse.nes.uni-due.de/elastic/cordis_eu_*_organizations/_search
|
||||
Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"size": 0,
|
||||
"query": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{
|
||||
"terms": {
|
||||
"name.keyword": [
|
||||
"UNIVERSITAET DUISBURG-ESSEN",
|
||||
"UNIVERSITY OF DUISBURG-ESSEN",
|
||||
"UNIVERSITÄT DUISBURG-ESSEN",
|
||||
"UNIVERSITAT DUISBURG ESSEN",
|
||||
"UNIVERSITÄT DUISBURG ESSEN",
|
||||
"UNIVERSITY OF DUISBURG ESSEN",
|
||||
"UNIVERSITAET DUISBURG ESSEN",
|
||||
"UNIVERSITAT DUISBURG-ESSEN"
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"aggs": {
|
||||
"organisation_ids": {
|
||||
"terms": {
|
||||
"field": "organisationID",
|
||||
"size": 10000
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
###
|
||||
GET https://inse.nes.uni-due.de/elastic/cordis_eu_horizon_europe_organizations/_search
|
||||
Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"size": 0,
|
||||
"query": {
|
||||
"match": {
|
||||
"name": {
|
||||
"query": "Essen",
|
||||
"fuzziness": "AUTO"
|
||||
}
|
||||
}
|
||||
},
|
||||
"aggs": {
|
||||
"distinct_matched_names": {
|
||||
"terms": {
|
||||
"field": "name.keyword",
|
||||
"size": 100
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
###
|
||||
GET https://inse.nes.uni-due.de/elastic/cordis_eu_fp7_organizations/_search
|
||||
Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"size": 0,
|
||||
"query": {
|
||||
"match": {
|
||||
"name": {
|
||||
"query": "Essen",
|
||||
"fuzziness": "AUTO"
|
||||
}
|
||||
}
|
||||
},
|
||||
"aggs": {
|
||||
"distinct_matched_names": {
|
||||
"terms": {
|
||||
"field": "name.keyword",
|
||||
"size": 100
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
###
|
||||
GET https://inse.nes.uni-due.de/elastic/projects_dfg_all/_search
|
||||
Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
|
||||
@@ -342,6 +667,42 @@ GET https://inse.nes.uni-due.de/elastic/projects_dfg_all/_search
|
||||
Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"wildcard": {
|
||||
"title.keyword": {
|
||||
"value": "*generic*",
|
||||
"case_insensitive": true
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"wildcard": {
|
||||
"Thema.keyword": {
|
||||
"value": "*generic*",
|
||||
"case_insensitive": true
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
###
|
||||
GET https://inse.nes.uni-due.de/elastic/projects_dfg_all/_mapping
|
||||
Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
|
||||
Content-Type: application/json
|
||||
|
||||
###
|
||||
GET https://inse.nes.uni-due.de/elastic/projects_dfg_all/_search
|
||||
Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"size": 100,
|
||||
"query": {
|
||||
@@ -451,37 +812,157 @@ Content-Type: application/json
|
||||
|
||||
|
||||
###
|
||||
GET https://inse.nes.uni-due.de/elastic/projects_bund/_mapping
|
||||
GET https://inse.nes.uni-due.de/elastic/projects_bund_v1/_mapping
|
||||
Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
|
||||
Content-Type: application/json
|
||||
|
||||
###
|
||||
GET https://inse.nes.uni-due.de/elastic/projects_bund/_search
|
||||
GET https://inse.nes.uni-due.de/elastic/projects_bund_v1/_search
|
||||
Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
|
||||
"size": 10,
|
||||
"from": 1000,
|
||||
"size": 0,
|
||||
"query": {
|
||||
"match": {
|
||||
"Zuwendungsempf\u00e4nger": {
|
||||
"query": "Universit\u00e4t Duisburg-Essen",
|
||||
"operator": "and"
|
||||
}
|
||||
"bool": {
|
||||
"must": [
|
||||
{
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"match": {
|
||||
"Zuwendungsempfänger": {
|
||||
"query": "university of duisburg-eßen",
|
||||
"operator": "and"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"match": {
|
||||
"Zuwendungsempfänger": {
|
||||
"query": "university of duisburg-essen",
|
||||
"operator": "and"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"match": {
|
||||
"Zuwendungsempfänger": {
|
||||
"query": "universitaet duisburg-essen",
|
||||
"operator": "and"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"match": {
|
||||
"Zuwendungsempfänger": {
|
||||
"query": "universitaet duisburg essen",
|
||||
"operator": "and"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"match": {
|
||||
"Zuwendungsempfänger": {
|
||||
"query": "universität duisburg-essen",
|
||||
"operator": "and"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"match": {
|
||||
"Zuwendungsempfänger": {
|
||||
"query": "universitat duisburg-eßen",
|
||||
"operator": "and"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"match": {
|
||||
"Zuwendungsempfänger": {
|
||||
"query": "universitat duisburg essen",
|
||||
"operator": "and"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"match": {
|
||||
"Zuwendungsempfänger": {
|
||||
"query": "university of duisburg essen",
|
||||
"operator": "and"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"match": {
|
||||
"Zuwendungsempfänger": {
|
||||
"query": "universitat duisburg-essen",
|
||||
"operator": "and"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"match": {
|
||||
"Zuwendungsempfänger": {
|
||||
"query": "universität duisburg-eßen",
|
||||
"operator": "and"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"match": {
|
||||
"Zuwendungsempfänger": {
|
||||
"query": "universität duisburg essen",
|
||||
"operator": "and"
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"minimum_should_match": 1
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"sort": [
|
||||
{
|
||||
"Thema.keyword": {
|
||||
"order": "asc"
|
||||
"aggs": {
|
||||
"distributed_annual_amounts": {
|
||||
"scripted_metric": {
|
||||
"init_script": "state.years_map = [:]",
|
||||
"map_script": "if (doc['funding_start'].size() == 0 || doc['funding_end'].size() == 0 || doc['Fördersumme'].size() == 0) { return; } def start = doc['funding_start'].value.toLocalDate(); def end = doc['funding_end'].value.toLocalDate(); def totalAmount = doc['Fördersumme'].value; def startYear = start.getYear(); def endYear = end.getYear(); if (startYear == endYear) { state.years_map[startYear] = state.years_map.getOrDefault(startYear, 0.0) + totalAmount; } else { long totalDays = ChronoUnit.DAYS.between(start, end) + 1; if (totalDays <= 0) return; double amountPerDay = totalAmount / (double)totalDays; for (int y = startYear; y <= endYear; y++) { def yearStart = (y == startYear) ? start : LocalDate.of(y, 1, 1); def yearEnd = (y == endYear) ? end : LocalDate.of(y, 12, 31); long daysInYear = ChronoUnit.DAYS.between(yearStart, yearEnd) + 1; double proportionalShare = daysInYear * amountPerDay; state.years_map[y] = state.years_map.getOrDefault(y, 0.0) + proportionalShare; } }",
|
||||
"combine_script": "return state.years_map",
|
||||
"reduce_script": "def final_map = [:]; for (state in states) { for (entry in state.entrySet()) { final_map[entry.getKey()] = final_map.getOrDefault(entry.getKey(), 0.0) + entry.getValue(); } } if (final_map.isEmpty()) { return ['funding_per_year': final_map, 'annual_average_over_period': 0.0]; } double totalSum = 0.0; for (val in final_map.values()) { totalSum += val; } double avg = totalSum / final_map.size(); return ['funding_per_year': final_map, 'annual_average_over_period': avg];"
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
###
|
||||
|
||||
# {
|
||||
|
||||
# "size": 10,
|
||||
# "from": 1000,
|
||||
# "query": {
|
||||
# "match": {
|
||||
# "Zuwendungsempf\u00e4nger": {
|
||||
# "query": "Universit\u00e4t Duisburg-Essen",
|
||||
# "operator": "and"
|
||||
# }
|
||||
# }
|
||||
# },
|
||||
# "sort": [
|
||||
# {
|
||||
# "Thema.keyword": {
|
||||
# "order": "asc"
|
||||
# }
|
||||
# }
|
||||
# ]
|
||||
|
||||
# }
|
||||
|
||||
#{'size': 10, 'from': 0, 'query': {'match': {'Zuwendungsempfänger': {'query': 'Universität Duisburg-Essen', 'operator': 'and'}}}, 'sort': [{'Thema': {'order': 'asc'}}]}
|
||||
|
||||
# {
|
||||
@@ -688,6 +1169,69 @@ GET https://project.nes.uni-due.de/elastic/openalex-authors/_search
|
||||
Authorization: ApiKey am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ==
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"query": {
|
||||
"bool": {
|
||||
"must": [
|
||||
{
|
||||
"prefix": {
|
||||
"display_name.keyword": "Marcus Roth"
|
||||
}
|
||||
},
|
||||
{
|
||||
"nested": {
|
||||
"path": "last_known_institutions",
|
||||
"query": {
|
||||
"match": {
|
||||
"last_known_institutions.display_name": "University of Duisburg-Essen"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
###
|
||||
|
||||
GET https://project.nes.uni-due.de/elastic/openalex-works/_search
|
||||
Authorization: ApiKey am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ==
|
||||
Content-Type: application/json
|
||||
|
||||
###
|
||||
|
||||
GET https://project.nes.uni-due.de/elastic/openalex-works/_search
|
||||
Authorization: ApiKey am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ==
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"_source": ["title", "doi"],
|
||||
"size": 100,
|
||||
"query": {
|
||||
"bool": {
|
||||
"must": [
|
||||
{
|
||||
"nested": {
|
||||
"path": "authorships",
|
||||
"query": {
|
||||
"term": {
|
||||
"authorships.author.id": "https://openalex.org/A5007170803"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"filter": [
|
||||
{
|
||||
"exists": {
|
||||
"field": "doi"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
###
|
||||
|
||||
@@ -783,6 +1327,20 @@ GET https://project.nes.uni-due.de/elastic/openalex-authors/_mapping
|
||||
Authorization: ApiKey am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ==
|
||||
Content-Type: application/json
|
||||
|
||||
###
|
||||
|
||||
GET https://project.nes.uni-due.de/elastic/openalex-institutions/_search
|
||||
Authorization: ApiKey am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ==
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"query": {},
|
||||
"size": 10,
|
||||
"from": 0,
|
||||
"sort": [{ "works_count": { "order": "desc" } }]
|
||||
}
|
||||
|
||||
|
||||
###
|
||||
|
||||
GET https://project.nes.uni-due.de/elastic/openalex-awards/_search
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
.gitignore
|
||||
.openapi-generator-ignore
|
||||
README.md
|
||||
api.base.service.ts
|
||||
api.module.ts
|
||||
api/api.ts
|
||||
api/companyConnections.service.ts
|
||||
api/funding.service.ts
|
||||
api/iNSEAccountService.service.ts
|
||||
api/iNSEService.service.ts
|
||||
api/institutions.service.ts
|
||||
api/items.service.ts
|
||||
api/news.service.ts
|
||||
api/patents.service.ts
|
||||
api/personNetwork.service.ts
|
||||
api/persons.service.ts
|
||||
api/projects.service.ts
|
||||
@@ -37,11 +41,16 @@ model/autocompleteResponseResultsInner.ts
|
||||
model/award.ts
|
||||
model/bodyCreateUser.ts
|
||||
model/bundProject.ts
|
||||
model/bundProjectDetails.ts
|
||||
model/bundProjectPage.ts
|
||||
model/categoryNested.ts
|
||||
model/careerMetrics.ts
|
||||
model/collaborationNetwork.ts
|
||||
model/collaborationNetworkEdge.ts
|
||||
model/collaborationNetworkNodeType.ts
|
||||
model/companyConnection.ts
|
||||
model/companyConnectionsResponse.ts
|
||||
model/cordisEuProject.ts
|
||||
model/cordisEuProjectPage.ts
|
||||
model/costUsd.ts
|
||||
model/customAuthor.ts
|
||||
model/customAuthorsListResponse.ts
|
||||
@@ -49,50 +58,64 @@ model/dehydratedAuthor.ts
|
||||
model/dehydratedFunder.ts
|
||||
model/dehydratedInstitution.ts
|
||||
model/dehydratedSource.ts
|
||||
model/dfgProjectDetails.ts
|
||||
model/dfgProjectPage.ts
|
||||
model/dfgProjectSummary.ts
|
||||
model/displayCodeSplittedNested.ts
|
||||
model/euProject.ts
|
||||
model/euProjectPage.ts
|
||||
model/euOrganizationProjectSummary.ts
|
||||
model/euOrganizationProjectSummaryPage.ts
|
||||
model/filterInformation.ts
|
||||
model/filterProperties.ts
|
||||
model/funderByAuthor.ts
|
||||
model/fundersByAuthorResponse.ts
|
||||
model/fundingProject.ts
|
||||
model/fundingProjectPage.ts
|
||||
model/fwci.ts
|
||||
model/groupByResult.ts
|
||||
model/hTTPValidationError.ts
|
||||
model/identityGrant.ts
|
||||
model/institution.ts
|
||||
model/institutionFunderSummary.ts
|
||||
model/institutionGeo.ts
|
||||
model/institutionIds.ts
|
||||
model/institutionInformation.ts
|
||||
model/institutionNetworkNode.ts
|
||||
model/institutionPage.ts
|
||||
model/institutionsListResponse.ts
|
||||
model/item.ts
|
||||
model/itemCreate.ts
|
||||
model/itemPage.ts
|
||||
model/keywordNested.ts
|
||||
model/keywords.ts
|
||||
model/latitude.ts
|
||||
model/location.ts
|
||||
model/longitude.ts
|
||||
model/matchedOfficer.ts
|
||||
model/mentionedPerson.ts
|
||||
model/meta.ts
|
||||
model/model2YrMeanCitedness.ts
|
||||
model/models.ts
|
||||
model/newsArticle.ts
|
||||
model/newsArticleDetail.ts
|
||||
model/newsPage.ts
|
||||
model/openAccess.ts
|
||||
model/organizationNested.ts
|
||||
model/patentEntry.ts
|
||||
model/patentsByAuthorResponse.ts
|
||||
model/personBio.ts
|
||||
model/programmeNested.ts
|
||||
model/projectType.ts
|
||||
model/projectsFilteringProperties.ts
|
||||
model/projectsSortBy.ts
|
||||
model/publicationDetailByFunder.ts
|
||||
model/publicationIdsByAuthorPosition.ts
|
||||
model/publicationsByAuthorResponse.ts
|
||||
model/rankingResponse.ts
|
||||
model/score.ts
|
||||
model/sortDirection.ts
|
||||
model/topic.ts
|
||||
model/topicCount.ts
|
||||
model/topicDomain.ts
|
||||
model/topicField.ts
|
||||
model/topicIds.ts
|
||||
model/topicSubfield.ts
|
||||
model/topics.ts
|
||||
model/topicsByTime.ts
|
||||
model/topicsByYear.ts
|
||||
model/topicsListResponse.ts
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
export * from './companyConnections.service';
|
||||
import { CompanyConnectionsService } from './companyConnections.service';
|
||||
export * from './funding.service';
|
||||
import { FundingService } from './funding.service';
|
||||
export * from './iNSEAccountService.service';
|
||||
@@ -8,6 +10,10 @@ export * from './institutions.service';
|
||||
import { InstitutionsService } from './institutions.service';
|
||||
export * from './items.service';
|
||||
import { ItemsService } from './items.service';
|
||||
export * from './news.service';
|
||||
import { NewsService } from './news.service';
|
||||
export * from './patents.service';
|
||||
import { PatentsService } from './patents.service';
|
||||
export * from './personNetwork.service';
|
||||
import { PersonNetworkService } from './personNetwork.service';
|
||||
export * from './persons.service';
|
||||
@@ -18,4 +24,4 @@ export * from './topics.service';
|
||||
import { TopicsService } from './topics.service';
|
||||
export * from './works.service';
|
||||
import { WorksService } from './works.service';
|
||||
export const APIS = [FundingService, INSEAccountServiceService, INSEServiceService, InstitutionsService, ItemsService, PersonNetworkService, PersonsService, ProjectsService, TopicsService, WorksService];
|
||||
export const APIS = [CompanyConnectionsService, FundingService, INSEAccountServiceService, INSEServiceService, InstitutionsService, ItemsService, NewsService, PatentsService, PersonNetworkService, PersonsService, ProjectsService, TopicsService, WorksService];
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
/* tslint:disable:no-unused-variable member-ordering */
|
||||
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import { HttpClient, HttpHeaders, HttpParams,
|
||||
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
// @ts-ignore
|
||||
import { CompanyConnectionsResponse } from '../model/companyConnectionsResponse';
|
||||
// @ts-ignore
|
||||
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||
|
||||
// @ts-ignore
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BaseService } from '../api.base.service';
|
||||
|
||||
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class CompanyConnectionsService extends BaseService {
|
||||
|
||||
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
|
||||
super(basePath, configuration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get possible company connections by OpenAlex author ID.
|
||||
* @endpoint get /api/inse-service/authors/{author_id}/company-connections
|
||||
* @param authorId
|
||||
* @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 getCompanyConnectionsByAuthor(authorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<CompanyConnectionsResponse>;
|
||||
public getCompanyConnectionsByAuthor(authorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<CompanyConnectionsResponse>>;
|
||||
public getCompanyConnectionsByAuthor(authorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<CompanyConnectionsResponse>>;
|
||||
public getCompanyConnectionsByAuthor(authorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (authorId === null || authorId === undefined) {
|
||||
throw new Error('Required parameter authorId was null or undefined when calling getCompanyConnectionsByAuthor.');
|
||||
}
|
||||
|
||||
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/authors/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/company-connections`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<CompanyConnectionsResponse>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -23,6 +23,8 @@ import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||
// @ts-ignore
|
||||
import { Institution } from '../model/institution';
|
||||
// @ts-ignore
|
||||
import { InstitutionPage } from '../model/institutionPage';
|
||||
// @ts-ignore
|
||||
import { InstitutionsListResponse } from '../model/institutionsListResponse';
|
||||
// @ts-ignore
|
||||
import { RankingResponse } from '../model/rankingResponse';
|
||||
@@ -312,4 +314,74 @@ export class InstitutionsService extends BaseService {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Searches for institutions by name.
|
||||
* Searches for institutions by name with pagination.
|
||||
* @endpoint get /api/inse-service/institutions/search
|
||||
* @param name Institution name to search for, for example \'University of Duisburg Essen\'.
|
||||
* @param page Page number (0-indexed).
|
||||
* @param size Number of institutions per page.
|
||||
* @param sortBy Field to sort by, either \'relevance\', \'name\', \'works_count\', or \'citations_count\'.
|
||||
* @param sortingDirection Sorting direction, either \'asc\' or \'desc\'.
|
||||
* @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 searchInstitutionsByName(name?: string, page?: number, size?: number, sortBy?: 'relevance' | 'name' | 'works_count' | 'citations_count', sortingDirection?: 'asc' | 'desc', observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<InstitutionPage>;
|
||||
public searchInstitutionsByName(name?: string, page?: number, size?: number, sortBy?: 'relevance' | 'name' | 'works_count' | 'citations_count', sortingDirection?: 'asc' | 'desc', observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<InstitutionPage>>;
|
||||
public searchInstitutionsByName(name?: string, page?: number, size?: number, sortBy?: 'relevance' | 'name' | 'works_count' | 'citations_count', sortingDirection?: 'asc' | 'desc', observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<InstitutionPage>>;
|
||||
public searchInstitutionsByName(name?: string, page?: number, size?: number, sortBy?: 'relevance' | 'name' | 'works_count' | 'citations_count', sortingDirection?: 'asc' | 'desc', 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>name, 'name');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>page, 'page');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>size, 'size');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>sortBy, 'sort_by');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>sortingDirection, 'sorting_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/institutions/search`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<InstitutionPage>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,554 @@
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
/* tslint:disable:no-unused-variable member-ordering */
|
||||
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import { HttpClient, HttpHeaders, HttpParams,
|
||||
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
// @ts-ignore
|
||||
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||
// @ts-ignore
|
||||
import { NewsArticleDetail } from '../model/newsArticleDetail';
|
||||
// @ts-ignore
|
||||
import { NewsPage } from '../model/newsPage';
|
||||
|
||||
// @ts-ignore
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BaseService } from '../api.base.service';
|
||||
|
||||
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class NewsService extends BaseService {
|
||||
|
||||
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
|
||||
super(basePath, configuration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns news articles in which the given person is mentioned.
|
||||
* @endpoint get /api/news/by-author
|
||||
* @param authorId OpenAlex author id, e.g. A5034365278.
|
||||
* @param page Page number (1-based).
|
||||
* @param pageSize Articles per page.
|
||||
* @param sortOrder Sort order: \'desc\' (newest first) or \'asc\' (oldest first).
|
||||
* @param query Optional search term, matched against title/author.
|
||||
* @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 getNewsByAuthor(authorId: string, page?: number, pageSize?: number, sortOrder?: string, query?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<NewsPage>;
|
||||
public getNewsByAuthor(authorId: string, page?: number, pageSize?: number, sortOrder?: string, query?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<NewsPage>>;
|
||||
public getNewsByAuthor(authorId: string, page?: number, pageSize?: number, sortOrder?: string, query?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<NewsPage>>;
|
||||
public getNewsByAuthor(authorId: string, page?: number, pageSize?: number, sortOrder?: string, query?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (authorId === null || authorId === undefined) {
|
||||
throw new Error('Required parameter authorId was null or undefined when calling getNewsByAuthor.');
|
||||
}
|
||||
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>authorId, 'authorId');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>page, 'page');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>pageSize, 'pageSize');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>sortOrder, 'sortOrder');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>query, 'query');
|
||||
|
||||
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/news/by-author`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<NewsPage>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns news articles in which the given person is mentioned.
|
||||
* @endpoint get /api/news/by-author
|
||||
* @param authorId OpenAlex author id, e.g. A5034365278.
|
||||
* @param page Page number (1-based).
|
||||
* @param pageSize Articles per page.
|
||||
* @param sortOrder Sort order: \'desc\' (newest first) or \'asc\' (oldest first).
|
||||
* @param query Optional search term, matched against title/author.
|
||||
* @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 getNewsByAuthor_1(authorId: string, page?: number, pageSize?: number, sortOrder?: string, query?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<NewsPage>;
|
||||
public getNewsByAuthor_1(authorId: string, page?: number, pageSize?: number, sortOrder?: string, query?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<NewsPage>>;
|
||||
public getNewsByAuthor_1(authorId: string, page?: number, pageSize?: number, sortOrder?: string, query?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<NewsPage>>;
|
||||
public getNewsByAuthor_1(authorId: string, page?: number, pageSize?: number, sortOrder?: string, query?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (authorId === null || authorId === undefined) {
|
||||
throw new Error('Required parameter authorId was null or undefined when calling getNewsByAuthor_1.');
|
||||
}
|
||||
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>authorId, 'authorId');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>page, 'page');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>pageSize, 'pageSize');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>sortOrder, 'sortOrder');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>query, 'query');
|
||||
|
||||
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/news/by-author`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<NewsPage>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a single news article including its full content.
|
||||
* @endpoint get /api/news/{news_id}
|
||||
* @param newsId The unique id of the news article (Elasticsearch _id).
|
||||
* @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 getNewsById(newsId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<NewsArticleDetail>;
|
||||
public getNewsById(newsId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<NewsArticleDetail>>;
|
||||
public getNewsById(newsId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<NewsArticleDetail>>;
|
||||
public getNewsById(newsId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (newsId === null || newsId === undefined) {
|
||||
throw new Error('Required parameter newsId was null or undefined when calling getNewsById.');
|
||||
}
|
||||
|
||||
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/news/${this.configuration.encodeParam({name: "newsId", value: newsId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<NewsArticleDetail>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a single news article including its full content.
|
||||
* @endpoint get /api/news/{news_id}
|
||||
* @param newsId The unique id of the news article (Elasticsearch _id).
|
||||
* @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 getNewsById_2(newsId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<NewsArticleDetail>;
|
||||
public getNewsById_2(newsId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<NewsArticleDetail>>;
|
||||
public getNewsById_2(newsId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<NewsArticleDetail>>;
|
||||
public getNewsById_2(newsId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (newsId === null || newsId === undefined) {
|
||||
throw new Error('Required parameter newsId was null or undefined when calling getNewsById_2.');
|
||||
}
|
||||
|
||||
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/news/${this.configuration.encodeParam({name: "newsId", value: newsId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<NewsArticleDetail>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a page of news articles, newest first.
|
||||
* @endpoint get /api/news
|
||||
* @param page Page number (1-based).
|
||||
* @param pageSize Articles per page.
|
||||
* @param sortOrder Sort order: \'desc\' (newest first) or \'asc\' (oldest first).
|
||||
* @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 listNews(page?: number, pageSize?: number, sortOrder?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<NewsPage>;
|
||||
public listNews(page?: number, pageSize?: number, sortOrder?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<NewsPage>>;
|
||||
public listNews(page?: number, pageSize?: number, sortOrder?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<NewsPage>>;
|
||||
public listNews(page?: number, pageSize?: number, sortOrder?: 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>pageSize, 'pageSize');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>sortOrder, 'sortOrder');
|
||||
|
||||
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/news`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<NewsPage>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a page of news articles, newest first.
|
||||
* @endpoint get /api/news
|
||||
* @param page Page number (1-based).
|
||||
* @param pageSize Articles per page.
|
||||
* @param sortOrder Sort order: \'desc\' (newest first) or \'asc\' (oldest first).
|
||||
* @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 listNews_3(page?: number, pageSize?: number, sortOrder?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<NewsPage>;
|
||||
public listNews_3(page?: number, pageSize?: number, sortOrder?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<NewsPage>>;
|
||||
public listNews_3(page?: number, pageSize?: number, sortOrder?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<NewsPage>>;
|
||||
public listNews_3(page?: number, pageSize?: number, sortOrder?: 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>pageSize, 'pageSize');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>sortOrder, 'sortOrder');
|
||||
|
||||
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/news`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<NewsPage>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Searches news articles by full text (full_content).
|
||||
* @endpoint get /api/news/search
|
||||
* @param query Search term, matched against the full text (full_content).
|
||||
* @param page Page number (1-based).
|
||||
* @param pageSize Articles per page.
|
||||
* @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 searchNews(query: string, page?: number, pageSize?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<NewsPage>;
|
||||
public searchNews(query: string, page?: number, pageSize?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<NewsPage>>;
|
||||
public searchNews(query: string, page?: number, pageSize?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<NewsPage>>;
|
||||
public searchNews(query: string, page?: number, pageSize?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (query === null || query === undefined) {
|
||||
throw new Error('Required parameter query was null or undefined when calling searchNews.');
|
||||
}
|
||||
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>query, 'query');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>page, 'page');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>pageSize, 'pageSize');
|
||||
|
||||
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/news/search`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<NewsPage>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Searches news articles by full text (full_content).
|
||||
* @endpoint get /api/news/search
|
||||
* @param query Search term, matched against the full text (full_content).
|
||||
* @param page Page number (1-based).
|
||||
* @param pageSize Articles per page.
|
||||
* @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 searchNews_4(query: string, page?: number, pageSize?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<NewsPage>;
|
||||
public searchNews_4(query: string, page?: number, pageSize?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<NewsPage>>;
|
||||
public searchNews_4(query: string, page?: number, pageSize?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<NewsPage>>;
|
||||
public searchNews_4(query: string, page?: number, pageSize?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (query === null || query === undefined) {
|
||||
throw new Error('Required parameter query was null or undefined when calling searchNews_4.');
|
||||
}
|
||||
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>query, 'query');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>page, 'page');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>pageSize, 'pageSize');
|
||||
|
||||
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/news/search`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<NewsPage>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
/* tslint:disable:no-unused-variable member-ordering */
|
||||
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import { HttpClient, HttpHeaders, HttpParams,
|
||||
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
// @ts-ignore
|
||||
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||
// @ts-ignore
|
||||
import { PatentsByAuthorResponse } from '../model/patentsByAuthorResponse';
|
||||
|
||||
// @ts-ignore
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BaseService } from '../api.base.service';
|
||||
|
||||
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class PatentsService extends BaseService {
|
||||
|
||||
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
|
||||
super(basePath, configuration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get patents matched to an author by name.
|
||||
* @endpoint get /api/inse-service/authors/{author_id}/patents
|
||||
* @param authorId
|
||||
* @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 getPatentsByAuthor(authorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<PatentsByAuthorResponse>;
|
||||
public getPatentsByAuthor(authorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<PatentsByAuthorResponse>>;
|
||||
public getPatentsByAuthor(authorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<PatentsByAuthorResponse>>;
|
||||
public getPatentsByAuthor(authorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (authorId === null || authorId === undefined) {
|
||||
throw new Error('Required parameter authorId was null or undefined when calling getPatentsByAuthor.');
|
||||
}
|
||||
|
||||
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/authors/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/patents`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<PatentsByAuthorResponse>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -112,16 +112,13 @@ export class PersonsService extends BaseService {
|
||||
* @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 getPersonByID(id: string, include: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AuthorsListResponse>;
|
||||
public getPersonByID(id: string, include: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AuthorsListResponse>>;
|
||||
public getPersonByID(id: string, include: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AuthorsListResponse>>;
|
||||
public getPersonByID(id: string, include: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
public getPersonByID(id: string, include?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<CustomAuthorsListResponse>;
|
||||
public getPersonByID(id: string, include?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<CustomAuthorsListResponse>>;
|
||||
public getPersonByID(id: string, include?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<CustomAuthorsListResponse>>;
|
||||
public getPersonByID(id: string, include?: 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 getPersonByID.');
|
||||
}
|
||||
if (include === null || include === undefined) {
|
||||
throw new Error('Required parameter include was null or undefined when calling getPersonByID.');
|
||||
}
|
||||
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
@@ -154,7 +151,7 @@ export class PersonsService extends BaseService {
|
||||
|
||||
let localVarPath = `/api/inse-service/person/${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<AuthorsListResponse>('get', `${basePath}${localVarPath}`,
|
||||
return this.httpClient.request<CustomAuthorsListResponse>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
@@ -176,16 +173,13 @@ export class PersonsService extends BaseService {
|
||||
* @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 getPersonByID_1(id: string, include: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AuthorsListResponse>;
|
||||
public getPersonByID_1(id: string, include: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AuthorsListResponse>>;
|
||||
public getPersonByID_1(id: string, include: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AuthorsListResponse>>;
|
||||
public getPersonByID_1(id: string, include: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
public getPersonByID_1(id: string, include?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<CustomAuthorsListResponse>;
|
||||
public getPersonByID_1(id: string, include?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<CustomAuthorsListResponse>>;
|
||||
public getPersonByID_1(id: string, include?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<CustomAuthorsListResponse>>;
|
||||
public getPersonByID_1(id: string, include?: 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 getPersonByID_1.');
|
||||
}
|
||||
if (include === null || include === undefined) {
|
||||
throw new Error('Required parameter include was null or undefined when calling getPersonByID_1.');
|
||||
}
|
||||
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
@@ -218,7 +212,7 @@ export class PersonsService extends BaseService {
|
||||
|
||||
let localVarPath = `/api/inse-service/person/${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<AuthorsListResponse>('get', `${basePath}${localVarPath}`,
|
||||
return this.httpClient.request<CustomAuthorsListResponse>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
|
||||
@@ -16,14 +16,32 @@ import { HttpClient, HttpHeaders, HttpParams,
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
// @ts-ignore
|
||||
import { BundProjectDetails } from '../model/bundProjectDetails';
|
||||
// @ts-ignore
|
||||
import { BundProjectPage } from '../model/bundProjectPage';
|
||||
// @ts-ignore
|
||||
import { CordisEuProjectPage } from '../model/cordisEuProjectPage';
|
||||
// @ts-ignore
|
||||
import { DfgProjectDetails } from '../model/dfgProjectDetails';
|
||||
// @ts-ignore
|
||||
import { DfgProjectPage } from '../model/dfgProjectPage';
|
||||
// @ts-ignore
|
||||
import { EuProjectPage } from '../model/euProjectPage';
|
||||
import { EuOrganizationProjectSummaryPage } from '../model/euOrganizationProjectSummaryPage';
|
||||
// @ts-ignore
|
||||
import { FundingProjectPage } from '../model/fundingProjectPage';
|
||||
// @ts-ignore
|
||||
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||
// @ts-ignore
|
||||
import { InstitutionFunderSummary } from '../model/institutionFunderSummary';
|
||||
// @ts-ignore
|
||||
import { ProjectType } from '../model/projectType';
|
||||
// @ts-ignore
|
||||
import { ProjectsFilteringProperties } from '../model/projectsFilteringProperties';
|
||||
// @ts-ignore
|
||||
import { ProjectsSortBy } from '../model/projectsSortBy';
|
||||
// @ts-ignore
|
||||
import { SortDirection } from '../model/sortDirection';
|
||||
|
||||
// @ts-ignore
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
@@ -41,82 +59,6 @@ export class ProjectsService extends BaseService {
|
||||
super(basePath, configuration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get bund projects.
|
||||
* Returns a page of bund projects based on the provided pagination parameters and optional institution filter.
|
||||
* @endpoint get /api/projects/institution/bund/search
|
||||
* @param institutionId The institution ID to filter by.
|
||||
* @param topic The topic to filter by.
|
||||
* @param page The page number.
|
||||
* @param size The page size.
|
||||
* @param sortBy The field to sort by.
|
||||
* @param sortDirection The sort direction (asc or desc).
|
||||
* @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 getBundProjects(institutionId: string, topic?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<BundProjectPage>;
|
||||
public getBundProjects(institutionId: string, topic?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<BundProjectPage>>;
|
||||
public getBundProjects(institutionId: string, topic?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<BundProjectPage>>;
|
||||
public getBundProjects(institutionId: string, topic?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (institutionId === null || institutionId === undefined) {
|
||||
throw new Error('Required parameter institutionId was null or undefined when calling getBundProjects.');
|
||||
}
|
||||
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>institutionId, 'institution_id');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>topic, 'topic');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>page, 'page');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>size, 'size');
|
||||
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/projects/institution/bund/search`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<BundProjectPage>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get DFG projects.
|
||||
* Returns a page of DFG projects based on the provided pagination parameters and optional institution filter.
|
||||
@@ -193,36 +135,459 @@ export class ProjectsService extends BaseService {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get EU projects for an author.
|
||||
* Returns a list of EU projects associated with the specified author ID.
|
||||
* @endpoint get /api/projects/author/{raw_oa_author_id}/eu
|
||||
* @param rawOaAuthorId The author ID to filter by.
|
||||
* @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 getEuProjectsForAuthor(rawOaAuthorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<CordisEuProjectPage>;
|
||||
public getEuProjectsForAuthor(rawOaAuthorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<CordisEuProjectPage>>;
|
||||
public getEuProjectsForAuthor(rawOaAuthorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<CordisEuProjectPage>>;
|
||||
public getEuProjectsForAuthor(rawOaAuthorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (rawOaAuthorId === null || rawOaAuthorId === undefined) {
|
||||
throw new Error('Required parameter rawOaAuthorId was null or undefined when calling getEuProjectsForAuthor.');
|
||||
}
|
||||
|
||||
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/author/${this.configuration.encodeParam({name: "rawOaAuthorId", value: rawOaAuthorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/eu`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<CordisEuProjectPage>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get funding over time for bund projects.
|
||||
* Returns the funding over time for bund projects associated with the specified institution.
|
||||
* @endpoint get /api/projects/institution/bund/funding-over-time
|
||||
* @param rawOaInstitutionId The institution ID to filter by.
|
||||
* @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 getInstitutionBundProjectsFundingOverTime(rawOaInstitutionId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<InstitutionFunderSummary>;
|
||||
public getInstitutionBundProjectsFundingOverTime(rawOaInstitutionId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<InstitutionFunderSummary>>;
|
||||
public getInstitutionBundProjectsFundingOverTime(rawOaInstitutionId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<InstitutionFunderSummary>>;
|
||||
public getInstitutionBundProjectsFundingOverTime(rawOaInstitutionId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (rawOaInstitutionId === null || rawOaInstitutionId === undefined) {
|
||||
throw new Error('Required parameter rawOaInstitutionId was null or undefined when calling getInstitutionBundProjectsFundingOverTime.');
|
||||
}
|
||||
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>rawOaInstitutionId, 'raw_oa_institution_id');
|
||||
|
||||
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/institution/bund/funding-over-time`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<InstitutionFunderSummary>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get funding over time for EU projects.
|
||||
* Returns the funding over time for EU projects associated with the specified institution.
|
||||
* @endpoint get /api/projects/institution/eu/funding-over-time
|
||||
* @param rawOaInstitutionId The institution ID to filter by.
|
||||
* @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 getInstitutionCordisEuProjectsFundingOverTime(rawOaInstitutionId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<InstitutionFunderSummary>;
|
||||
public getInstitutionCordisEuProjectsFundingOverTime(rawOaInstitutionId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<InstitutionFunderSummary>>;
|
||||
public getInstitutionCordisEuProjectsFundingOverTime(rawOaInstitutionId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<InstitutionFunderSummary>>;
|
||||
public getInstitutionCordisEuProjectsFundingOverTime(rawOaInstitutionId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (rawOaInstitutionId === null || rawOaInstitutionId === undefined) {
|
||||
throw new Error('Required parameter rawOaInstitutionId was null or undefined when calling getInstitutionCordisEuProjectsFundingOverTime.');
|
||||
}
|
||||
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>rawOaInstitutionId, 'raw_oa_institution_id');
|
||||
|
||||
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/institution/eu/funding-over-time`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<InstitutionFunderSummary>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a single BUND project.
|
||||
* Returns a single BUND project based on its ID.
|
||||
* @endpoint get /api/projects/bund/{id}
|
||||
* @param id The ID of the BUND 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 getSingleBundProject(id: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<BundProjectDetails>;
|
||||
public getSingleBundProject(id: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<BundProjectDetails>>;
|
||||
public getSingleBundProject(id: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<BundProjectDetails>>;
|
||||
public getSingleBundProject(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 getSingleBundProject.');
|
||||
}
|
||||
|
||||
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/bund/${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<BundProjectDetails>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a single DFG project.
|
||||
* Returns a single DFG project based on its ID.
|
||||
* @endpoint get /api/projects/dfg/{id}
|
||||
* @param id The ID of the DFG 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 getSingleDfgProject(id: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<DfgProjectDetails>;
|
||||
public getSingleDfgProject(id: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<DfgProjectDetails>>;
|
||||
public getSingleDfgProject(id: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<DfgProjectDetails>>;
|
||||
public getSingleDfgProject(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 getSingleDfgProject.');
|
||||
}
|
||||
|
||||
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/dfg/${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<DfgProjectDetails>('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.
|
||||
* @endpoint post /api/projects/institution/bund/search
|
||||
* @param projectsFilteringProperties
|
||||
* @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 searchBundProjects(projectsFilteringProperties: ProjectsFilteringProperties, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<BundProjectPage>;
|
||||
public searchBundProjects(projectsFilteringProperties: ProjectsFilteringProperties, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<BundProjectPage>>;
|
||||
public searchBundProjects(projectsFilteringProperties: ProjectsFilteringProperties, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<BundProjectPage>>;
|
||||
public searchBundProjects(projectsFilteringProperties: ProjectsFilteringProperties, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (projectsFilteringProperties === null || projectsFilteringProperties === undefined) {
|
||||
throw new Error('Required parameter projectsFilteringProperties was null or undefined when calling searchBundProjects.');
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
|
||||
// to determine the Content-Type header
|
||||
const consumes: string[] = [
|
||||
'application/json'
|
||||
];
|
||||
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
|
||||
if (httpContentTypeSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
|
||||
}
|
||||
|
||||
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/institution/bund/search`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<BundProjectPage>('post', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
body: projectsFilteringProperties,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get EU projects.
|
||||
* Returns a page of EU projects based on the provided pagination parameters and optional institution filter.
|
||||
* @endpoint get /api/projects/institution/eu/search
|
||||
* @param institutionId The institution ID to filter by.
|
||||
* @param topic The topic to filter by.
|
||||
* @endpoint post /api/projects/institution/eu/search
|
||||
* @param projectsFilteringProperties
|
||||
* @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 searchCordisEuProjects(projectsFilteringProperties: ProjectsFilteringProperties, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<EuOrganizationProjectSummaryPage>;
|
||||
public searchCordisEuProjects(projectsFilteringProperties: ProjectsFilteringProperties, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<EuOrganizationProjectSummaryPage>>;
|
||||
public searchCordisEuProjects(projectsFilteringProperties: ProjectsFilteringProperties, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<EuOrganizationProjectSummaryPage>>;
|
||||
public searchCordisEuProjects(projectsFilteringProperties: ProjectsFilteringProperties, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (projectsFilteringProperties === null || projectsFilteringProperties === undefined) {
|
||||
throw new Error('Required parameter projectsFilteringProperties was null or undefined when calling searchCordisEuProjects.');
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
|
||||
// to determine the Content-Type header
|
||||
const consumes: string[] = [
|
||||
'application/json'
|
||||
];
|
||||
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
|
||||
if (httpContentTypeSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
|
||||
}
|
||||
|
||||
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/institution/eu/search`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<EuOrganizationProjectSummaryPage>('post', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
body: projectsFilteringProperties,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Search projects across all funders.
|
||||
* Returns a page of projects across all funders based on the provided pagination parameters and optional institution filter.
|
||||
* @endpoint get /api/projects/search
|
||||
* @param page The page number.
|
||||
* @param size The page size.
|
||||
* @param selectedProjectTypes The set of project types to filter by (e.g., \'bund\', \'eu\', \'dfg\'). If not provided, projects of all types will be included.
|
||||
* @param title The title to filter by.
|
||||
* @param sortBy The field to sort by.
|
||||
* @param sortDirection The sort direction (asc or desc).
|
||||
* @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 getEuProjects(institutionId: string, topic?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<EuProjectPage>;
|
||||
public getEuProjects(institutionId: string, topic?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<EuProjectPage>>;
|
||||
public getEuProjects(institutionId: string, topic?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<EuProjectPage>>;
|
||||
public getEuProjects(institutionId: string, topic?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (institutionId === null || institutionId === undefined) {
|
||||
throw new Error('Required parameter institutionId was null or undefined when calling getEuProjects.');
|
||||
}
|
||||
public searchProjects(page?: number, size?: number, selectedProjectTypes?: Set<ProjectType>, title?: string, sortBy?: ProjectsSortBy, sortDirection?: SortDirection, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<FundingProjectPage>;
|
||||
public searchProjects(page?: number, size?: number, selectedProjectTypes?: Set<ProjectType>, title?: string, sortBy?: ProjectsSortBy, sortDirection?: SortDirection, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<FundingProjectPage>>;
|
||||
public searchProjects(page?: number, size?: number, selectedProjectTypes?: Set<ProjectType>, title?: string, sortBy?: ProjectsSortBy, sortDirection?: SortDirection, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<FundingProjectPage>>;
|
||||
public searchProjects(page?: number, size?: number, selectedProjectTypes?: Set<ProjectType>, title?: string, sortBy?: ProjectsSortBy, sortDirection?: SortDirection, 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>institutionId, 'institution_id');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>topic, 'topic');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>page, 'page');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>size, 'size');
|
||||
if (selectedProjectTypes) {
|
||||
selectedProjectTypes.forEach((element) => {
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>element, 'selected_project_types');
|
||||
})
|
||||
}
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>title, 'title');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>sortBy, 'sort_by');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
@@ -253,9 +618,9 @@ export class ProjectsService extends BaseService {
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/projects/institution/eu/search`;
|
||||
let localVarPath = `/api/projects/search`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<EuProjectPage>('get', `${basePath}${localVarPath}`,
|
||||
return this.httpClient.request<FundingProjectPage>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* Clean summary model for a Bund (federal) project, consolidating all fields into semantic English names with proper native types.
|
||||
*/
|
||||
export interface BundProjectDetails {
|
||||
/**
|
||||
* The ID of the Bund project
|
||||
*/
|
||||
id: string;
|
||||
funding_reference?: string | null;
|
||||
title?: string | null;
|
||||
description?: string | null;
|
||||
joint_project?: string | null;
|
||||
funding_type?: string | null;
|
||||
funding_profile?: string | null;
|
||||
funding_amount?: number | null;
|
||||
funding_start_date?: string | null;
|
||||
funding_end_date?: string | null;
|
||||
duration?: string | null;
|
||||
performance_plan_code?: string | null;
|
||||
performance_plan_fullname?: string | null;
|
||||
executing_agency?: string | null;
|
||||
funding_recipient?: string | null;
|
||||
project_agency?: string | null;
|
||||
project_agency_fullname?: string | null;
|
||||
department?: string | null;
|
||||
department_fullname?: string | null;
|
||||
division?: string | null;
|
||||
location?: string | null;
|
||||
municipality?: string | null;
|
||||
state?: string | null;
|
||||
country?: string | null;
|
||||
municipality_code?: string | null;
|
||||
publication_date?: string | null;
|
||||
is_new?: boolean | null;
|
||||
record_date?: string | null;
|
||||
unix_timestamp?: number | null;
|
||||
/**
|
||||
* All persons associated with the Bund project (from nested Arb object)
|
||||
*/
|
||||
associated_persons?: Array<string>;
|
||||
/**
|
||||
* All institutions associated with the Bund project
|
||||
*/
|
||||
institutions?: Array<string>;
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
*/
|
||||
|
||||
|
||||
export interface CareerMetrics {
|
||||
first_publication_year?: number | null;
|
||||
last_publication_year?: number | null;
|
||||
career_age?: number | null;
|
||||
career_span?: number | null;
|
||||
career_stage?: string | null;
|
||||
/**
|
||||
* Number of distinct years with at least one publication.
|
||||
*/
|
||||
active_years?: number;
|
||||
/**
|
||||
* Number of publications used for career metrics.
|
||||
*/
|
||||
publication_count?: number;
|
||||
publications_per_active_year?: number | null;
|
||||
publications_per_career_year?: number | null;
|
||||
years_since_last_publication?: number | null;
|
||||
/**
|
||||
* True if publication years look suspicious.
|
||||
*/
|
||||
has_suspicious_publication_years?: boolean;
|
||||
}
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
/**
|
||||
* 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 { DisplayCodeSplittedNested } from './displayCodeSplittedNested';
|
||||
|
||||
|
||||
export interface CategoryNested {
|
||||
category?: string | null;
|
||||
code?: string | null;
|
||||
display_code?: string | null;
|
||||
/**
|
||||
* A tokenized hierarchy breakdown of the display code represented as an array of strings.
|
||||
*/
|
||||
display_code_splitted?: Array<string>;
|
||||
/**
|
||||
* Granular, nested breakdowns of the split parts of the display code.
|
||||
*/
|
||||
display_code_splitted_nested?: Array<DisplayCodeSplittedNested>;
|
||||
}
|
||||
|
||||
@@ -10,9 +10,9 @@
|
||||
|
||||
|
||||
export const CollaborationNetworkNodeType = {
|
||||
author: 'author',
|
||||
institution: 'institution',
|
||||
work: 'work'
|
||||
Author: 'author',
|
||||
Institution: 'institution',
|
||||
Work: 'work'
|
||||
} as const;
|
||||
export type CollaborationNetworkNodeType = typeof CollaborationNetworkNodeType[keyof typeof CollaborationNetworkNodeType];
|
||||
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
import { MatchedOfficer } from './matchedOfficer';
|
||||
|
||||
|
||||
export interface CompanyConnection {
|
||||
company_number?: string | null;
|
||||
company_name?: string | null;
|
||||
company_status?: string | null;
|
||||
register_art?: string | null;
|
||||
register_nummer?: string | null;
|
||||
native_company_number?: string | null;
|
||||
registrar?: string | null;
|
||||
registered_office?: string | null;
|
||||
registered_address?: string | null;
|
||||
retrieved_at?: string | null;
|
||||
matched_officers?: Array<MatchedOfficer>;
|
||||
officers?: Array<MatchedOfficer>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
import { CompanyConnection } from './companyConnection';
|
||||
|
||||
|
||||
export interface CompanyConnectionsResponse {
|
||||
author_id: string;
|
||||
display_name?: string | null;
|
||||
is_ude_author: boolean;
|
||||
institution_scope?: string | null;
|
||||
matching_institutions?: Array<string>;
|
||||
matching_method?: string | null;
|
||||
company_count: number;
|
||||
has_more_results: boolean;
|
||||
common_name_warning: boolean;
|
||||
connections?: Array<CompanyConnection>;
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
*/
|
||||
import { Keywords } from './keywords';
|
||||
import { Topics } from './topics';
|
||||
|
||||
|
||||
export interface CordisEuProject {
|
||||
/**
|
||||
* Unique identifier for the project, typically the CORDIS ID
|
||||
*/
|
||||
id: string;
|
||||
rcn?: string | null;
|
||||
acronym?: string | null;
|
||||
title?: string | null;
|
||||
objective?: string | null;
|
||||
frameworkProgramme?: string | null;
|
||||
fundingScheme?: string | null;
|
||||
legalBasis?: string | null;
|
||||
masterCall?: string | null;
|
||||
subCall?: string | null;
|
||||
topics?: Topics | null;
|
||||
nature?: string | null;
|
||||
status?: string | null;
|
||||
ecMaxContribution?: number | null;
|
||||
totalCost?: number | null;
|
||||
startDate?: string | null;
|
||||
endDate?: string | null;
|
||||
ecSignatureDate?: string | null;
|
||||
contentUpdateDate?: string | null;
|
||||
grantDoi?: string | null;
|
||||
humanValidated?: boolean | null;
|
||||
keywords?: Keywords | null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* 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 { CordisEuProject } from './cordisEuProject';
|
||||
|
||||
|
||||
export interface CordisEuProjectPage {
|
||||
/**
|
||||
* The current page number.
|
||||
*/
|
||||
page?: number;
|
||||
/**
|
||||
* The requested page size.
|
||||
*/
|
||||
size?: number;
|
||||
/**
|
||||
* The total number of items.
|
||||
*/
|
||||
total?: number;
|
||||
/**
|
||||
* The CORDIS EU projects on this page.
|
||||
*/
|
||||
elements?: Array<CordisEuProject>;
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
*/
|
||||
import { AuthorAffiliationsInner } from './authorAffiliationsInner';
|
||||
import { AuthorParsedLongestName } from './authorParsedLongestName';
|
||||
import { CareerMetrics } from './careerMetrics';
|
||||
import { DehydratedInstitution } from './dehydratedInstitution';
|
||||
import { AuthorCountsByYearInner } from './authorCountsByYearInner';
|
||||
import { AuthorIds } from './authorIds';
|
||||
@@ -35,5 +36,6 @@ export interface CustomAuthor {
|
||||
created_date?: string | null;
|
||||
updated_date?: string | null;
|
||||
relevance_rating?: string | null;
|
||||
career_metrics?: CareerMetrics | null;
|
||||
}
|
||||
|
||||
|
||||
@@ -9,13 +9,12 @@
|
||||
*/
|
||||
import { Meta } from './meta';
|
||||
import { CustomAuthor } from './customAuthor';
|
||||
import { Author } from './author';
|
||||
import { GroupByResult } from './groupByResult';
|
||||
|
||||
|
||||
export interface CustomAuthorsListResponse {
|
||||
meta?: Meta | null;
|
||||
results?: Array<Author> | null;
|
||||
results?: Array<CustomAuthor> | null;
|
||||
group_by?: Array<GroupByResult> | null;
|
||||
placeholder?: CustomAuthor | 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.
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* Clean summary model for a DFG project, consolidating all person roles and institution references into unified lists.
|
||||
*/
|
||||
export interface DfgProjectDetails {
|
||||
/**
|
||||
* The ID of the DFG project
|
||||
*/
|
||||
id: string;
|
||||
link?: string | null;
|
||||
title?: string | null;
|
||||
description?: string | null;
|
||||
project_identifier?: string | null;
|
||||
funding_start_date?: string | null;
|
||||
funding_end_date?: string | null;
|
||||
dfg_procedure?: string | null;
|
||||
subject_area?: string | null;
|
||||
funding_type?: string | null;
|
||||
international_reference?: string | null;
|
||||
website?: string | null;
|
||||
/**
|
||||
* All persons associated with the DFG project (any role)
|
||||
*/
|
||||
associated_persons?: Array<string>;
|
||||
/**
|
||||
* All institutions associated with the DFG project
|
||||
*/
|
||||
institutions?: Array<string>;
|
||||
subproject_of?: string | null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
|
||||
export interface EuOrganizationProjectSummary {
|
||||
/**
|
||||
* The unique identifier of the organization.
|
||||
*/
|
||||
organization_id: string;
|
||||
/**
|
||||
* The unique identifier of the project.
|
||||
*/
|
||||
project_id: string;
|
||||
title?: string | null;
|
||||
start_date?: string | null;
|
||||
end_date?: string | null;
|
||||
acronym?: string | null;
|
||||
ec_contribution?: number | null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* 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 { EuOrganizationProjectSummary } from './euOrganizationProjectSummary';
|
||||
|
||||
|
||||
export interface EuOrganizationProjectSummaryPage {
|
||||
/**
|
||||
* The current page number.
|
||||
*/
|
||||
page?: number;
|
||||
/**
|
||||
* The requested page size.
|
||||
*/
|
||||
size?: number;
|
||||
/**
|
||||
* The total number of items.
|
||||
*/
|
||||
total?: number;
|
||||
/**
|
||||
* The organization project summaries on this page.
|
||||
*/
|
||||
elements?: Array<EuOrganizationProjectSummary>;
|
||||
}
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
/**
|
||||
* 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 { ProgrammeNested } from './programmeNested';
|
||||
import { KeywordNested } from './keywordNested';
|
||||
import { OrganizationNested } from './organizationNested';
|
||||
import { CategoryNested } from './categoryNested';
|
||||
|
||||
|
||||
export interface EuProject {
|
||||
acronym?: string | null;
|
||||
/**
|
||||
* Structured lists of classification categories and taxonomy mappings assigned to the project.
|
||||
*/
|
||||
categories_nested?: Array<CategoryNested>;
|
||||
doc_number?: string | null;
|
||||
doi?: string | null;
|
||||
ec_max_contribution?: string | null;
|
||||
end_date?: string | null;
|
||||
funding_end?: string | null;
|
||||
funding_start?: string | null;
|
||||
id?: string | null;
|
||||
keywords?: string | null;
|
||||
/**
|
||||
* Strictly tokenized and isolated keywords nested for targeted search engine aggregations.
|
||||
*/
|
||||
keywords_nested?: Array<KeywordNested>;
|
||||
link?: string | null;
|
||||
objective?: string | null;
|
||||
/**
|
||||
* The full roster of academic, public, or private organizations participating in the project consortium.
|
||||
*/
|
||||
organization_nested?: Array<OrganizationNested>;
|
||||
/**
|
||||
* The nested historical line of EU funding frameworks and structural grants supporting this project.
|
||||
*/
|
||||
programme_nested?: Array<ProgrammeNested>;
|
||||
source?: string | null;
|
||||
start_date?: string | null;
|
||||
status?: string | null;
|
||||
teaser?: string | null;
|
||||
title?: string | null;
|
||||
total_cost?: string | null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* 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 { ProjectType } from './projectType';
|
||||
|
||||
|
||||
export interface FundingProject {
|
||||
/**
|
||||
* The type of the project.
|
||||
*/
|
||||
type: ProjectType;
|
||||
/**
|
||||
* The unique identifier of the project.
|
||||
*/
|
||||
id: string;
|
||||
title?: string | null;
|
||||
acronym?: string | null;
|
||||
start_date?: string | null;
|
||||
end_date?: string | null;
|
||||
funding_amount?: number | null;
|
||||
}
|
||||
export namespace FundingProject {
|
||||
}
|
||||
|
||||
|
||||
+4
-4
@@ -7,10 +7,10 @@
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
import { EuProject } from './euProject';
|
||||
import { FundingProject } from './fundingProject';
|
||||
|
||||
|
||||
export interface EuProjectPage {
|
||||
export interface FundingProjectPage {
|
||||
/**
|
||||
* The current page number.
|
||||
*/
|
||||
@@ -24,8 +24,8 @@ export interface EuProjectPage {
|
||||
*/
|
||||
total?: number;
|
||||
/**
|
||||
* The EU projects on this page.
|
||||
* The funding projects on this page.
|
||||
*/
|
||||
elements?: Array<EuProject>;
|
||||
elements?: Array<FundingProject>;
|
||||
}
|
||||
|
||||
@@ -0,0 +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.
|
||||
*/
|
||||
import { ProjectType } from './projectType';
|
||||
|
||||
|
||||
export interface InstitutionFunderSummary {
|
||||
/**
|
||||
* The type of funding data (e.g., \'bund\', \'eu\', \'dfg\').
|
||||
*/
|
||||
type: ProjectType;
|
||||
/**
|
||||
* A dictionary mapping years to total funding amounts for that year.
|
||||
*/
|
||||
funding_per_year?: object;
|
||||
/**
|
||||
* The average annual funding over the continuous period covered by the data.
|
||||
*/
|
||||
annual_average_over_period?: number;
|
||||
}
|
||||
export namespace InstitutionFunderSummary {
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* 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 { Institution } from './institution';
|
||||
|
||||
|
||||
export interface InstitutionPage {
|
||||
/**
|
||||
* List of institutions in the current page.
|
||||
*/
|
||||
elements?: Array<Institution>;
|
||||
/**
|
||||
* Current page number. (0-indexed)
|
||||
*/
|
||||
page?: number;
|
||||
/**
|
||||
* Number of institutions per page.
|
||||
*/
|
||||
size?: number;
|
||||
/**
|
||||
* Total number of institutions matching the search criteria.
|
||||
*/
|
||||
total?: number;
|
||||
}
|
||||
|
||||
+4
-2
@@ -9,7 +9,9 @@
|
||||
*/
|
||||
|
||||
|
||||
export interface DisplayCodeSplittedNested {
|
||||
single_display_code?: string | null;
|
||||
/**
|
||||
* Keywords associated with the project
|
||||
*/
|
||||
export interface Keywords {
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
*/
|
||||
|
||||
|
||||
export interface MatchedOfficer {
|
||||
name?: string | null;
|
||||
firstname?: string | null;
|
||||
lastname?: string | null;
|
||||
city?: string | null;
|
||||
position?: string | null;
|
||||
start_date?: string | null;
|
||||
type?: string | null;
|
||||
flag?: string | null;
|
||||
is_matched_person?: boolean;
|
||||
}
|
||||
|
||||
+4
-4
@@ -9,9 +9,9 @@
|
||||
*/
|
||||
|
||||
|
||||
export interface ProgrammeNested {
|
||||
code?: string | null;
|
||||
id?: string | null;
|
||||
programme?: string | null;
|
||||
export interface MentionedPerson {
|
||||
name: string;
|
||||
is_ude?: boolean;
|
||||
person_id?: string | null;
|
||||
}
|
||||
|
||||
@@ -18,11 +18,16 @@ export * from './autocompleteResponseResultsInner';
|
||||
export * from './award';
|
||||
export * from './bodyCreateUser';
|
||||
export * from './bundProject';
|
||||
export * from './bundProjectDetails';
|
||||
export * from './bundProjectPage';
|
||||
export * from './categoryNested';
|
||||
export * from './careerMetrics';
|
||||
export * from './collaborationNetwork';
|
||||
export * from './collaborationNetworkEdge';
|
||||
export * from './collaborationNetworkNodeType';
|
||||
export * from './companyConnection';
|
||||
export * from './companyConnectionsResponse';
|
||||
export * from './cordisEuProject';
|
||||
export * from './cordisEuProjectPage';
|
||||
export * from './costUsd';
|
||||
export * from './customAuthor';
|
||||
export * from './customAuthorsListResponse';
|
||||
@@ -30,49 +35,63 @@ export * from './dehydratedAuthor';
|
||||
export * from './dehydratedFunder';
|
||||
export * from './dehydratedInstitution';
|
||||
export * from './dehydratedSource';
|
||||
export * from './dfgProjectDetails';
|
||||
export * from './dfgProjectPage';
|
||||
export * from './dfgProjectSummary';
|
||||
export * from './displayCodeSplittedNested';
|
||||
export * from './euProject';
|
||||
export * from './euProjectPage';
|
||||
export * from './euOrganizationProjectSummary';
|
||||
export * from './euOrganizationProjectSummaryPage';
|
||||
export * from './filterInformation';
|
||||
export * from './filterProperties';
|
||||
export * from './funderByAuthor';
|
||||
export * from './fundersByAuthorResponse';
|
||||
export * from './fundingProject';
|
||||
export * from './fundingProjectPage';
|
||||
export * from './fwci';
|
||||
export * from './groupByResult';
|
||||
export * from './hTTPValidationError';
|
||||
export * from './identityGrant';
|
||||
export * from './institution';
|
||||
export * from './institutionFunderSummary';
|
||||
export * from './institutionGeo';
|
||||
export * from './institutionIds';
|
||||
export * from './institutionInformation';
|
||||
export * from './institutionNetworkNode';
|
||||
export * from './institutionPage';
|
||||
export * from './institutionsListResponse';
|
||||
export * from './item';
|
||||
export * from './itemCreate';
|
||||
export * from './itemPage';
|
||||
export * from './keywordNested';
|
||||
export * from './keywords';
|
||||
export * from './latitude';
|
||||
export * from './location';
|
||||
export * from './longitude';
|
||||
export * from './matchedOfficer';
|
||||
export * from './mentionedPerson';
|
||||
export * from './meta';
|
||||
export * from './model2YrMeanCitedness';
|
||||
export * from './newsArticle';
|
||||
export * from './newsArticleDetail';
|
||||
export * from './newsPage';
|
||||
export * from './openAccess';
|
||||
export * from './organizationNested';
|
||||
export * from './patentEntry';
|
||||
export * from './patentsByAuthorResponse';
|
||||
export * from './personBio';
|
||||
export * from './programmeNested';
|
||||
export * from './projectType';
|
||||
export * from './projectsFilteringProperties';
|
||||
export * from './projectsSortBy';
|
||||
export * from './publicationDetailByFunder';
|
||||
export * from './publicationIdsByAuthorPosition';
|
||||
export * from './publicationsByAuthorResponse';
|
||||
export * from './rankingResponse';
|
||||
export * from './score';
|
||||
export * from './sortDirection';
|
||||
export * from './topic';
|
||||
export * from './topicCount';
|
||||
export * from './topicDomain';
|
||||
export * from './topicField';
|
||||
export * from './topicIds';
|
||||
export * from './topicSubfield';
|
||||
export * from './topics';
|
||||
export * from './topicsByTime';
|
||||
export * from './topicsByYear';
|
||||
export * from './topicsListResponse';
|
||||
|
||||
@@ -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.
|
||||
*/
|
||||
|
||||
|
||||
export interface NewsArticle {
|
||||
id: string;
|
||||
date?: string | null;
|
||||
maintitle?: string | null;
|
||||
author?: string | null;
|
||||
url?: string | null;
|
||||
relevant?: boolean | null;
|
||||
snippet?: string | null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
import { MentionedPerson } from './mentionedPerson';
|
||||
|
||||
|
||||
export interface NewsArticleDetail {
|
||||
id: string;
|
||||
date?: string | null;
|
||||
maintitle?: string | null;
|
||||
author?: string | null;
|
||||
url?: string | null;
|
||||
relevant?: boolean | null;
|
||||
snippet?: string | null;
|
||||
full_content?: string | null;
|
||||
authors?: Array<MentionedPerson>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
import { NewsArticle } from './newsArticle';
|
||||
|
||||
|
||||
export interface NewsPage {
|
||||
total: number;
|
||||
page: number;
|
||||
page_size: number;
|
||||
results: Array<NewsArticle>;
|
||||
}
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
/**
|
||||
* 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 OrganizationNested {
|
||||
ec_contribution?: string | null;
|
||||
id?: string | null;
|
||||
name?: string | null;
|
||||
net_ec_contribution?: string | null;
|
||||
total_cost?: string | null;
|
||||
organization_type?: string | null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
import { PatentEntry } from './patentEntry';
|
||||
|
||||
|
||||
export interface PatentsByAuthorResponse {
|
||||
author_id: string;
|
||||
author_name?: string | null;
|
||||
patent_count: number;
|
||||
patents: Array<PatentEntry>;
|
||||
}
|
||||
|
||||
@@ -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 const ProjectType = {
|
||||
Bund: 'bund',
|
||||
Eu: 'eu',
|
||||
Dfg: 'dfg'
|
||||
} as const;
|
||||
export type ProjectType = typeof ProjectType[keyof typeof ProjectType];
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* 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 { SortDirection } from './sortDirection';
|
||||
import { ProjectsSortBy } from './projectsSortBy';
|
||||
import { ProjectType } from './projectType';
|
||||
|
||||
|
||||
export interface ProjectsFilteringProperties {
|
||||
/**
|
||||
* The type of projects to filter by.
|
||||
*/
|
||||
project_type: ProjectType;
|
||||
/**
|
||||
* The page number for pagination.
|
||||
*/
|
||||
page: number;
|
||||
/**
|
||||
* The page size for pagination.
|
||||
*/
|
||||
size: number;
|
||||
raw_oa_institution_id?: string | null;
|
||||
query?: string | null;
|
||||
/**
|
||||
* The field to sort by.
|
||||
*/
|
||||
sort_by?: ProjectsSortBy;
|
||||
/**
|
||||
* The sort direction (asc or desc).
|
||||
*/
|
||||
sort_direction?: SortDirection;
|
||||
}
|
||||
export namespace ProjectsFilteringProperties {
|
||||
}
|
||||
|
||||
|
||||
@@ -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.
|
||||
*/
|
||||
|
||||
|
||||
export const ProjectsSortBy = {
|
||||
Title: 'title',
|
||||
FundingStart: 'funding_start',
|
||||
FundingEnd: 'funding_end',
|
||||
FundingAmount: 'funding_amount'
|
||||
} as const;
|
||||
export type ProjectsSortBy = typeof ProjectsSortBy[keyof typeof ProjectsSortBy];
|
||||
|
||||
@@ -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.
|
||||
*/
|
||||
|
||||
|
||||
export const SortDirection = {
|
||||
Asc: 'asc',
|
||||
Desc: 'desc'
|
||||
} as const;
|
||||
export type SortDirection = typeof SortDirection[keyof typeof SortDirection];
|
||||
|
||||
@@ -9,7 +9,6 @@
|
||||
*/
|
||||
|
||||
|
||||
export interface KeywordNested {
|
||||
keyword?: string | null;
|
||||
export interface Topics {
|
||||
}
|
||||
|
||||
@@ -20,9 +20,9 @@ export interface UniversityRanking {
|
||||
}
|
||||
export namespace UniversityRanking {
|
||||
export const TrendEnum = {
|
||||
up: 'up',
|
||||
down: 'down',
|
||||
stable: 'stable'
|
||||
Up: 'up',
|
||||
Down: 'down',
|
||||
Stable: 'stable'
|
||||
} as const;
|
||||
export type TrendEnum = typeof TrendEnum[keyof typeof TrendEnum];
|
||||
}
|
||||
|
||||
@@ -17,9 +17,9 @@ export interface UniversityTopicData {
|
||||
}
|
||||
export namespace UniversityTopicData {
|
||||
export const TopicEnum = {
|
||||
Artificial_Intelligence: 'Artificial Intelligence',
|
||||
Quantum_Computing: 'Quantum Computing',
|
||||
Renewable_Energy: 'Renewable Energy',
|
||||
ArtificialIntelligence: 'Artificial Intelligence',
|
||||
QuantumComputing: 'Quantum Computing',
|
||||
RenewableEnergy: 'Renewable Energy',
|
||||
Biotechnology: 'Biotechnology'
|
||||
} as const;
|
||||
export type TopicEnum = typeof TopicEnum[keyof typeof TopicEnum];
|
||||
|
||||
@@ -51,6 +51,8 @@ export const appConfig: ApplicationConfig = {
|
||||
return;
|
||||
}
|
||||
|
||||
console.error('Fehler beim Navigieren:', navigationError);
|
||||
|
||||
const error = navigationError.error;
|
||||
let errorMessage: string = 'Unbekannter Fehler';
|
||||
if (error instanceof HttpErrorResponse) {
|
||||
|
||||
@@ -5,9 +5,18 @@ import { personListResolver } from './resolvers/person-list.resolver';
|
||||
import { personBioResolver } from './resolvers/person-bio.resolver';
|
||||
import { personResolver } from './resolvers/person.resolver';
|
||||
import { institutionResolver } from './resolvers/institution.resolver';
|
||||
import { bundProjectsResolver } from './resolvers/bund-projects.resolver';
|
||||
import { euProjectsResolver } from './resolvers/eu-projects.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';
|
||||
import { bundSingleProjectResolver } from './resolvers/bund-single-project-resolver';
|
||||
import { cordisEuProjectPageResolver } from './resolvers/cordis-eu-project-page.resolver';
|
||||
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';
|
||||
|
||||
export const routes: Routes = [
|
||||
{
|
||||
path: '',
|
||||
@@ -75,6 +84,20 @@ export const routes: Routes = [
|
||||
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],
|
||||
@@ -83,6 +106,30 @@ export const routes: Routes = [
|
||||
(mod) => mod.PublicationDetailComponent,
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'projects/dfg/:id',
|
||||
canActivate: [userGuard],
|
||||
pathMatch: 'full',
|
||||
loadComponent: () =>
|
||||
import('./modules/person-projects/dfg-details/dfg-details.component').then(
|
||||
(mod) => mod.DfgDetailsComponent,
|
||||
),
|
||||
resolve: {
|
||||
dfgSingleProject: dfgSingleProjectResolver,
|
||||
},
|
||||
},
|
||||
{
|
||||
path: 'projects/bund/:id',
|
||||
canActivate: [userGuard],
|
||||
pathMatch: 'full',
|
||||
loadComponent: () =>
|
||||
import('./modules/person-projects/bund-details/bund-details.component').then(
|
||||
(mod) => mod.BundDetailsComponent,
|
||||
),
|
||||
resolve: {
|
||||
bundSingleProject: bundSingleProjectResolver,
|
||||
},
|
||||
},
|
||||
{
|
||||
path: 'person/:id',
|
||||
canActivate: [userGuard],
|
||||
@@ -116,6 +163,7 @@ export const routes: Routes = [
|
||||
),
|
||||
resolve: {
|
||||
dfgProjectPage: dfgProjectsResolver,
|
||||
personCordisEuProjectPage: personCordisEuProjectPageResolver,
|
||||
},
|
||||
runGuardsAndResolvers: (from, to) => {
|
||||
const keys = ['page', 'size', 'sort_by', 'sort_direction', 'search'];
|
||||
@@ -168,8 +216,57 @@ 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: () =>
|
||||
import('./modules/person-patents/person-patents.component').then(
|
||||
(mod) => mod.PersonPatentsComponent,
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'company-connections',
|
||||
loadComponent: () =>
|
||||
import('./modules/person-company-connections/person-company-connections.component').then(
|
||||
(mod) => mod.PersonCompanyConnectionsComponent,
|
||||
),
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
path: 'institutions',
|
||||
canActivate: [userGuard],
|
||||
loadComponent: () =>
|
||||
import('./modules/institutions/institutions.component').then(
|
||||
(mod) => mod.InstitutionsComponent,
|
||||
),
|
||||
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),
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
path: 'institution/:institutionId',
|
||||
canActivate: [userGuard],
|
||||
@@ -193,6 +290,13 @@ export const routes: Routes = [
|
||||
(mod) => mod.InstitutionOverviewComponent,
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'publications',
|
||||
loadComponent: () =>
|
||||
import('./modules/institution-publications/institution-publications.component').then(
|
||||
(mod) => mod.InstitutionPublicationsComponent,
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'projects',
|
||||
loadComponent: () => {
|
||||
@@ -201,8 +305,10 @@ export const routes: Routes = [
|
||||
);
|
||||
},
|
||||
resolve: {
|
||||
bundProjectPage: bundProjectsResolver,
|
||||
euProjectPage: euProjectsResolver,
|
||||
bundProjectPage: bundProjectPageResolver,
|
||||
bundProjectsFunding: bundProjectsFundingResolver,
|
||||
cordisEuProjectPage: cordisEuProjectPageResolver,
|
||||
cordisEuProjectsFunding: cordisEuProjectsFundingResolver,
|
||||
},
|
||||
runGuardsAndResolvers: (from, to) => {
|
||||
const keys = ['page', 'size', 'sort_by', 'sort_direction', 'search'];
|
||||
@@ -213,8 +319,26 @@ export const routes: Routes = [
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
path: 'projects',
|
||||
canActivate: [userGuard],
|
||||
loadComponent: () =>
|
||||
import('./modules/projects/projects.component').then(
|
||||
(mod) => mod.ProjectsComponent,
|
||||
),
|
||||
resolve: {
|
||||
fundingProjectPage: fundingProjectPageResolver,
|
||||
},
|
||||
runGuardsAndResolvers: (from, to) => {
|
||||
const keys = ['page', 'size', 'sort_by', 'sort_direction'];
|
||||
const keys = [
|
||||
'search',
|
||||
'page',
|
||||
'size',
|
||||
'selected_project_types',
|
||||
'sort_by',
|
||||
'sorting_order',
|
||||
];
|
||||
|
||||
return keys.some(
|
||||
(key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
|
||||
|
||||
@@ -43,7 +43,7 @@
|
||||
Anmelden
|
||||
</button>
|
||||
|
||||
<div class="field" style="text-align: center; margin-top: -10px;">
|
||||
<div class="field" style="text-align: center; margin-top: -10px">
|
||||
<button mat-button type="button" routerLink="/register">
|
||||
Noch kein Konto? <b>Registrieren</b>
|
||||
</button>
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
<div class="container">
|
||||
<form class="form" [formGroup]="registerForm">
|
||||
<h3>Konto erstellen</h3>
|
||||
<p class="field">
|
||||
Bitte gib Deine Daten ein, um Dich zu registrieren.
|
||||
</p>
|
||||
<p class="field">Bitte gib Deine Daten ein, um Dich zu registrieren.</p>
|
||||
|
||||
<mat-form-field class="field">
|
||||
<mat-label>Benutzername</mat-label>
|
||||
@@ -49,43 +47,50 @@
|
||||
<mat-label>Institution</mat-label>
|
||||
|
||||
<mat-icon matPrefix>apartment</mat-icon>
|
||||
<input
|
||||
type="text"
|
||||
matInput
|
||||
formControlName="institution"
|
||||
[matAutocomplete]="auto"
|
||||
placeholder="Institution suchen..."
|
||||
/>
|
||||
@if (registerForm.controls['institution'].hasError('required')) {
|
||||
<input
|
||||
type="text"
|
||||
matInput
|
||||
formControlName="institution"
|
||||
[matAutocomplete]="auto"
|
||||
placeholder="Institution suchen..." />
|
||||
@if (registerForm.controls['institution'].hasError('required')) {
|
||||
<mat-error>Fehler: <b>Institution</b> erforderlich.</mat-error>
|
||||
}
|
||||
<mat-autocomplete
|
||||
#auto="matAutocomplete"
|
||||
(optionSelected)="onInstitutionSelected($event)">
|
||||
@for (institution of institutionOptions(); track institution.id) {
|
||||
<mat-option [value]="institution.display_name" style="font-size: 16px;">
|
||||
<div><span>{{ institution.display_name }}</span></div>
|
||||
@if (institution.hint) {
|
||||
<small>{{ institution.hint }}</small>
|
||||
}
|
||||
</mat-option>
|
||||
<mat-autocomplete
|
||||
#auto="matAutocomplete"
|
||||
(optionSelected)="onInstitutionSelected($event)">
|
||||
@for (institution of institutionOptions(); track institution.id) {
|
||||
<mat-option
|
||||
[value]="institution.display_name"
|
||||
style="font-size: 16px">
|
||||
<div>
|
||||
<span>{{ institution.display_name }}</span>
|
||||
</div>
|
||||
@if (institution.hint) {
|
||||
<small>{{ institution.hint }}</small>
|
||||
}
|
||||
</mat-autocomplete>
|
||||
</mat-option>
|
||||
}
|
||||
</mat-autocomplete>
|
||||
</mat-form-field>
|
||||
|
||||
<div class="field checkbox-container">
|
||||
<mat-checkbox formControlName="superadmin">Superadmin Rechte</mat-checkbox>
|
||||
<mat-checkbox formControlName="superadmin"
|
||||
>Superadmin Rechte</mat-checkbox
|
||||
>
|
||||
</div>
|
||||
|
||||
<button
|
||||
mat-raised-button
|
||||
class="button"
|
||||
(click)="submit()"
|
||||
[disabled]="!registerForm.valid || (credentialService.validating | async)">
|
||||
[disabled]="
|
||||
!registerForm.valid || (credentialService.validating | async)
|
||||
">
|
||||
Registrieren
|
||||
</button>
|
||||
|
||||
<div class="field" style="text-align: center; margin-top: -10px;">
|
||||
<div class="field" style="text-align: center; margin-top: -10px">
|
||||
<button mat-button type="button" routerLink="/login">
|
||||
Bereits ein Konto? <b>Anmelden</b>
|
||||
</button>
|
||||
@@ -94,4 +99,4 @@
|
||||
<p class="progress">
|
||||
<!-- Statusanzeige analog zum Login-Formular -->
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,11 @@
|
||||
import { Component, inject, OnDestroy, signal, DestroyRef, OnInit } from '@angular/core';
|
||||
import {
|
||||
Component,
|
||||
inject,
|
||||
OnDestroy,
|
||||
signal,
|
||||
DestroyRef,
|
||||
OnInit,
|
||||
} from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { Router, RouterLink } from '@angular/router';
|
||||
@@ -15,8 +22,19 @@ import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatCheckboxModule } from '@angular/material/checkbox';
|
||||
import { CredentialService } from '../../shared/services/credential.service';
|
||||
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
|
||||
import { Subscription, map, switchMap, debounceTime, distinctUntilChanged, catchError,of} from 'rxjs';
|
||||
import { MatAutocompleteModule, MatAutocompleteSelectedEvent } from '@angular/material/autocomplete';
|
||||
import {
|
||||
Subscription,
|
||||
map,
|
||||
switchMap,
|
||||
debounceTime,
|
||||
distinctUntilChanged,
|
||||
catchError,
|
||||
of,
|
||||
} from 'rxjs';
|
||||
import {
|
||||
MatAutocompleteModule,
|
||||
MatAutocompleteSelectedEvent,
|
||||
} from '@angular/material/autocomplete';
|
||||
import { InstitutionsService } from '../../api';
|
||||
@Component({
|
||||
selector: 'app-register',
|
||||
@@ -43,7 +61,7 @@ export class AppRegisterComponent implements OnDestroy, OnInit {
|
||||
private readonly snackBar = inject(MatSnackBar);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
private subscription?: Subscription;
|
||||
private institutionsService = inject(InstitutionsService)
|
||||
private institutionsService = inject(InstitutionsService);
|
||||
registerForm: FormGroup = this.fb.group({
|
||||
username: ['', [Validators.required, Validators.minLength(4)]],
|
||||
email: ['', [Validators.required, Validators.email]],
|
||||
@@ -126,7 +144,10 @@ export class AppRegisterComponent implements OnDestroy, OnInit {
|
||||
}
|
||||
|
||||
return this.searchInstitutions(query).pipe(
|
||||
catchError((ev) => {console.log(ev);return of([])}),
|
||||
catchError((ev) => {
|
||||
console.log(ev);
|
||||
return of([]);
|
||||
}),
|
||||
);
|
||||
}),
|
||||
takeUntilDestroyed(this.destroyRef),
|
||||
@@ -144,7 +165,9 @@ export class AppRegisterComponent implements OnDestroy, OnInit {
|
||||
|
||||
onInstitutionSelected(event: MatAutocompleteSelectedEvent): void {
|
||||
const val = event.option.value;
|
||||
this.registerForm.controls['institution'].setValue(val, { emitEvent: false });
|
||||
this.registerForm.controls['institution'].setValue(val, {
|
||||
emitEvent: false,
|
||||
});
|
||||
this.institutionOptions.set([]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,28 +1,39 @@
|
||||
<div class="dashboard-wrapper">
|
||||
<header class="dashboard-header">
|
||||
<h2>University Performance Dashboard</h2>
|
||||
<div class="controls">
|
||||
<select (change)="onTopicChange($any($event.target).value)">
|
||||
@for (t of topics; track t){
|
||||
<option [value]="t">{{t}}</option>
|
||||
}
|
||||
|
||||
</select>
|
||||
|
||||
<div class="toggle-group">
|
||||
<button [class.active]="metric === 'publications'" (click)="setMetric('publications')">Publications</button>
|
||||
<button [class.active]="metric === 'citations'" (click)="setMetric('citations')">Citations</button>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
<header class="dashboard-header">
|
||||
<h2>University Performance Dashboard</h2>
|
||||
<div class="controls">
|
||||
<select (change)="onTopicChange($any($event.target).value)">
|
||||
@for (t of topics; track t) {
|
||||
<option [value]="t">{{ t }}</option>
|
||||
}
|
||||
</select>
|
||||
|
||||
<div class="content-grid">
|
||||
<section class="chart-section">
|
||||
<app-university-line-chart [data]="rawDataSource" [metric]="metric"></app-university-line-chart>
|
||||
</section>
|
||||
|
||||
<aside class="table-section">
|
||||
<app-university-ranking-table [rankings]="computedRankings" [loading]="isLoading"></app-university-ranking-table>
|
||||
</aside>
|
||||
<div class="toggle-group">
|
||||
<button
|
||||
[class.active]="metric === 'publications'"
|
||||
(click)="setMetric('publications')">
|
||||
Publications
|
||||
</button>
|
||||
<button
|
||||
[class.active]="metric === 'citations'"
|
||||
(click)="setMetric('citations')">
|
||||
Citations
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class="content-grid">
|
||||
<section class="chart-section">
|
||||
<app-university-line-chart
|
||||
[data]="rawDataSource"
|
||||
[metric]="metric"></app-university-line-chart>
|
||||
</section>
|
||||
|
||||
<aside class="table-section">
|
||||
<app-university-ranking-table
|
||||
[rankings]="computedRankings"
|
||||
[loading]="isLoading"></app-university-ranking-table>
|
||||
</aside>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -26,7 +26,7 @@
|
||||
.controls {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
|
||||
|
||||
select {
|
||||
padding: 0.5rem;
|
||||
border-radius: 4px;
|
||||
@@ -40,9 +40,16 @@
|
||||
background: white;
|
||||
color: #0056b3;
|
||||
cursor: pointer;
|
||||
&:first-child { border-radius: 4px 0 0 4px; }
|
||||
&:last-child { border-radius: 0 4px 4px 0; }
|
||||
&.active { background: #0056b3; color: white; }
|
||||
&:first-child {
|
||||
border-radius: 4px 0 0 4px;
|
||||
}
|
||||
&:last-child {
|
||||
border-radius: 0 4px 4px 0;
|
||||
}
|
||||
&.active {
|
||||
background: #0056b3;
|
||||
color: white;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -54,20 +61,35 @@
|
||||
border-collapse: collapse;
|
||||
font-size: 0.9rem;
|
||||
|
||||
th, td {
|
||||
th,
|
||||
td {
|
||||
padding: 0.75rem;
|
||||
text-align: left;
|
||||
border-bottom: 1px solid #f0f0f0;
|
||||
}
|
||||
|
||||
.top-tier { background-color: #f8fbff; font-weight: 600; }
|
||||
.positive { color: #28a745; }
|
||||
.negative { color: #dc3545; }
|
||||
.mover-badge { margin-left: 4px; font-size: 0.8rem; }
|
||||
|
||||
.top-tier {
|
||||
background-color: #f8fbff;
|
||||
font-weight: 600;
|
||||
}
|
||||
.positive {
|
||||
color: #28a745;
|
||||
}
|
||||
.negative {
|
||||
color: #dc3545;
|
||||
}
|
||||
.mover-badge {
|
||||
margin-left: 4px;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
.trend-col {
|
||||
font-weight: bold;
|
||||
&[data-trend="up"] { color: #28a745; }
|
||||
&[data-trend="down"] { color: #dc3545; }
|
||||
&[data-trend='up'] {
|
||||
color: #28a745;
|
||||
}
|
||||
&[data-trend='down'] {
|
||||
color: #dc3545;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,24 +1,31 @@
|
||||
|
||||
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
import { UniversityRankingService } from '../university-ranking/services/uni-ranking-service';
|
||||
import {UniversityLineChartComponent} from '../university-ranking/uni-line-chart/uni-line-chart.component';
|
||||
import { UniversityLineChartComponent } from '../university-ranking/uni-line-chart/uni-line-chart.component';
|
||||
import { UniversityRankingTableComponent } from '../university-ranking/uni-ranking-table/uni-ranking-table.component';
|
||||
import { UniversityTopicData, UniversityRanking } from '../../api';
|
||||
export type ResearchTopic = 'Artificial Intelligence' | 'Quantum Computing' | 'Renewable Energy' | 'Biotechnology';
|
||||
export type ResearchTopic =
|
||||
| 'Artificial Intelligence'
|
||||
| 'Quantum Computing'
|
||||
| 'Renewable Energy'
|
||||
| 'Biotechnology';
|
||||
export type DashboardMetric = 'publications' | 'citations';
|
||||
|
||||
@Component({
|
||||
selector: 'dashboard',
|
||||
imports: [UniversityLineChartComponent,UniversityRankingTableComponent],
|
||||
imports: [UniversityLineChartComponent, UniversityRankingTableComponent],
|
||||
templateUrl: './dashboard.component.html',
|
||||
styleUrl: './dashboard.component.scss',
|
||||
})
|
||||
export class DashboardComponent implements OnInit {
|
||||
topics: ResearchTopic[] = ['Artificial Intelligence', 'Quantum Computing', 'Renewable Energy', 'Biotechnology'];
|
||||
topics: ResearchTopic[] = [
|
||||
'Artificial Intelligence',
|
||||
'Quantum Computing',
|
||||
'Renewable Energy',
|
||||
'Biotechnology',
|
||||
];
|
||||
selectedTopic: ResearchTopic = 'Artificial Intelligence';
|
||||
metric: DashboardMetric = 'publications';
|
||||
|
||||
|
||||
rawDataSource: UniversityTopicData[] = [];
|
||||
computedRankings: UniversityRanking[] = [];
|
||||
isLoading = false;
|
||||
@@ -41,13 +48,15 @@ export class DashboardComponent implements OnInit {
|
||||
|
||||
private loadData() {
|
||||
this.isLoading = true;
|
||||
this.dataService.getRankingData(this.selectedTopic, this.metric).subscribe(response => {
|
||||
// Map backend snake_case properties to frontend camelCase if necessary,
|
||||
// though OpenAPI Generator usually handles this.
|
||||
console.log(response);
|
||||
this.rawDataSource = (response.timeseries as any) || [];
|
||||
this.computedRankings = (response.rankings as any) || [];
|
||||
this.isLoading = false;
|
||||
});
|
||||
this.dataService
|
||||
.getRankingData(this.selectedTopic, this.metric)
|
||||
.subscribe((response) => {
|
||||
// Map backend snake_case properties to frontend camelCase if necessary,
|
||||
// though OpenAPI Generator usually handles this.
|
||||
console.log(response);
|
||||
this.rawDataSource = (response.timeseries as any) || [];
|
||||
this.computedRankings = (response.rankings as any) || [];
|
||||
this.isLoading = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
+1
@@ -0,0 +1 @@
|
||||
<div echarts [options]="options"></div>
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
import { Component, effect, input } from '@angular/core';
|
||||
|
||||
import * as echarts from 'echarts/core';
|
||||
import { EChartsOption } from 'echarts';
|
||||
|
||||
import { GridComponent, LegendComponent } from 'echarts/components';
|
||||
import { CanvasRenderer } from 'echarts/renderers';
|
||||
import { NgxEchartsDirective } from 'ngx-echarts';
|
||||
import { InstitutionFunderSummary } from '../../api';
|
||||
|
||||
echarts.use([GridComponent, CanvasRenderer, LegendComponent]);
|
||||
|
||||
type FunderData = {
|
||||
funderName: string;
|
||||
fundingMap: Record<number, number>;
|
||||
};
|
||||
|
||||
@Component({
|
||||
selector: 'app-institution-projects-funding-graph',
|
||||
imports: [NgxEchartsDirective],
|
||||
templateUrl: './institution-projects-funding-graph.component.html',
|
||||
styleUrl: './institution-projects-funding-graph.component.scss',
|
||||
})
|
||||
export class InstitutionProjectsFundingGraphComponent {
|
||||
options!: EChartsOption;
|
||||
|
||||
fundings = input.required<InstitutionFunderSummary[]>();
|
||||
|
||||
constructor() {
|
||||
effect(() => {
|
||||
const fundings = this.fundings();
|
||||
this.generateChartOptions(fundings);
|
||||
});
|
||||
}
|
||||
|
||||
generateChartOptions(fundings: InstitutionFunderSummary[]): void {
|
||||
const floorToTwoDecimals = (value: number): string => {
|
||||
const floored = Math.floor(value * 100) / 100;
|
||||
return floored.toLocaleString(undefined, {
|
||||
style: 'currency',
|
||||
currency: 'EUR',
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
});
|
||||
};
|
||||
|
||||
const yearsSet = new Set<string>();
|
||||
|
||||
fundings.forEach((series) => {
|
||||
if (series.funding_per_year) {
|
||||
Object.keys(series.funding_per_year).forEach((year) =>
|
||||
yearsSet.add(year),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
const xAxisYears = Array.from(yearsSet).sort(
|
||||
(a, b) => Number(a) - Number(b),
|
||||
);
|
||||
|
||||
const currentYearStr = new Date().getFullYear().toString();
|
||||
|
||||
const chartSeries = fundings.map((series, index) => {
|
||||
const fundingMap = (series.funding_per_year || {}) as Record<
|
||||
string,
|
||||
number
|
||||
>;
|
||||
const dataPoints = xAxisYears.map((year) => fundingMap[year] ?? 0);
|
||||
|
||||
const baseSeries: any = {
|
||||
name: series.type.toUpperCase(),
|
||||
type: 'line',
|
||||
stack: 'TotalInstitutionalFunding',
|
||||
areaStyle: {},
|
||||
emphasis: { focus: 'series' },
|
||||
data: dataPoints,
|
||||
};
|
||||
|
||||
if (index === 0) {
|
||||
baseSeries.markLine = {
|
||||
symbol: ['none', 'none'],
|
||||
silent: true,
|
||||
label: {
|
||||
show: true,
|
||||
position: 'end',
|
||||
formatter: 'Aktuelles Jahr',
|
||||
backgroundColor: '#333',
|
||||
color: '#fff',
|
||||
padding: [4, 6],
|
||||
borderRadius: 4,
|
||||
},
|
||||
lineStyle: {
|
||||
color: '#ff4d4f',
|
||||
type: 'dashed',
|
||||
width: 2,
|
||||
},
|
||||
data: [
|
||||
{
|
||||
xAxis: currentYearStr,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
return baseSeries;
|
||||
});
|
||||
|
||||
this.options = {
|
||||
tooltip: {
|
||||
trigger: 'axis',
|
||||
axisPointer: {
|
||||
type: 'cross',
|
||||
label: { backgroundColor: '#6a7985' },
|
||||
},
|
||||
valueFormatter: (value) => {
|
||||
const numericValue = Array.isArray(value) ? 0 : Number(value ?? 0);
|
||||
return floorToTwoDecimals(numericValue);
|
||||
},
|
||||
},
|
||||
legend: {
|
||||
data: fundings.map((series) => series.type.toUpperCase()),
|
||||
top: '10%',
|
||||
},
|
||||
grid: {
|
||||
left: '4%',
|
||||
right: '4%',
|
||||
bottom: '5%',
|
||||
containLabel: true,
|
||||
},
|
||||
xAxis: [
|
||||
{
|
||||
type: 'category',
|
||||
boundaryGap: false,
|
||||
data: xAxisYears,
|
||||
},
|
||||
],
|
||||
yAxis: [
|
||||
{
|
||||
type: 'value',
|
||||
axisLabel: {
|
||||
formatter: (value: number) =>
|
||||
value.toLocaleString(undefined, {
|
||||
style: 'currency',
|
||||
currency: 'EUR',
|
||||
maximumFractionDigits: 0,
|
||||
}),
|
||||
},
|
||||
},
|
||||
],
|
||||
series: chartSeries,
|
||||
};
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user