Compare commits

..
Author SHA1 Message Date
farajollahi 50912dbac1 fix .env
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-21 10:28:36 +02:00
303 changed files with 15802 additions and 15677 deletions
+13 -7
View File
@@ -8,13 +8,19 @@ build
__pycache__
# Ignore macos
.DS_Store
# Ignore generated python code
src/python/account/
*.pyc
node_modules/
# Ignore generated python code
src/python/account/
# Ignore local environment files
.env
.env.*
!.env.example
!.env.*.example
*.pyc
node_modules/
angular-app/.angular
# Ignore sentence-transformer local model cache
service/sentence_transformer/models/␍
service/sentence_transformer/models/
File diff suppressed because it is too large Load Diff
+2 -3
View File
@@ -13,9 +13,8 @@ RUN pip install --root-user-action=ignore --no-cache-dir --disable-pip-version-c
"pytest~=8.1.0" \
"httpx~=0.27.0" \
"python-multipart~=0.0.19"\
"openai~=2.41.0" \
"sqlmodel~=0.0.33" \
"argon2-cffi~=25.1.0"
"elasticsearch~=9.4.0" \
"openai~=2.41.0"
COPY [ "src/main", "/home" ]
COPY [ "src/data", "/data" ]
+2 -2
View File
@@ -49,7 +49,7 @@ task exportOpenApiSpec(type: Exec) {
commandLine 'docker', 'run', '--rm',
'--platform', "${targetPlatform}",
'-w', '/home',
//'-v', "${projectDir}/src/main:/home", the source code is already baked into the image at build time
'-v', "${projectDir}/src/main:/home",
'-v', "${openApiDir}:/mnt/openapi",
'-e', "DOCKER_DEFAULT_PLATFORM='${targetPlatform}'",
'--name', "${imageName}-service-openapi",
@@ -61,7 +61,7 @@ task exportOpenApiSpec(type: Exec) {
task runServeContainer(type: Exec) {
dependsOn createImage
commandLine 'docker', 'run', '--rm', '-v', "${projectDir}/src/main:/home", '-v', "${projectDir}/src/data:/data", '-p', '8000:8000', '-e', "DOCKER_DEFAULT_PLATFORM='${targetPlatform}'", '-e', "INSE_AUTH_STANDALONE=true", '-e', 'INSE_OPENALEX_WORKS_API_KEY', '--name', "${imageName}-service-serve", '--detach', "${imagePrefix}-service:${imageVersion}", 'run', '--reload', '--reload-dir', './inse'
commandLine 'docker', 'run', '--rm', '-v', "${projectDir}/src/main:/home", '-v', "${projectDir}/src/data:/data", '-p', '8000:8000', '-e', "DOCKER_DEFAULT_PLATFORM='${targetPlatform}'", '-e', "INSE_AUTH_STANDALONE=true", '-e', 'INSE_ELASTICSEARCH_API_KEY', '--name', "${imageName}-service-serve", '--detach', "${imagePrefix}-service:${imageVersion}", 'run', '--reload', '--reload-dir', './inse'
}
task stopServeContainer(type: Exec) {
+2 -2
View File
@@ -7,6 +7,7 @@ requires-python = ">=3.12"
dependencies = [
"cryptography~=42.0.0",
"dotenv>=0.9.9",
"elasticsearch~=9.4.0",
"fastapi~=0.115.0",
"httpx~=0.27.0",
"openai~=2.41.0",
@@ -16,11 +17,10 @@ dependencies = [
"pytest~=8.1.0",
"python-multipart~=0.0.19",
"pyyaml~=6.0.1",
"sqlalchemy~=2.0.0",
"uvicorn~=0.29.0",
"sentence-transformers~=5.5.1",
"torch",
"sqlmodel~=0.0.33",
"argon2-cffi~=25.1.0",
]
[[tool.uv.index]]
+59 -119
View File
@@ -1,13 +1,17 @@
#!/usr/bin/env python3
"""
Script to fetch all topics from 'openalex-topics',
vectorize display names, full descriptions, and individual keywords using the sentence-transformers model,
and push them to the 'topicvectors' index with multi-vector mapping.
One-time script to fetch all topics from 'openalex-topics',
vectorize display names and chunked descriptions using the sentence-transformers model,
and push them to the 'topicvectors' index with multi-vector hybrid mapping.
"""
import os
import sys
import json
import base64
import re
from pathlib import Path
import httpx
import numpy as np
from dotenv import load_dotenv
# Add service/src/main to python path to load settings
@@ -20,10 +24,8 @@ sys.path.append(str(project_root / "service" / "src" / "main"))
from inse.config import settings
ELASTIC_URL = settings.elasticsearch_url
if ELASTIC_URL and not ELASTIC_URL.endswith("/"):
ELASTIC_URL += "/"
API_KEY = settings.elasticsearch_api_key
MODEL_NAME = settings.sentence_transformers_model_name
MODEL_NAME = "paraphrase-multilingual-mpnet-base-v2"
# Import sentence-transformers
from sentence_transformers import SentenceTransformer
@@ -33,12 +35,20 @@ headers = {
"Content-Type": "application/json"
}
def split_into_sentences(text):
if not text:
return []
# Split on period, exclamation, or question mark followed by whitespace
sentences = re.split(r'(?<=[.!?])\s+', text.strip())
# Filter out empty or extremely short sentences
return [s for s in sentences if len(s.strip()) > 3]
def fetch_all_topics():
print("Fetching topics from 'openalex-topics'...")
topics = []
size = 1000
offset = 0
with httpx.Client(timeout=60.0) as client:
while True:
payload = {
@@ -61,104 +71,42 @@ def fetch_all_topics():
print(f"Fetched {len(topics)} topics so far...")
if len(hits) < size:
break
print(f"Total topics fetched: {len(topics)}")
return topics
def update_mappings():
print("Checking/updating mappings for 'topicvectors'...")
mapping_payload = {
"properties": {
"display_name_vector": {
"type": "dense_vector",
"dims": 768,
"index": True,
"similarity": "cosine",
"index_options": {
"type": "int8_hnsw",
"m": 16,
"ef_construction": 100
}
},
"description_vector": {
"type": "dense_vector",
"dims": 768,
"index": True,
"similarity": "cosine",
"index_options": {
"type": "int8_hnsw",
"m": 16,
"ef_construction": 100
}
},
"keyword_vectors": {
"type": "nested",
"properties": {
"vector": {
"type": "dense_vector",
"dims": 768,
"index": True,
"similarity": "cosine",
"index_options": {
"type": "int8_hnsw",
"m": 16,
"ef_construction": 100
}
}
}
}
}
}
with httpx.Client(timeout=30.0) as client:
# Check if index exists
check_resp = client.get(f"{ELASTIC_URL}topicvectors", headers=headers)
if check_resp.status_code == 404:
print("Index 'topicvectors' does not exist. Creating it...")
create_payload = {
"mappings": mapping_payload
}
resp = client.put(f"{ELASTIC_URL}topicvectors", json=create_payload, headers=headers)
resp.raise_for_status()
else:
print("Index 'topicvectors' exists. Updating mappings...")
resp = client.put(f"{ELASTIC_URL}topicvectors/_mapping", json=mapping_payload, headers=headers)
resp.raise_for_status()
print("Mappings update process completed.")
def bulk_index_topics(topics, display_name_vectors, description_vectors, keyword_vectors_list):
def bulk_index_topics(topics, display_name_vectors, nested_description_vectors):
print("Bulk indexing vectorized topics into 'topicvectors'...")
batch_size = 500
with httpx.Client(timeout=60.0) as client:
for i in range(0, len(topics), batch_size):
batch_topics = topics[i:i+batch_size]
batch_name_vecs = display_name_vectors[i:i+batch_size]
batch_desc_vecs = description_vectors[i:i+batch_size]
batch_kw_vecs_list = keyword_vectors_list[i:i+batch_size]
batch_desc_vecs_list = nested_description_vectors[i:i+batch_size]
bulk_lines = []
for t, name_vec, desc_vec, kw_vecs in zip(batch_topics, batch_name_vecs, batch_desc_vecs, batch_kw_vecs_list):
for t, name_vec, desc_vecs in zip(batch_topics, batch_name_vecs, batch_desc_vecs_list):
source = t["_source"]
source.pop("siblings", None) # drop siblings field when making the copy
# Remove deprecated single vector if present
if "vector" in source:
del source["vector"]
# Assign name vector as a standard float list
source["display_name_vector"] = name_vec.tolist()
# Assign description vector
source["description_vector"] = desc_vec.tolist()
# Assign nested keyword vectors
source["keyword_vectors"] = [
{"vector": vec.tolist()} for vec in kw_vecs
# Assign nested description vectors as standard float lists
source["description_vectors"] = [
{"vector": vec.tolist()} for vec in desc_vecs
]
# Meta line
meta = {"index": {"_index": "topicvectors", "_id": t["_id"]}}
bulk_lines.append(json.dumps(meta))
# Document line
bulk_lines.append(json.dumps(source))
payload = "\n".join(bulk_lines) + "\n"
resp = client.post(
f"{ELASTIC_URL}_bulk",
@@ -176,61 +124,53 @@ def bulk_index_topics(topics, display_name_vectors, description_vectors, keyword
print(f"Indexed batch {i} to {i + len(batch_topics)}")
def main():
update_mappings()
topics = fetch_all_topics()
if not topics:
print("No topics found. Exiting.")
return
print(f"Initializing SentenceTransformer model '{MODEL_NAME}'...")
model = SentenceTransformer(MODEL_NAME)
# 1. Gather all texts to embed
keywords_by_topic = []
display_names = []
description_sentences_by_topic = []
all_texts_to_embed = []
for t in topics:
source = t["_source"]
name = source.get("display_name") or ""
display_names.append(name)
all_texts_to_embed.append(name)
desc = source.get("description") or ""
all_texts_to_embed.append(desc)
kws = source.get("keywords") or []
if not isinstance(kws, list):
kws = [kws] if kws else []
keywords_by_topic.append(kws)
all_texts_to_embed.extend(kws)
print(f"Embedding {len(all_texts_to_embed)} texts (display names, descriptions, and keywords)...")
sentences = split_into_sentences(desc)
description_sentences_by_topic.append(sentences)
all_texts_to_embed.extend(sentences)
print(f"Embedding {len(all_texts_to_embed)} texts (display names and description passages)...")
all_vectors = model.encode(all_texts_to_embed, show_progress_bar=True, batch_size=32)
# 2. Map embeddings back to topics
display_name_vectors = []
description_vectors = []
keyword_vectors_list = []
nested_description_vectors = []
vector_idx = 0
for idx, t in enumerate(topics):
# First vector is the display name
display_name_vectors.append(all_vectors[vector_idx])
vector_idx += 1
description_vectors.append(all_vectors[vector_idx])
vector_idx += 1
kws = keywords_by_topic[idx]
topic_kw_vecs = []
for _ in range(len(kws)):
topic_kw_vecs.append(all_vectors[vector_idx])
# Next N vectors are the description chunks
sentences = description_sentences_by_topic[idx]
topic_desc_vecs = []
for _ in range(len(sentences)):
topic_desc_vecs.append(all_vectors[vector_idx])
vector_idx += 1
keyword_vectors_list.append(topic_kw_vecs)
nested_description_vectors.append(topic_desc_vecs)
# Bulk index
bulk_index_topics(topics, display_name_vectors, description_vectors, keyword_vectors_list)
bulk_index_topics(topics, display_name_vectors, nested_description_vectors)
print("Done!")
if __name__ == "__main__":
-29
View File
@@ -1,29 +0,0 @@
{
"organizations": [
{
"id": "b3d61e33-ef7a-42bf-b4b5-4b96e153b67c",
"name": "The Super Admin Organization"
},
{
"name": "Universität Duisburg-Essen",
"openalex_instution_id": "https://openalex.org/I62318514"
},
{
"name": "Ruhr-Universität Bochum",
"openalex_instution_id": "https://openalex.org/I904495901"
},
{
"name": "TU Dortmund",
"openalex_instution_id": "https://openalex.org/I200332995"
}
],
"accounts": [
{
"email": "super@admin.com",
"password": "superadmin",
"name": "Super Admin",
"organization_id": "b3d61e33-ef7a-42bf-b4b5-4b96e153b67c",
"role": "SUPER_ADMIN"
}
]
}
+114
View File
@@ -0,0 +1,114 @@
{
"query": "localization",
"max_score": 23.237041,
"results": [
{
"topic_name": "Indoor and Outdoor Localization Technologies",
"score": 23.237041
},
{
"topic_name": "Robotics and Sensor-Based Localization",
"score": 21.511477
},
{
"topic_name": "Spectral Theory in Mathematical Physics",
"score": 14.039959
},
{
"topic_name": "Socioeconomic Development in MENA",
"score": 11.518878
},
{
"topic_name": "Electrical Fault Detection and Protection",
"score": 10.770052
},
{
"topic_name": "Machine Learning in Bioinformatics",
"score": 10.322677
},
{
"topic_name": "Software System Performance and Reliability",
"score": 10.112644
},
{
"topic_name": "Quantum many-body systems",
"score": 10.112644
},
{
"topic_name": "Random lasers and scattering media",
"score": 10.112644
},
{
"topic_name": "Insect Pheromone Research and Control",
"score": 9.910988
},
{
"topic_name": "Tactile and Sensory Interactions",
"score": 9.910988
},
{
"topic_name": "Handwritten Text Recognition Techniques",
"score": 9.910988
},
{
"topic_name": "Integrated Circuits and Semiconductor Failure Analysis",
"score": 9.910988
},
{
"topic_name": "Medical Imaging and Analysis",
"score": 9.7172165
},
{
"topic_name": "Microwave Imaging and Scattering Analysis",
"score": 9.7172165
},
{
"topic_name": "Neurology and Historical Studies",
"score": 9.7172165
},
{
"topic_name": "High-Velocity Impact and Material Behavior",
"score": 9.7172165
},
{
"topic_name": "Software Engineering Research",
"score": 9.530875
},
{
"topic_name": "Software Testing and Debugging Techniques",
"score": 9.530875
},
{
"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.351548
},
{
"topic_name": "Diffusion and Search Dynamics",
"score": 8.8518915
},
{
"topic_name": "Direction-of-Arrival Estimation Techniques",
"score": 5.968384
},
{
"topic_name": "Retinal Imaging and Analysis",
"score": 5.6107
},
{
"topic_name": "Radar Systems and Signal Processing",
"score": 4.721418
}
]
}
+22
View File
@@ -0,0 +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
}
]
}
-19
View File
@@ -1,19 +0,0 @@
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
ELASTICSEARCH_INSE_URL=https://inse.nes.uni-due.de/elastic
ELASTICSEARCH_INSE_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
# Sentence Transformers Configuration
SENTENCE_TRANSFORMERS_MODEL_NAME=paraphrase-multilingual-mpnet-base-v2
TOKEN_ISSUER_ID=inse
TOKEN_HMAC_KEY=9dd09c80dd0796fa24bd2007f4cf57fc28c9a38909b7e83bb2d73121c5bc69c7
+40
View File
@@ -0,0 +1,40 @@
# Database config
DATABASE_URL=sqlite:///path/to/local.db
DATABASE_DEBUG=false
DATABASE_INIT=true
# Authorization config
AUTH_DISABLED=false
AUTH_STANDALONE=true
AUTH_SECRET=your-auth-secret
# OpenAlex works search config
OPENALEX_WORKS_SEARCH_INDEX=your-openalex-index*
OPENALEX_WORKS_SEARCH_TIMEOUT_SECONDS=30.0
# OpenAlex public API config
OPENALEX_API_BASE_URL=https://api.openalex.org
OPENALEX_API_KEY=your-openalex-api-key
OPENALEX_API_TIMEOUT_SECONDS=30.0
# Patent Elasticsearch config
PATENT_ELASTICSEARCH_URL=https://example.com/patent-elastic
PATENT_ELASTICSEARCH_API_KEY=your-patent-elasticsearch-api-key
# LLM config
LLM_API_URL=https://example.com/llm-api
LLM_API_KEY=your-llm-api-key
LLM_MODEL=your-llm-model
# Elasticsearch config
ELASTICSEARCH_URL=https://example.com/elasticsearch
ELASTICSEARCH_API_KEY=your-elasticsearch-api-key
ELASTICSEARCH_INSE_URL=https://example.com/inse-elasticsearch
ELASTICSEARCH_INSE_API_KEY=your-inse-elasticsearch-api-key
# API metadata
ALLOWED_ORIGINS=["http://localhost:4200"]
SERVERS=[{"url":"http://localhost:8000","description":"Local development server"}]
# Logging
LOGGING_LEVEL=DEBUG
+66
View File
@@ -0,0 +1,66 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module contains the validation logic for
user names and passwords.
"""
import typing
import logging
from . import model
logger = logging.getLogger(__name__)
def _get_users() -> typing.List[model.User]:
''' Returns the list of users from the user configuration file. '''
try:
with open('../data/users.json') as file:
config = model.UserFile.model_validate_json(file.read())
return config.users
except Exception as e:
logger.error('Could not read user configuration file.', exc_info=e)
return []
def get_user(username: str) -> typing.Optional[model.User]:
''' Returns the user with the given username. '''
for user in _get_users():
if user.username == username:
return user
return None
def validate_user(username: str, password: str) -> typing.Optional[model.User]:
''' Validates the user with the given username and password. '''
user = get_user(username)
if user and user.password == password:
return user
return None
def create_user(username, password, email, institution, superadmin) -> typing.Optional[model.User]:
''' Adds a new user to the user configuration file. '''
users = _get_users()
if any(u.username == username for u in users):
logger.warning("Attempt to create duplicate user: %s", username)
return None
# Determine new IDs
next_account = max((u.account for u in users), default=0) + 1
next_org = max((u.organization for u in users), default=0) + 1
new_user = model.User(
username=username,
password=password,
email=email,
account=next_account,
organization=next_org,
organization_name=institution,
superadmin=superadmin
)
users.append(new_user)
user_file = model.UserFile(users=users)
try:
with open('../data/users.json', 'w') as file:
file.write(user_file.model_dump_json(indent=4))
return new_user
except Exception as e:
logger.error('Could not write user configuration file.', exc_info=e)
return None
+56
View File
@@ -0,0 +1,56 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Data models for the standalone account sub-app.
"""
from pydantic import BaseModel
from pydantic import Field
from pydantic import StrictInt
from typing import List, Optional
class User(BaseModel):
''' An entry in the user configuration file. '''
username: str = Field(description="The username of the user.")
password: str = Field(description="The password of the user.")
email: str = Field(description="The email of the user.")
account: StrictInt = Field(description="The account id of the user.")
organization: StrictInt = Field(description="The organization id of the user.")
organization_name: str = Field(description="The organization name of the user.")
superadmin: bool = Field(default=False, description="Indicates whether the user is a superadmin.")
class UserFile(BaseModel):
''' The data model for the file containing the user configuration. '''
users: List[User] = Field(default=[], description="The list of users.")
class AuthAccount(BaseModel):
i: int
l: str
o: int
e: str
on: str
class AuthScope(BaseModel):
t: str
a: AuthAccount
d: Optional[int] = None
r: List[str] = []
class IdentityGrant(BaseModel):
token_type: str
access_token: str
expires_in: int
scope: AuthScope
class AccessGrant(BaseModel):
token_type: str
access_token: str
expires_in: int
scope: AuthScope
refresh_token: str
+62
View File
@@ -0,0 +1,62 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module defines the security-related code.
"""
from typing import Optional
from typing import Dict
from typing import Literal
import jwt
import time
import logging
from .. import config
from .. import security
from . import model
logger = logging.getLogger(__name__)
def principal(id_token: str) -> Optional[security.Principal]:
''' Extracts the principal from the id token. '''
return security._extract_principal(id_token, config.settings.auth_secret, 'HS256', token_types=['ID', 'REFRESH'])
def id_token(user: model.User, exp: int) -> str:
''' Creates a new identity token for the specified user. '''
return _encode(_payload(user, 'ID', exp))
def access_token(user: model.User, exp: int) -> str:
''' Creates a new access token for the specified user. '''
return _encode(_payload(user, 'ACCESS', exp))
def refresh_token(user: model.User, exp: int) -> str:
''' Creates a new refresh token for the specified user. '''
return _encode(_payload(user, 'REFRESH', exp))
def _encode(payload: Dict[str, any]) -> str:
''' Creates a valid web token that encodes the contents with the symmetric key. '''
headers = {
"kid" : "sym",
}
return jwt.encode(payload, config.settings.auth_secret, algorithm="HS256", headers=headers)
def _payload(user: model.User, type: Literal['ID', 'ACCESS', 'REFRESH'], exp: int) -> str:
''' Creates the payload of the token for the specified user and token type. '''
now = int(time.time())
roles = [ 'SUPER_ADMIN' ] if user.superadmin else [ 'UNI_ADMIN' ]
payload = {
"iss" : "my-app",
"exp" : now + exp,
"iat" : now,
"nbf" : now,
"inse" : {
"t" : type,
"a" : {
"i" : user.account,
"l" : user.username,
"o" : user.organization
},
"d" : None,
"r" : roles if type == 'ACCESS' else []
}
}
return payload
+169
View File
@@ -0,0 +1,169 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Standalone account service that provides identity and access
token endpoints for authentication.
"""
import logging
import fastapi
import typing
from . import logic
from . import model
from . import security
from starlette.status import HTTP_400_BAD_REQUEST
from starlette.status import HTTP_403_FORBIDDEN
from starlette.status import HTTP_200_OK
from starlette.status import HTTP_500_INTERNAL_SERVER_ERROR
logger = logging.getLogger(__name__)
router = fastapi.APIRouter(
prefix="/inse-account",
tags=["INSE Account Service"],
responses={404: {"description": "Not found"}},
)
@router.post(
"/auth/id",
operation_id="getIdentityGrant",
responses={
HTTP_200_OK: {"model": model.IdentityGrant},
HTTP_400_BAD_REQUEST: {
"model": None,
"description": "Invalid request parameters.",
},
HTTP_403_FORBIDDEN: {
"model": None,
"description": "Account login not successful.",
},
HTTP_500_INTERNAL_SERVER_ERROR: {
"model": None,
"description": "Token generation failed.",
},
},
)
async def get_identity_grant(
username: typing.Annotated[str, fastapi.Form()],
password: typing.Annotated[str, fastapi.Form()],
):
user = logic.validate_user(username, password)
if user is None:
logger.info("Invalid login attempt (%s).", username)
raise fastapi.HTTPException(status_code=HTTP_403_FORBIDDEN)
try:
exp = 12 * 60 * 60
token = security.id_token(user, exp=exp)
account = model.AuthAccount(
i=user.account,
l=user.username,
o=user.organization,
e=user.email,
on=user.organization_name,
)
scope = model.AuthScope(t="ID", a=account, d=None, r=[])
grant = model.IdentityGrant(
token_type="bearer", access_token=token, expires_in=exp, scope=scope
)
logger.info("Identity token generated (%s).", username)
return grant
except Exception as e:
logger.error("Token generation failed (%s).", username, exc_info=e)
raise fastapi.HTTPException(status_code=HTTP_500_INTERNAL_SERVER_ERROR)
@router.post(
"/auth/access",
operation_id="getAccessGrant",
responses={
HTTP_200_OK: {"model": model.AccessGrant},
HTTP_400_BAD_REQUEST: {
"model": None,
"description": "Invalid request parameters.",
},
HTTP_403_FORBIDDEN: {"model": None, "description": "Access not allowed."},
HTTP_500_INTERNAL_SERVER_ERROR: {
"model": None,
"description": "Token generation failed.",
},
},
)
async def get_access_grant(
secret: typing.Annotated[str, fastapi.Form()],
account: typing.Annotated[int, fastapi.Form()],
organization: typing.Annotated[int, fastapi.Form()],
):
principal = security.principal(secret)
if principal is None:
logger.info("Invalid access attempt without principal (%s).", account)
raise fastapi.HTTPException(status_code=HTTP_400_BAD_REQUEST)
user = logic.get_user(principal.account.login)
if user is None:
logger.info("Invalid access attempt without user (%s).", account)
raise fastapi.HTTPException(status_code=HTTP_403_FORBIDDEN)
if user.organization != organization or user.account != account:
logger.info("Invalid personation attempt (%s).", account)
raise fastapi.HTTPException(status_code=HTTP_403_FORBIDDEN)
try:
exp = 10 * 60
token = security.access_token(user, exp=exp)
refresh = security.refresh_token(user, exp=exp)
auth_account = model.AuthAccount(
i=user.account,
l=user.username,
o=user.organization,
e=user.email,
on=user.organization_name,
)
scope = model.AuthScope(
t="ACCESS",
a=auth_account,
d=None,
r=["SUPER_ADMIN"] if user.superadmin else ["UNI_ADMIN"],
)
grant = model.AccessGrant(
token_type="bearer",
access_token=token,
expires_in=exp,
scope=scope,
refresh_token=refresh,
)
logger.info("Access token generated (%s).", user.username)
return grant
except Exception as e:
logger.error("Token generation failed (%s).", user.username, exc_info=e)
raise fastapi.HTTPException(status_code=HTTP_500_INTERNAL_SERVER_ERROR)
@router.post(
"/create",
operation_id="createUser",
responses={
HTTP_200_OK: {"model": model.User},
HTTP_400_BAD_REQUEST: {
"model": None,
"description": "User creation failed (e.g. duplicate username).",
},
HTTP_500_INTERNAL_SERVER_ERROR: {
"model": None,
"description": "Internal server error.",
},
},
)
async def create_user(
username: typing.Annotated[str, fastapi.Body()],
password: typing.Annotated[str, fastapi.Body()],
email: typing.Annotated[str, fastapi.Body()],
institution: typing.Annotated[str, fastapi.Body()],
superadmin: typing.Annotated[bool, fastapi.Body()] = False,
):
user = logic.create_user(username, password, email, institution, superadmin)
if user is None:
logger.info("User creation failed for (%s).", username)
raise fastapi.HTTPException(
status_code=HTTP_400_BAD_REQUEST,
detail="User creation failed. Username might already exist."
)
logger.info("User created successfully (%s).", username)
return user
@@ -1 +0,0 @@
@@ -1,51 +0,0 @@
import uuid
from typing import List, Optional
from pydantic import BaseModel, Field
from inse.auth.model import UserRole
class OrganizationProfile(BaseModel):
id: uuid.UUID
name: str
openalex_institution_id: Optional[str] = None
class AccountProfile(BaseModel):
id: uuid.UUID
email: str
name: str
role: UserRole
organization_id: uuid.UUID
organization_name: str
deleted: bool
is_current: bool = False
is_real_account: bool = False
is_impersonating: bool = False
class AccountPage(BaseModel):
items: List[AccountProfile]
total: int
page: int
page_size: int
class CreateAccountRequest(BaseModel):
email: str = Field(min_length=3)
name: str = Field(min_length=1)
role: UserRole = UserRole.USER
organization_id: uuid.UUID
password: str = Field(min_length=8)
openalex_person_id: Optional[str] = None
class UpdateAccountRequest(BaseModel):
email: Optional[str] = Field(default=None, min_length=3)
name: Optional[str] = Field(default=None, min_length=1)
role: Optional[UserRole] = None
organization_id: Optional[uuid.UUID] = None
password: Optional[str] = Field(default=None, min_length=8)
openalex_person_id: Optional[str] = None
deleted: Optional[bool] = None
@@ -1,125 +0,0 @@
import uuid
from typing import Optional
from fastapi import APIRouter, Depends, Query, Response, status
from sqlmodel import Session
from inse.auth import service as auth_service
from inse.auth.model import AccessToken
from inse.database import get_session
from inse.tags import Tags
from . import service
from .model import (
AccountPage,
AccountProfile,
CreateAccountRequest,
OrganizationProfile,
UpdateAccountRequest,
)
router = APIRouter(prefix="/api/accounts", tags=[Tags.AUTH])
@router.get(
"/me",
operation_id="getCurrentAccount",
response_model=AccountProfile,
)
async def get_current_account(
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> AccountProfile:
return service.get_current_account(session=session, access_token=access_token)
@router.get(
"",
operation_id="listAccounts",
response_model=AccountPage,
)
async def list_accounts(
page: int = Query(default=0, ge=0),
page_size: int = Query(default=25, ge=1, le=100),
offset: Optional[int] = Query(default=None, ge=0),
search: Optional[str] = Query(default=None),
organization_id: Optional[uuid.UUID] = Query(default=None),
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> AccountPage:
return service.list_accounts(
session=session,
access_token=access_token,
page=page,
page_size=page_size,
offset=offset,
search=search,
organization_id=organization_id,
)
@router.post(
"",
operation_id="createAccount",
response_model=AccountProfile,
status_code=status.HTTP_201_CREATED,
)
async def create_account(
payload: CreateAccountRequest,
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> AccountProfile:
return service.create_account(
session=session,
access_token=access_token,
payload=payload,
)
@router.get(
"/organizations",
operation_id="listAccountOrganizations",
response_model=list[OrganizationProfile],
)
async def list_organizations(
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> list[OrganizationProfile]:
return service.list_organizations(session=session, access_token=access_token)
@router.put(
"/{account_id}",
operation_id="updateAccount",
response_model=AccountProfile,
)
async def update_account(
account_id: uuid.UUID,
payload: UpdateAccountRequest,
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> AccountProfile:
return service.update_account(
session=session,
access_token=access_token,
account_id=account_id,
payload=payload,
)
@router.delete(
"/{account_id}",
operation_id="deleteAccount",
status_code=status.HTTP_204_NO_CONTENT,
)
async def delete_account(
account_id: uuid.UUID,
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> Response:
service.delete_account(
session=session,
access_token=access_token,
account_id=account_id,
)
return Response(status_code=status.HTTP_204_NO_CONTENT)
@@ -1,311 +0,0 @@
import uuid
from typing import Optional
from fastapi import HTTPException, status
from sqlmodel import Session, func, or_, select
from inse.auth import service as auth_service
from inse.auth.model import AccessToken, Account, Organization, UserRole
from .model import (
AccountPage,
AccountProfile,
CreateAccountRequest,
OrganizationProfile,
UpdateAccountRequest,
)
def _is_admin(role: UserRole) -> bool:
return role in {UserRole.SUPER_ADMIN, UserRole.ADMIN}
def _role_allowed_for_editor(editor_role: UserRole, role: UserRole) -> bool:
if editor_role == UserRole.SUPER_ADMIN:
return True
if editor_role == UserRole.ADMIN:
return role in {UserRole.MANAGER, UserRole.USER}
return False
def _account_to_profile(account: Account, token: AccessToken) -> AccountProfile:
organization_name = account.organization.name if account.organization else ""
return AccountProfile(
id=account.id,
email=account.email,
name=account.name,
role=account.role,
organization_id=account.organization_id,
organization_name=organization_name,
deleted=account.deleted,
is_current=account.id == token.effective_account_id,
is_real_account=account.id == token.real_account_id,
is_impersonating=token.is_impersonating(),
)
def _get_account_or_404(session: Session, account_id: uuid.UUID) -> Account:
account = session.get(Account, account_id)
if account is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Account not found.",
)
return account
def _ensure_account_in_editor_scope(account: Account, token: AccessToken) -> None:
if token.effective_role == UserRole.SUPER_ADMIN:
return
if (
token.effective_role == UserRole.ADMIN
and account.organization_id == token.effective_organization_id
):
return
if account.id == token.effective_account_id:
return
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Account is outside your scope.",
)
def _ensure_email_available(
session: Session,
email: str,
excluded_account_id: Optional[uuid.UUID] = None,
) -> None:
normalized_email = email.lower().strip()
if "@" not in normalized_email or "." not in normalized_email.rsplit("@", 1)[-1]:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="Invalid email address.",
)
statement = select(Account).where(Account.email == normalized_email)
if excluded_account_id is not None:
statement = statement.where(Account.id != excluded_account_id)
existing = session.exec(statement).first()
if existing is not None:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="Email address is already used by another account.",
)
def get_current_account(session: Session, access_token: AccessToken) -> AccountProfile:
account = _get_account_or_404(session, access_token.effective_account_id)
return _account_to_profile(account, access_token)
def list_accounts(
session: Session,
access_token: AccessToken,
page: int,
page_size: int,
offset: Optional[int] = None,
search: Optional[str] = None,
organization_id: Optional[uuid.UUID] = None,
) -> AccountPage:
if not _is_admin(access_token.effective_role):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Only admins can list accounts.",
)
statement = select(Account)
count_statement = select(func.count()).select_from(Account)
filters = []
if access_token.effective_role == UserRole.ADMIN:
filters.append(Account.organization_id == access_token.effective_organization_id)
elif organization_id is not None:
filters.append(Account.organization_id == organization_id)
if search:
pattern = f"%{search.lower().strip()}%"
filters.append(
or_(
func.lower(Account.name).like(pattern),
func.lower(Account.email).like(pattern),
)
)
for filter_expression in filters:
statement = statement.where(filter_expression)
count_statement = count_statement.where(filter_expression)
total = session.exec(count_statement).one()
effective_offset = offset if offset is not None else page * page_size
accounts = session.exec(
statement.order_by(Account.name).offset(effective_offset).limit(page_size)
).all()
return AccountPage(
items=[_account_to_profile(account, access_token) for account in accounts],
total=total,
page=page,
page_size=page_size,
)
def create_account(
session: Session,
access_token: AccessToken,
payload: CreateAccountRequest,
) -> AccountProfile:
if not _is_admin(access_token.effective_role):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Only admins can create accounts.",
)
if (
access_token.effective_role == UserRole.ADMIN
and payload.organization_id != access_token.effective_organization_id
):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Admins can only create accounts in their own organization.",
)
if not _role_allowed_for_editor(access_token.effective_role, payload.role):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="You cannot assign this role.",
)
organization = session.get(Organization, payload.organization_id)
if organization is None or organization.deleted:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Organization not found.",
)
email = payload.email.lower().strip()
_ensure_email_available(session, email)
account = Account(
email=email,
name=payload.name.strip(),
role=payload.role,
organization_id=payload.organization_id,
password_hash=auth_service._hash_password(payload.password),
openalex_person_id=payload.openalex_person_id,
)
session.add(account)
session.commit()
session.refresh(account)
return _account_to_profile(account, access_token)
def list_organizations(
session: Session,
access_token: AccessToken,
) -> list[OrganizationProfile]:
if access_token.effective_role == UserRole.SUPER_ADMIN:
organizations = session.exec(
select(Organization)
.where(Organization.deleted == False) # noqa: E712
.order_by(Organization.name)
).all()
elif access_token.effective_role == UserRole.ADMIN:
organization = session.get(Organization, access_token.effective_organization_id)
organizations = [organization] if organization and not organization.deleted else []
else:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
return [
OrganizationProfile(
id=organization.id,
name=organization.name,
openalex_institution_id=organization.openalex_institution_id,
)
for organization in organizations
]
def update_account(
session: Session,
access_token: AccessToken,
account_id: uuid.UUID,
payload: UpdateAccountRequest,
) -> AccountProfile:
account = _get_account_or_404(session, account_id)
_ensure_account_in_editor_scope(account, access_token)
is_self_update = account.id == access_token.effective_account_id
can_admin_update = _is_admin(access_token.effective_role)
if not can_admin_update and not is_self_update:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
if payload.email is not None:
email = payload.email.lower().strip()
_ensure_email_available(session, email, excluded_account_id=account.id)
account.email = email
if payload.name is not None:
account.name = payload.name.strip()
if payload.password is not None:
account.password_hash = auth_service._hash_password(payload.password)
account.epoch += 1
if payload.openalex_person_id is not None:
account.openalex_person_id = payload.openalex_person_id
if payload.role is not None:
if not can_admin_update:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
if not _role_allowed_for_editor(access_token.effective_role, payload.role):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="You cannot assign this role.",
)
account.role = payload.role
account.epoch += 1
if payload.organization_id is not None:
if access_token.effective_role != UserRole.SUPER_ADMIN:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
organization = session.get(Organization, payload.organization_id)
if organization is None or organization.deleted:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Organization not found.",
)
account.organization_id = payload.organization_id
account.epoch += 1
if payload.deleted is not None:
if not can_admin_update or is_self_update:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
account.deleted = payload.deleted
account.epoch += 1
session.add(account)
session.commit()
session.refresh(account)
return _account_to_profile(account, access_token)
def delete_account(
session: Session,
access_token: AccessToken,
account_id: uuid.UUID,
) -> None:
account = _get_account_or_404(session, account_id)
_ensure_account_in_editor_scope(account, access_token)
if (
not _is_admin(access_token.effective_role)
or account.id == access_token.effective_account_id
):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
account.deleted = True
account.epoch += 1
session.add(account)
session.commit()
@@ -1,29 +0,0 @@
import smtplib
from email.message import EmailMessage
def send_email(
recipient: str,
subject: str,
body: str,
smtp_server: str = "localhost",
smtp_port: int = 25,
sender: str = "no-reply@smartguide.local",
username: str | None = None,
password: str | None = None,
use_tls: bool = False,
):
msg = EmailMessage()
msg["From"] = sender
msg["To"] = recipient
msg["Subject"] = subject
msg.set_content(body)
with smtplib.SMTP(smtp_server, smtp_port) as server:
if use_tls:
server.starttls()
if username and password:
server.login(username, password)
server.send_message(msg)
-212
View File
@@ -1,212 +0,0 @@
import uuid
from datetime import datetime
from enum import StrEnum
from typing import List
from pydantic import BaseModel
from sqlmodel import Field, Relationship, SQLModel
class UserRole(StrEnum):
SUPER_ADMIN = "SUPER_ADMIN"
ADMIN = "ADMIN"
MANAGER = "MANAGER"
USER = "USER"
class TokenType(StrEnum):
ID_TOKEN = "ID"
REFRESH_TOKEN = "REFRESH"
ACCESS_TOKEN = "ACCESS"
class Durable(SQLModel):
deleted: bool = Field(
default=False,
nullable=False,
index=True,
description="Indicates whether the record is marked as deleted.",
)
class Organization(Durable, table=True):
id: uuid.UUID | None = Field(
default_factory=uuid.uuid4,
primary_key=True,
description="Unique identifier for the organization. Generated automatically if not provided.",
)
name: str = Field(
index=True,
unique=True,
nullable=False,
description="The unique name of the organization.",
)
openalex_institution_id: str | None = Field(
default=None,
index=True,
description="The OpenAlex ID of the institution associated with the organization.",
)
accounts: List["Account"] = Relationship(back_populates="organization")
class Account(Durable, table=True):
id: uuid.UUID | None = Field(
default_factory=uuid.uuid4,
primary_key=True,
description="Unique identifier for the account. Generated automatically if not provided.",
)
email: str = Field(
index=True,
unique=True,
nullable=False,
description="The email address associated with the account.",
)
name: str = Field(
index=True,
nullable=False,
description="The name of the account holder.",
)
openalex_person_id: str | None = Field(
default=None,
index=True,
description="The OpenAlex ID of the person associated with the account.",
)
epoch: int = Field(
default=0,
nullable=False,
description="The epoch value for the account. Used for versioning of tokens.",
)
password_hash: str = Field(
index=False,
nullable=False,
description="The hashed password for the account using Argon2id algorithm.",
# https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html
)
organization_id: uuid.UUID = Field(
foreign_key="organization.id",
nullable=False,
description="The unique identifier of the organization strictly associated with this account.",
)
role: UserRole = Field(
default=UserRole.USER,
index=True,
nullable=False,
description="The specific role this account holds within its organization.",
)
organization: Organization = Relationship(back_populates="accounts")
class Secret(SQLModel, table=True):
id: uuid.UUID | None = Field(
default_factory=uuid.uuid4,
primary_key=True,
description="Unique identifier for the secret. Generated automatically if not provided.",
)
account_id: uuid.UUID = Field(
foreign_key="account.id",
unique=True, # Ensure that each account can have only one associated secret
nullable=False,
description="The unique identifier of the account associated with this secret.",
)
secret_value: str = Field(
index=False,
nullable=False,
description="The actual secret value. This should be stored securely and encrypted.",
)
expires_at: datetime = Field(
index=True,
nullable=False,
description="The timestamp indicating when the secret will expire.",
)
class Token(BaseModel):
token_type: TokenType = Field(
description="The type of the token (ID, Refresh, or Access).",
)
real_account_id: uuid.UUID = Field(
nullable=False,
description="The unique identifier of the real account associated with this token.",
)
expires_at: datetime = Field(
index=True,
nullable=False,
description="The timestamp indicating when the token will expire.",
)
epoch: int = Field(
default=0,
nullable=False,
description="The epoch value for the token. Used for versioning of tokens.",
)
user_fingerprint_hash: str = Field(
index=True,
nullable=False,
description="A hash of the user's fingerprint to ensure the token is used by the same user.",
)
raw_token: str = Field(
index=False,
nullable=False,
description="The raw token string.",
)
class IdToken(Token):
token_type: TokenType = Field(
default=TokenType.ID_TOKEN,
const=True,
description="The type of the token, which is always ID_TOKEN for this class.",
)
class AccessToken(Token):
token_type: TokenType = Field(
default=TokenType.ACCESS_TOKEN,
const=True,
description="The type of the token, which is always ACCESS_TOKEN for this class.",
)
effective_account_id: uuid.UUID = Field(
nullable=False,
description="The unique identifier of the effective account associated with this access token. This may differ from the real account ID due to account impersonation.",
)
effective_role: UserRole = Field(
default=UserRole.USER,
index=True,
nullable=False,
description="The specific role this access token grants within its organization.",
)
effective_organization_id: uuid.UUID = Field(
nullable=False,
description="The unique identifier of the organization associated with this access token.",
)
def is_impersonating(self) -> bool:
"""Determine if the access token is being used for impersonation.
Returns:
bool: True if the effective account ID differs from the real account ID, indicating impersonation; False otherwise.
"""
return self.effective_account_id != self.real_account_id
class RefreshToken(AccessToken):
token_type: TokenType = Field(
default=TokenType.REFRESH_TOKEN,
const=True,
description="The type of the token, which is always REFRESH_TOKEN for this class.",
)
class LoginResponse(BaseModel):
id_token: IdToken = Field(description="The ID token issued upon successful login.")
class AccessResponse(BaseModel):
access_token: AccessToken = Field(
description="The access token issued upon successful authentication."
)
refresh_token: RefreshToken = Field(
description="The refresh token issued alongside the access token for obtaining new access tokens."
)
-162
View File
@@ -1,162 +0,0 @@
import logging
from typing import Annotated
import uuid
from fastapi import APIRouter, Body, Depends, Response, status
from sqlmodel import Session
from inse.tags import Tags
import inse.auth.service as auth_service
from inse.database import SessionDep, get_session
from inse.auth.model import (
AccessResponse,
AccessToken,
IdToken,
LoginResponse,
RefreshToken,
)
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/auth/v2", tags=[Tags.AUTH])
@router.get("/health")
async def health_check():
return {"status": "ok"}
@router.post(
"/request-otk",
summary="Request One-Time Key",
description="Request a one-time key (OTK) for authentication using email and password.",
operation_id="requestOtk",
responses={
status.HTTP_200_OK: {"description": "One-time key requested successfully."}
},
)
async def request_otk(
session: SessionDep,
email: Annotated[str, Body(description="User's email address")],
password: Annotated[str, Body(description="User's password")],
):
return auth_service.request_otk(session=session, email=email, password=password)
@router.post(
"/login",
summary="Login with One-Time Key",
description="Login using a one-time key (OTK) sent to the user's email.",
operation_id="login",
responses={status.HTTP_200_OK: {"description": "Login successful."}},
)
async def login(
session: SessionDep,
response: Response,
account_id: Annotated[uuid.UUID, Body(description="User's account ID")],
email_code: Annotated[
str, Body(embed=True, description="One-time code sent to user's email")
],
) -> LoginResponse:
return auth_service.login(
session=session, response=response, account_id=account_id, email_code=email_code
)
@router.post(
"/access",
summary="Get Access Token",
description="Retrieve an access token for the authenticated user.",
operation_id="getAccessToken",
responses={
status.HTTP_200_OK: {"description": "Access token retrieved successfully."}
},
)
async def get_action_tokens(
response: Response,
session: SessionDep,
real_account_id: Annotated[uuid.UUID, Body(description="User's account ID")],
effective_account_id: Annotated[
uuid.UUID, Body(description="Effective account ID for the access token")
],
id_token: Annotated[IdToken, auth_service.CurrentUserIdTokenPayloadDep],
) -> AccessResponse:
logger.debug(
"Generating access token for real_account_id=%s, effective_account_id=%s, id_token=%s",
real_account_id,
effective_account_id,
id_token,
)
return auth_service.get_access_token(
response=response,
session=session,
real_account_id=real_account_id,
effective_account_id=effective_account_id,
id_token=id_token,
)
@router.post(
"/refresh",
summary="Refresh Access Token",
description="Refresh the access token using a valid refresh token.",
operation_id="refreshAccessToken",
responses={
status.HTTP_200_OK: {"description": "Access token refreshed successfully."}
},
)
async def refresh_access_token(
refresh_token: Annotated[
RefreshToken, auth_service.CurrentUserRefreshTokenPayloadDep
],
) -> AccessToken:
return auth_service.refresh_access_token(refresh_token=refresh_token)
@router.post(
"/logout",
summary="Logout",
description="Logout the authenticated user.",
operation_id="logout",
responses={status.HTTP_200_OK: {"description": "Logout successful."}},
)
async def logout(
session: Annotated[Session, Depends(get_session)],
access_token: Annotated[
AccessToken,
auth_service.CurrentUserAccessTokenPayloadDep,
],
):
return auth_service.logout(session=session, access_token=access_token)
@router.post(
"/change-password",
summary="Change Password",
description="Change the user's password and invalidate existing tokens.",
operation_id="changePassword",
responses={status.HTTP_200_OK: {"description": "Password changed successfully."}},
)
async def change_password(
session: Annotated[Session, Depends(get_session)],
current_password: Annotated[
str,
Body(description="Current password"),
],
new_password: Annotated[
str,
Body(description="New password", min_length=8),
],
access_token: Annotated[
AccessToken,
auth_service.CurrentUserAccessTokenPayloadDep,
],
):
return auth_service.change_password(
session=session,
access_token=access_token,
current_password=current_password,
new_password=new_password,
)
File diff suppressed because it is too large Load Diff
@@ -1,517 +0,0 @@
import inse.config as config_module
import uuid
import pytest
from sqlmodel import Session, SQLModel, create_engine, select
from fastapi import Response, HTTPException
import datetime as _dt
from datetime import timedelta
from inse.auth import service as auth_service
from inse.auth.model import (
Account,
Organization,
Secret,
IdToken,
AccessToken,
RefreshToken,
UserRole,
)
@pytest.fixture()
def settings_backup():
orig = config_module.get_settings()
backup = config_module.Settings(**orig.model_dump())
yield backup
for k, v in backup.model_dump().items():
setattr(config_module.settings, k, v)
@pytest.fixture()
def in_memory_session():
engine = create_engine(
"sqlite:///:memory:", connect_args={"check_same_thread": False}
)
SQLModel.metadata.create_all(engine)
with Session(engine) as session:
yield session
def create_org_and_account(
session: Session, email: str, password: str, role=UserRole.USER
):
org = Organization(name=f"Test Org {email}")
session.add(org)
session.flush()
assert org.id is not None
pwd_hash = auth_service._hash_password(password)
acc = Account(
email=email,
name="Tester",
organization_id=org.id,
password_hash=pwd_hash,
role=role,
)
session.add(acc)
session.commit()
session.refresh(acc)
return org, acc
def test_hash_and_verify_password():
pw = "s3cret-password"
h = auth_service._hash_password(pw)
assert auth_service._verify_password(pw, h) is True
assert auth_service._verify_password("wrong", h) is False
def test_request_otk_and_login_flow(in_memory_session, settings_backup):
config_module.settings.token_hmac_key = "test-hmac-key"
config_module.settings.token_issuer_id = "test-issuer"
config_module.settings.skip_otk_validation = False
email = "user@example.com"
password = "hunter2"
org, acc = create_org_and_account(in_memory_session, email, password)
assert acc.id is not None
resp = auth_service.request_otk(in_memory_session, email, password)
assert resp["status"] == "ok"
assert resp["account_id"] == str(acc.id)
secret = in_memory_session.exec(
select(Secret).where(Secret.account_id == acc.id)
).first()
assert secret is not None
response = Response()
login_result = auth_service.login(
in_memory_session, response, acc.id, secret.secret_value
)
assert isinstance(login_result.id_token, IdToken)
assert login_result.id_token.real_account_id == acc.id
assert login_result.id_token.user_fingerprint_hash is not None
def test_token_build_verify_and_fp_checks(in_memory_session, settings_backup):
config_module.settings.token_hmac_key = "another-key"
config_module.settings.token_issuer_id = "issuer-2"
email = "fp@example.com"
password = "pw"
org, acc = create_org_and_account(in_memory_session, email, password)
assert acc.id is not None
response = Response()
id_token = auth_service._build_id_token(response, acc.id, acc.epoch)
assert isinstance(id_token, IdToken)
cookie_header = None
for header, value in response.headers.items():
if header.lower() == "set-cookie":
cookie_header = value
break
assert cookie_header is not None
cookie_value = cookie_header.split("=")[1].split(";")[0]
class DummyReq:
def __init__(self, cookies):
self.cookies = cookies
req = DummyReq({auth_service.ID_FP_COOKIE_KEY: cookie_value})
payload = auth_service._verify_fp_token(
request=req,
cookie_key=auth_service.ID_FP_COOKIE_KEY,
token=id_token.raw_token,
session=in_memory_session,
)
assert payload[auth_service.REAL_ACCOUNT_ID_KEY] == str(acc.id)
with pytest.raises(Exception):
auth_service._verify_fp_token(
request=DummyReq({}),
cookie_key=auth_service.ID_FP_COOKIE_KEY,
token=id_token.raw_token,
session=in_memory_session,
)
def test_access_and_refresh_token_flow(in_memory_session, settings_backup):
config_module.settings.token_hmac_key = "flow-key"
config_module.settings.token_issuer_id = "flow-issuer"
email = "flow@example.com"
password = "pwflow"
org, acc = create_org_and_account(
in_memory_session, email, password, role=UserRole.ADMIN
)
assert acc.id is not None
response = Response()
id_token = auth_service._build_id_token(response, acc.id, acc.epoch)
access_response = auth_service.get_access_token(
response, in_memory_session, id_token, acc.id
)
assert isinstance(access_response.access_token, AccessToken)
assert isinstance(access_response.refresh_token, RefreshToken)
refreshed = auth_service.refresh_access_token(access_response.refresh_token)
assert isinstance(refreshed, AccessToken)
assert refreshed.real_account_id == access_response.access_token.real_account_id
def test_logout_and_change_password(in_memory_session, settings_backup):
config_module.settings.token_hmac_key = "logout-key"
config_module.settings.token_issuer_id = "logout-issuer"
email = "logout@example.com"
password = "oldpw"
org, acc = create_org_and_account(in_memory_session, email, password)
assert acc.id is not None
response = Response()
id_token = auth_service._build_id_token(response, acc.id, acc.epoch)
access_resp = auth_service.get_access_token(
response, in_memory_session, id_token, acc.id
)
before_epoch = acc.epoch
out = auth_service.logout(in_memory_session, access_resp.access_token)
assert out["status"] == "ok"
in_memory_session.refresh(acc)
assert acc.epoch == before_epoch + 1
new_pw = "newpw123"
acc.password_hash = auth_service._hash_password(password)
in_memory_session.add(acc)
in_memory_session.commit()
change_out = auth_service.change_password(
in_memory_session, access_resp.access_token, password, new_pw
)
assert change_out["status"] == "ok"
in_memory_session.refresh(acc)
assert auth_service._verify_password(new_pw, acc.password_hash)
def test_request_otk_invalid_credentials(in_memory_session, settings_backup):
email = "nope@example.com"
password = "rightpw"
org, acc = create_org_and_account(in_memory_session, email, password)
assert acc.id is not None
with pytest.raises(HTTPException):
auth_service.request_otk(in_memory_session, email, "wrongpw")
def test_login_with_expired_secret(in_memory_session, settings_backup):
config_module.settings.token_hmac_key = "expired-key"
config_module.settings.token_issuer_id = "expired-issuer"
config_module.settings.skip_otk_validation = False
email = "expired@example.com"
password = "pw"
org, acc = create_org_and_account(in_memory_session, email, password)
assert acc.id is not None
expired_at = _dt.datetime.now(_dt.timezone.utc) - timedelta(minutes=10)
secret = Secret(account_id=acc.id, secret_value="000000", expires_at=expired_at)
in_memory_session.add(secret)
in_memory_session.commit()
with pytest.raises(HTTPException):
auth_service.login(in_memory_session, Response(), acc.id, "000000")
def test_verify_fp_token_cookie_mismatch(in_memory_session, settings_backup):
config_module.settings.token_hmac_key = "cookie-key"
config_module.settings.token_issuer_id = "cookie-issuer"
email = "cookie@example.com"
password = "pw"
org, acc = create_org_and_account(in_memory_session, email, password)
assert acc.id is not None
response = Response()
id_token = auth_service._build_id_token(response, acc.id, acc.epoch)
cookie_header = None
for header, value in response.headers.items():
if header.lower() == "set-cookie":
cookie_header = value
break
cookie_value = cookie_header.split("=")[1].split(";")[0] # type: ignore
class DummyReq:
def __init__(self, cookies):
self.cookies = cookies
with pytest.raises(HTTPException):
auth_service._verify_fp_token(
request=DummyReq({auth_service.ID_FP_COOKIE_KEY: "badcookie"}), # type: ignore
cookie_key=auth_service.ID_FP_COOKIE_KEY,
token=id_token.raw_token,
session=in_memory_session,
)
def test_token_epoch_mismatch(in_memory_session, settings_backup):
config_module.settings.token_hmac_key = "epoch-key"
config_module.settings.token_issuer_id = "epoch-issuer"
email = "epoch@example.com"
password = "pw"
org, acc = create_org_and_account(in_memory_session, email, password)
assert acc.id is not None
response = Response()
id_token = auth_service._build_id_token(response, acc.id, acc.epoch)
cookie_header = None
for header, value in response.headers.items():
if header.lower() == "set-cookie":
cookie_header = value
break
cookie_value = cookie_header.split("=")[1].split(";")[0] # type: ignore
class DummyReq:
def __init__(self, cookies):
self.cookies = cookies
acc.epoch += 1
in_memory_session.add(acc)
in_memory_session.commit()
with pytest.raises(HTTPException):
auth_service._verify_fp_token(
request=DummyReq({auth_service.ID_FP_COOKIE_KEY: cookie_value}), # type: ignore
cookie_key=auth_service.ID_FP_COOKIE_KEY,
token=id_token.raw_token,
session=in_memory_session,
)
def test_invalid_token_signature_raises(in_memory_session, settings_backup):
config_module.settings.token_hmac_key = "sig-key"
config_module.settings.token_issuer_id = "sig-issuer"
email = "sig@example.com"
password = "pw"
org, acc = create_org_and_account(in_memory_session, email, password)
assert acc.id is not None
response = Response()
id_token = auth_service._build_id_token(response, acc.id, acc.epoch)
cookie_header = None
for header, value in response.headers.items():
if header.lower() == "set-cookie":
cookie_header = value
break
cookie_value = cookie_header.split("=")[1].split(";")[0] # type: ignore
class DummyReq:
def __init__(self, cookies):
self.cookies = cookies
bad_token = id_token.raw_token + "x"
with pytest.raises(HTTPException):
auth_service._verify_fp_token(
request=DummyReq({auth_service.ID_FP_COOKIE_KEY: cookie_value}), # type: ignore
cookie_key=auth_service.ID_FP_COOKIE_KEY,
token=bad_token,
session=in_memory_session,
)
def test_impersonation_rules(in_memory_session, settings_backup):
config_module.settings.token_hmac_key = "imp-key"
config_module.settings.token_issuer_id = "imp-issuer"
org_a, real_acc = create_org_and_account(in_memory_session, "real@a.test", "pw")
assert real_acc.id is not None
org_b, eff_acc = create_org_and_account(in_memory_session, "eff@b.test", "pw")
assert eff_acc.id is not None
response = Response()
id_token = auth_service._build_id_token(response, real_acc.id, real_acc.epoch)
with pytest.raises(HTTPException):
auth_service.get_access_token(
response,
in_memory_session,
id_token,
real_acc.id,
effective_account_id=eff_acc.id,
)
real_acc.role = UserRole.SUPER_ADMIN
in_memory_session.add(real_acc)
in_memory_session.commit()
access_resp = auth_service.get_access_token(
response,
in_memory_session,
id_token,
real_acc.id,
effective_account_id=eff_acc.id,
)
assert isinstance(access_resp.access_token, AccessToken)
def test_otk_regeneration_and_reuse(in_memory_session, settings_backup):
config_module.settings.token_hmac_key = "regen-key"
config_module.settings.token_issuer_id = "regen-issuer"
config_module.settings.skip_otk_validation = False
email = "regen@example.com"
password = "pw"
org, acc = create_org_and_account(in_memory_session, email, password)
assert acc.id is not None
auth_service.request_otk(in_memory_session, email, password)
secret1 = in_memory_session.exec(
select(Secret).where(Secret.account_id == acc.id)
).first()
assert secret1 is not None
first_value = secret1.secret_value
auth_service.request_otk(in_memory_session, email, password)
secret2 = in_memory_session.exec(
select(Secret).where(Secret.account_id == acc.id)
).first()
assert secret2 is not None
assert first_value != secret2.secret_value
with pytest.raises(HTTPException):
auth_service.login(in_memory_session, Response(), acc.id, first_value)
login_res = auth_service.login(
in_memory_session, Response(), acc.id, secret2.secret_value
)
assert isinstance(login_res.id_token, IdToken)
def test_otk_deleted_after_login(in_memory_session, settings_backup):
config_module.settings.token_hmac_key = "del-key"
config_module.settings.token_issuer_id = "del-issuer"
config_module.settings.skip_otk_validation = False
email = "single@example.com"
password = "pw"
org, acc = create_org_and_account(in_memory_session, email, password)
assert acc.id is not None
auth_service.request_otk(in_memory_session, email, password)
secret = in_memory_session.exec(
select(Secret).where(Secret.account_id == acc.id)
).first()
assert secret is not None
auth_service.login(in_memory_session, Response(), acc.id, secret.secret_value)
post = in_memory_session.exec(
select(Secret).where(Secret.account_id == acc.id)
).first()
assert post is None
def test_access_token_fp_mismatch(in_memory_session, settings_backup):
config_module.settings.token_hmac_key = "act-key"
config_module.settings.token_issuer_id = "act-issuer"
email = "act@example.com"
password = "pw"
org, acc = create_org_and_account(in_memory_session, email, password)
assert acc.id is not None
response = Response()
raw = auth_service._set_act_fp_cookie(response)
access_token = auth_service._build_access_token(
real_account_id=acc.id,
effective_account_id=acc.id,
effective_role=acc.role,
effective_organization_id=acc.organization_id,
epoch=acc.epoch,
user_fingerprint_hash=raw,
)
class DummyReq:
def __init__(self, cookies):
self.cookies = cookies
with pytest.raises(HTTPException):
auth_service._verify_fp_token(
request=DummyReq({auth_service.ACT_FP_COOKIE_KEY: "wrongcookie"}), # type: ignore
cookie_key=auth_service.ACT_FP_COOKIE_KEY,
token=access_token.raw_token,
session=in_memory_session,
)
def test_expired_jwt_token_raises(in_memory_session, settings_backup):
config_module.settings.token_hmac_key = "exp-key"
config_module.settings.token_issuer_id = "exp-issuer"
email = "exp@example.com"
password = "pw"
org, acc = create_org_and_account(in_memory_session, email, password)
assert acc.id is not None
response = Response()
cookie_raw = auth_service._set_id_fp_cookie(response)
past = _dt.datetime.now(_dt.timezone.utc) - timedelta(minutes=5)
payload = {
auth_service.REAL_ACCOUNT_ID_KEY: str(acc.id),
auth_service.EPOCH_KEY: acc.epoch,
auth_service.USER_FINGERPRINT_HASH_KEY: cookie_raw,
}
bad_token = auth_service._build_token(
payload=payload,
expiration_datetime=past,
token_type=auth_service.TokenType.ID_TOKEN,
)
class DummyReq:
def __init__(self, cookies):
self.cookies = cookies
with pytest.raises(HTTPException):
auth_service._verify_fp_token(
request=DummyReq(
{
auth_service.ID_FP_COOKIE_KEY: response.headers["set-cookie"]
.split("=")[1]
.split(";")[0]
}
), # type: ignore
cookie_key=auth_service.ID_FP_COOKIE_KEY,
token=bad_token,
session=in_memory_session,
)
def test_missing_hmac_key_raises_value_error(settings_backup):
orig = config_module.get_settings()
saved = orig.token_hmac_key
config_module.settings.token_hmac_key = None
with pytest.raises(ValueError):
auth_service._build_token(
payload={},
expiration_datetime=_dt.datetime.now(_dt.timezone.utc),
token_type=auth_service.TokenType.ID_TOKEN,
)
config_module.settings.token_hmac_key = saved
def test_get_account_epoch_not_found(in_memory_session):
random_id = uuid.uuid4()
with pytest.raises(Exception):
auth_service._get_account_epoch(in_memory_session, random_id)
@@ -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,141 @@
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 config.settings.openalex_works_search_base_url
).rstrip("/")
self.api_key = (
api_key
if api_key is not None
else config.settings.elasticsearch_api_key
or config.settings.openalex_works_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"}}],
}
@@ -28,7 +28,7 @@ class CompanyConnectionsSearchClient:
api_key
if api_key is not None
else config.settings.elasticsearch_api_key
)
)
self.openalex_index = openalex_index
self.handelsregister_index = handelsregister_index
self.timeout = timeout
@@ -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)
+10 -23
View File
@@ -7,7 +7,7 @@ that can be adjusted via environment variables.
from functools import lru_cache
import logging
from typing import Dict, List, Literal, Optional
from typing import Dict, List, Optional
from pydantic_settings import BaseSettings, SettingsConfigDict
from dotenv import load_dotenv
@@ -26,6 +26,7 @@ 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
# IMPORTANT: wildcard * needed to query all work indices
openalex_works_search_index: str = "openalex-works*"
openalex_works_search_timeout_seconds: float = 30.0
@@ -34,20 +35,18 @@ class Settings(BaseSettings):
openalex_api_key: Optional[str] = None
openalex_api_timeout_seconds: float = 30.0
# Patent Elasticsearch config
# Patent elasticsearch config
patent_elasticsearch_url: str = "https://inse.nes.uni-due.de/elastic"
patent_elasticsearch_api_key: Optional[str] = None
patent_elasticsearch_api_key: str = ""
# LLM config
llm_api_url: Optional[str] = None
llm_api_key: Optional[str] = None
llm_model: Optional[str] = None
# Sentence Transformers config
sentence_transformers_model_name: str = "paraphrase-multilingual-mpnet-base-v2"
# Elasticsearch config
elasticsearch_url: str = "https://project.nes.uni-due.de/elastic"
# elasticsearch config
elasticsearch_url: Optional[str] = None
elasticsearch_api_key: Optional[str] = None
elasticsearch_inse_url: Optional[str] = None
elasticsearch_inse_api_key: Optional[str] = None
@@ -60,23 +59,11 @@ 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"
environment: Literal["dev", "prod"] = "dev"
token_issuer_id: Optional[str] = None
token_hmac_key: Optional[str] = None
skip_otk_validation: bool = True
# SMTP / email config
send_otk_email: bool = False
smtp_server: str = "localhost"
smtp_port: int = 25
smtp_sender: str = "no-reply@smartguide.local"
smtp_username: Optional[str] = None
smtp_password: Optional[str] = None
smtp_use_tls: bool = False
settings = Settings()
+22 -30
View File
@@ -1,33 +1,25 @@
from typing import Annotated
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module contains the code to bootstrap the database
using our schema and sqlalchemy.
"""
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from . import schema
from . import config
from fastapi import Depends
from sqlmodel import SQLModel, Session, create_engine
engine = create_engine(config.settings.database_url, echo=config.settings.database_debug)
from inse import config
if config.settings.database_init:
schema.Base.metadata.create_all(engine)
settings = config.get_settings()
connect_args = {"check_same_thread": False}
engine = create_engine(
url=settings.database_url,
echo=settings.database_debug,
connect_args=connect_args,
)
def create_db_and_tables():
"""Creates the database and tables based on the SQLModel metadata."""
SQLModel.metadata.create_all(engine)
def get_session():
"""Yields a database session for use in FastAPI endpoints.
Yields:
Session: A SQLModel session connected to the database.
"""
with Session(engine) as session:
yield session
SessionDep = Annotated[Session, Depends(get_session)]
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
def get():
''' Returns a database connection and closes it when done. '''
db = SessionLocal()
try:
yield db
finally:
db.close()
-5
View File
@@ -1,8 +1,3 @@
class NotFoundException(Exception):
"""Exception raised when a requested resource is not found.
Args:
Exception (_type_): Base exception class.
"""
def __init__(self, message: str):
super().__init__(message)
@@ -20,21 +20,13 @@ class InstitutionsSearchClient:
"""
pass
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.
def get_institution_by_id(self, raw_institution_id: str) -> Institution:
"""
Retrieves a single institution by its OpenAlex ID from the local Elasticsearch cluster.
"""
query = {
"match": {
"id": f"https://openalex.org/{raw_oa_institution_id.upper()}",
"id": f"https://openalex.org/{raw_institution_id.upper()}",
}
}
@@ -43,13 +35,13 @@ class InstitutionsSearchClient:
hits = res.get("hits", {}).get("hits", [])
if not hits:
raise NotFoundException(
f"Institution with ID '{raw_oa_institution_id}' not found."
f"Institution with ID '{raw_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."
f"Institution with ID '{raw_institution_id}' could not be parsed."
)
return institution
@@ -216,39 +208,37 @@ 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,
}
}
},
],
"minimum_should_match": 1,
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
}
})
filter_queries = []
@@ -288,41 +278,35 @@ class InstitutionsSearchClient:
return [Institution.from_dict(hit["_source"]) for hit in hits]
def get_institution_aliases_by_oa_institution_id(
self, raw_oa_institution_id: str
) -> List[str]:
def get_institution_aliases_by_id(self, raw_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_oa_institution_id (str): The raw OpenAlex institution ID for which to retrieve aliases.
raw_institution_id (str): The raw institution ID for which to retrieve aliases.
Returns:
List[str]: A list of aliases for the given institution ID.
"""
institution = self.get_institution_by_id(raw_oa_institution_id)
institution = self.get_institution_by_id(raw_institution_id)
aliases = list(
self.augment_aliases(set(institution.display_name_alternatives or []))
| self.get_predefined_institution_aliases(raw_oa_institution_id)
| self.get_predefined_institution_aliases(raw_institution_id)
)
logger.debug(
"Retrieved aliases for institution_id=%s: %s",
raw_oa_institution_id,
aliases,
"Retrieved aliases for institution_id=%s: %s", raw_institution_id, aliases
)
return aliases
def get_predefined_institution_aliases(
self, raw_oa_institution_id: str
) -> Set[str]:
def get_predefined_institution_aliases(self, raw_institution_id: str) -> Set[str]:
"""Get predefined aliases for a given institution ID.
Args:
raw_oa_institution_id (str): The raw OpenAlex institution ID for which to retrieve predefined aliases.
raw_institution_id (str): The raw institution ID for which to retrieve predefined aliases.
Returns:
Set[str]: A set of predefined aliases for the given institution ID.
"""
raw_oa_institution_id = raw_oa_institution_id.upper()
raw_institution_id = raw_institution_id.upper()
predefined_aliases = {
"I62318514": [
"universität duisburg-essen",
@@ -333,9 +317,7 @@ class InstitutionsSearchClient:
],
}
return self.augment_aliases(
set(predefined_aliases.get(raw_oa_institution_id, []))
)
return self.augment_aliases(set(predefined_aliases.get(raw_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.
@@ -425,80 +407,3 @@ class InstitutionsSearchClient:
"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
@@ -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.",
)
@@ -0,0 +1,207 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
REST API for OpenAlex institutions.
"""
from functools import lru_cache
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.models.openalex.institution import Institution
from inse.institutions.model import InstitutionPage
from . import logic
from inse.institutions.institutions_search_client import InstitutionsSearchClient
router = APIRouter(prefix="/api/inse-service/institutions", tags=[Tags.INSTITUTIONS])
@lru_cache
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",
response_model=AutocompleteResponse,
response_model_exclude_none=True,
summary="Returns institution options for autocomplete inputs.",
)
async def autocomplete_institutions(
query: Annotated[
str,
Query(
description="Institution search text, for example 'Duisburg Essen'.",
min_length=1,
),
],
country_code: Annotated[
str | None,
Query(alias="countryCode", description="Optional ISO country code filter."),
] = None,
institution_type: Annotated[
str | None,
Query(alias="type", description="Optional institution type filter."),
] = None,
limit: Annotated[
int,
Query(description="Maximum number of autocomplete options.", ge=1, le=25),
] = 10,
client: Annotated[
InstitutionsSearchClient, Depends(get_institutions_search_client)
] = None,
):
return await logic.autocomplete_institutions(
query=query,
country_code=country_code,
institution_type=institution_type,
limit=limit,
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(
"",
operation_id="listInstitutions",
response_model=InstitutionsListResponse,
response_model_exclude_none=True,
summary="Returns a list of OpenAlex institutions.",
)
async def list_institutions(
search: Annotated[
str | None,
Query(description="Full-text search, for example 'Duisburg Essen'."),
] = None,
filter: Annotated[
str | None,
Query(
description="OpenAlex filter, for example 'country_code:DE,type:education'."
),
] = None,
sort: Annotated[
str | None,
Query(description="Sort field, for example 'works_count:desc'."),
] = "works_count:desc",
group_by: Annotated[
str | None,
Query(description="OpenAlex group_by field, for example 'country_code'."),
] = None,
per_page: Annotated[
int,
Query(description="Results per page.", ge=1, le=100),
] = 25,
page: Annotated[
int | None,
Query(description="Page number. Use cursor for deep pagination.", ge=1),
] = 1,
cursor: Annotated[
str | None,
Query(description="Cursor pagination token. Use '*' to start."),
] = None,
sample: Annotated[
int | None,
Query(
description="Random sample size. Cannot be combined with sort or page.",
ge=1,
le=10000,
),
] = None,
select: Annotated[
str | None,
Query(description="Comma-separated fields to return."),
] = None,
):
return await logic.list_institutions(
search=search,
filter=filter,
sort=sort,
group_by=group_by,
per_page=per_page,
page=page,
cursor=cursor,
sample=sample,
select=select,
)
@@ -1,19 +1,16 @@
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: ESCluster) -> Tuple[str, str]:
def _cluster_credentials(cluster: str) -> 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".
cluster (str): 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.
@@ -22,7 +19,7 @@ def _cluster_credentials(cluster: ESCluster) -> Tuple[str, str]:
Tuple[str, str]: The Elasticsearch URL and API key for the specified cluster.
"""
if cluster == ESCluster.NES:
if cluster == "nes":
if (
not config.settings.elasticsearch_url
or not config.settings.elasticsearch_api_key
@@ -31,7 +28,7 @@ def _cluster_credentials(cluster: ESCluster) -> Tuple[str, str]:
"Elasticsearch URL and API key must be set in the configuration for cluster 'nes'"
)
return config.settings.elasticsearch_url, config.settings.elasticsearch_api_key
elif cluster == ESCluster.INSE:
elif cluster == "inse":
if (
not config.settings.elasticsearch_inse_url
or not config.settings.elasticsearch_inse_api_key
@@ -48,40 +45,10 @@ def _cluster_credentials(cluster: ESCluster) -> Tuple[str, str]:
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: ESIndex | List[ESIndex],
index: str,
query_field: Optional[str] = None,
query_value: Optional[str] = None,
query: Optional[Dict] = None,
source: Optional[List] = None,
size: Optional[int] = None,
@@ -89,13 +56,14 @@ def search(
sort: Optional[List] = None,
body: Optional[Dict] = None,
track_total_hits=False,
highlight: Optional[Dict] = None,
cluster: ESCluster = ESCluster.NES,
cluster: str = "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.
index (str): The name of the Elasticsearch index to search.
query_field (Optional[str], optional): The field to search in. Defaults to None.
query_value (Optional[str], optional): The value to search for. Defaults to None.
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.
@@ -103,41 +71,22 @@ def search(
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.
cluster (str, optional): The Elasticsearch cluster to search. Defaults to "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"}
payload: Dict[str, Any] = {}
payload: Dict[str, Any]
if body is not None:
payload = body
else:
if query is not None:
payload["query"] = query
elif query is not None:
payload = {"query": query}
if source is not None:
payload["_source"] = source
if size is not None:
@@ -148,35 +97,29 @@ def search(
payload["sort"] = sort
if track_total_hits:
payload["track_total_hits"] = True
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"
)
else:
payload = {
"query": {
"query_string": {"default_field": query_field, "query": query_value}
}
}
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)}"
f"Sending search request to Elasticsearch cluster '{cluster}' at {elasticsearch_url} with payload: {payload}"
)
if isinstance(index, list):
index_str = ",".join(index)
else:
index_str = index
response = client.post(
f"{elasticsearch_url}/{index_str}/_search", json=payload, headers=headers
f"{elasticsearch_url}/{index}/_search", json=payload, headers=headers
)
response.raise_for_status()
return response.json()
def get(
index: ESIndex,
index: str,
doc_id: str,
source: Optional[list] = None,
cluster: ESCluster = ESCluster.NES,
cluster: str = "nes",
) -> dict[str, Any]:
elasticsearch_url, api_key = _cluster_credentials(cluster)
+86 -13
View File
@@ -6,10 +6,17 @@ web service.
"""
from typing import List
from typing import TypeVar
from typing import Optional
from typing import Type
from sqlalchemy.orm import Session
from sqlalchemy import select
from sqlalchemy import func
import logging
import httpx
import json
from . import schema
from . import model
from . import config
@@ -22,13 +29,68 @@ from inse.models.openalex.topic_domain import TopicDomain
logger = logging.getLogger(__name__)
topic_cache_filename: str = "topic_hierarchy_cache.json"
S = TypeVar('S', bound=schema.Base)
M = TypeVar('M', bound=model.BaseModel)
def filter_none():
return True
def get_page(
db: Session,
schema_type: Type[S],
model_type: Type[M],
offset: int,
limit: int,
filter=filter_none,
) -> model.Page[M]:
result = model.Page[model_type]()
result.offset = offset
result.total = get_count(db, schema_type, filter)
result.size = limit
if result.total > result.offset:
result.elements = get_elements(db, schema_type, offset, limit, filter)
else:
result.elements = []
return result
def get_count(db: Session, schema_type: Type[S], filter=filter_none) -> int:
return db.scalar(select(func.count()).select_from(schema_type).where(filter))
def get_elements(
db: Session, schema_type: Type[S], offset: int, limit: int, filter=filter_none
) -> List[S]:
return db.scalars(
select(schema_type).where(filter).offset(offset).limit(limit)
).all()
def get_element(db: Session, schema_type: Type[S], element_id: int) -> Optional[S]:
return db.scalars(
select(schema_type).where(schema_type.id == element_id).limit(1)
).first()
def delete_element(db: Session, schema_type: Type[S], element_id: int):
element = get_element(db, schema_type, element_id)
db.delete(element)
def insert_element(db: Session, value: S) -> S:
db.add(value)
db.flush()
db.refresh(value)
return value
def _load_topic_cache() -> dict:
"""Loads the topic hierarchy cache from a JSON file."""
import os
try:
cache_path = "/data/" + topic_cache_filename
if not os.path.exists(cache_path):
@@ -169,7 +231,6 @@ def count_topic_hierarchy(topic_names: List[str]) -> dict:
return counts
def get_topic_hierarchy() -> dict:
"""
Builds and returns a hierarchical tree structure of topics:
@@ -177,25 +238,28 @@ def get_topic_hierarchy() -> dict:
"""
flat_cache = _load_topic_cache()
tree = {}
for topic_name, info in flat_cache.items():
domain = info.get("domain") or "Unbekannter Bereich"
field = info.get("field") or "Unbekanntes Feld"
subfield = info.get("subfield") or "Unbekanntes Teilfeld"
topic_id = info.get("topic_id", "")
# Clean topic ID to just be the trailing ID or keep full URL
# For querying, display name is used in persons search, but ID is useful
if domain not in tree:
tree[domain] = {}
if field not in tree[domain]:
tree[domain][field] = {}
if subfield not in tree[domain][field]:
tree[domain][field][subfield] = []
tree[domain][field][subfield].append({"id": topic_id, "name": topic_name})
tree[domain][field][subfield].append({
"id": topic_id,
"name": topic_name
})
formatted_domains = []
for d_name, d_fields in tree.items():
formatted_fields = []
@@ -203,11 +267,20 @@ def get_topic_hierarchy() -> dict:
formatted_subfields = []
for sf_name, sf_topics in f_subfields.items():
sf_topics.sort(key=lambda x: x["name"])
formatted_subfields.append({"name": sf_name, "topics": sf_topics})
formatted_subfields.append({
"name": sf_name,
"topics": sf_topics
})
formatted_subfields.sort(key=lambda x: x["name"])
formatted_fields.append({"name": f_name, "subfields": formatted_subfields})
formatted_fields.append({
"name": f_name,
"subfields": formatted_subfields
})
formatted_fields.sort(key=lambda x: x["name"])
formatted_domains.append({"name": d_name, "fields": formatted_fields})
formatted_domains.append({
"name": d_name,
"fields": formatted_fields
})
formatted_domains.sort(key=lambda x: x["name"])
return {"domains": formatted_domains}
+6 -30
View File
@@ -6,7 +6,6 @@ for fastapi that loads the service and the
webapp.
"""
from contextlib import asynccontextmanager, contextmanager
import logging
from fastapi import FastAPI, Request
@@ -19,25 +18,19 @@ 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.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.news.service import router as news_service_router
from inse.persons.service import router as persons_service_router
from inse.funders.service import router as funders_service_router
from inse.patents.service import router as patents_service_router
from inse.auth.router import router as auth_router
from inse.account_management.router import router as account_management_router
from inse.organization_management.router import router as organization_management_router
from inse.institutions.router import router as institutions_router
from inse.database import create_db_and_tables, get_session
from inse.auth.service import create_predefined_accounts
from . import config
from .account.service import router as account_router
from .service import router as service_router
logger = logging.getLogger(__name__)
@@ -46,24 +39,12 @@ logger = logging.getLogger(__name__)
settings = config.get_settings()
@asynccontextmanager
async def lifespan(app: FastAPI):
logger.info("Starting up the application...")
create_db_and_tables()
with contextmanager(get_session)() as session:
create_predefined_accounts(session, "../data/predefined_accounts.json")
yield
logger.info("Shutting down the application...")
app = FastAPI(
redoc_url=None,
title="Innovation Search Engine API",
description="API for the Innovation Search Engine (INSE) application.",
version="0.1.0",
servers=settings.servers,
lifespan=lifespan,
)
app.include_router(collaboration_network_router)
app.include_router(institutions_router)
@@ -71,18 +52,13 @@ 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)
app.include_router(service_router)
app.include_router(auth_router)
app.include_router(account_management_router)
app.include_router(organization_management_router)
app.add_middleware(
ETagCacheMiddleware,
ttl=300, # 5 minutes expiration time
+10 -32
View File
@@ -1,13 +1,9 @@
# middleware/etag_cache.py
import hashlib
import json
import time
import hashlib, json, time
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import Response
class ETagCacheMiddleware(BaseHTTPMiddleware):
def __init__(self, app, ttl: int = 60):
super().__init__(app)
@@ -18,19 +14,10 @@ class ETagCacheMiddleware(BaseHTTPMiddleware):
# Include query params and relevant headers in the key
return f"{request.url.path}?{request.url.query}"
def _content_type(self, response: Response) -> str | None:
return response.headers.get("content-type")
async def dispatch(self, request: Request, call_next):
if request.method != "GET":
return await call_next(request)
if request.url.path.startswith(("/api/auth", "/api/accounts")):
return await call_next(request)
if request.headers.get("authorization"):
return await call_next(request)
key = self._cache_key(request)
entry = self.cache.get(key)
client_etag = request.headers.get("if-none-match")
@@ -38,37 +25,28 @@ class ETagCacheMiddleware(BaseHTTPMiddleware):
# Cache hit + not expired
if entry and time.time() < entry["expires"]:
if client_etag == entry["etag"]:
headers = {"ETag": entry["etag"]}
if entry.get("content_type"):
headers["Content-Type"] = entry["content_type"]
return Response(status_code=304, headers=headers)
return Response(status_code=304, headers={"ETag": entry["etag"]})
# Client has stale ETag - return fresh cached body
headers = {"ETag": entry["etag"], "Cache-Control": f"max-age={self.ttl}"}
if entry.get("content_type"):
headers["Content-Type"] = entry["content_type"]
return Response(
content=entry["body"],
headers=headers,
media_type="application/json",
headers={"ETag": entry["etag"], "Cache-Control": f"max-age={self.ttl}"}
)
# Cache miss or expired → hit the actual route
response = await call_next(request)
body = b"".join([chunk async for chunk in response.body_iterator])
etag = f'"{hashlib.md5(body).hexdigest()}"'
content_type = self._content_type(response)
self.cache[key] = {
"body": body,
"etag": etag,
"expires": time.time() + self.ttl,
"content_type": content_type,
"expires": time.time() + self.ttl
}
headers = {"ETag": etag, "Cache-Control": f"max-age={self.ttl}"}
if content_type:
headers["Content-Type"] = content_type
return Response(
content=body,
status_code=response.status_code,
headers=headers,
)
media_type="application/json",
headers={"ETag": etag, "Cache-Control": f"max-age={self.ttl}"}
)
+21 -24
View File
@@ -1,43 +1,40 @@
#!/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
from typing import List
from typing import TypeVar
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 number. (0-based)")
size: int = Field(default=20, description="The page size in elements.")
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)
@@ -8,39 +8,3 @@ class TopicCount(BaseModel):
name: str = Field(description="The topic display name.")
count: int = Field(default=0, description="The number of occurrences.")
description: Optional[str] = Field(default=None, description="The topic description.")
subfield_id: Optional[str] = Field(
default=None,
description="The topic subfield id.",
)
subfield_name: Optional[str] = Field(
default=None,
description="The topic subfield display name.",
)
subfield_description: Optional[str] = Field(
default=None,
description="The topic subfield description.",
)
field_id: Optional[str] = Field(
default=None,
description="The topic field id.",
)
field_name: Optional[str] = Field(
default=None,
description="The topic field display name.",
)
field_description: Optional[str] = Field(
default=None,
description="The topic field description.",
)
domain_id: Optional[str] = Field(
default=None,
description="The topic domain id.",
)
domain_name: Optional[str] = Field(
default=None,
description="The topic domain display name.",
)
domain_description: Optional[str] = Field(
default=None,
description="The topic domain description.",
)
-274
View File
@@ -1,274 +0,0 @@
#!/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,
)
-35
View File
@@ -1,35 +0,0 @@
#!/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]
-105
View File
@@ -1,105 +0,0 @@
#!/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)
@@ -1 +0,0 @@
"""Organization management API."""
@@ -1,30 +0,0 @@
import uuid
from typing import List, Optional
from pydantic import BaseModel, Field
class OrganizationProfile(BaseModel):
id: uuid.UUID
name: str
other_inst_id: Optional[str] = None
deleted: bool
member_count: int
class OrganizationPage(BaseModel):
items: List[OrganizationProfile]
total: int
page: int
page_size: int
class CreateOrganizationRequest(BaseModel):
name: str = Field(min_length=1)
other_inst_id: Optional[str] = None
class UpdateOrganizationRequest(BaseModel):
name: Optional[str] = Field(default=None, min_length=1)
other_inst_id: Optional[str] = None
deleted: Optional[bool] = None
@@ -1,81 +0,0 @@
import uuid
from typing import Optional
from fastapi import APIRouter, Depends, Query, Response, status
from sqlmodel import Session
from inse.auth import service as auth_service
from inse.auth.model import AccessToken
from inse.database import get_session
from inse.tags import Tags
from . import service
from .model import (
CreateOrganizationRequest,
OrganizationPage,
OrganizationProfile,
UpdateOrganizationRequest,
)
router = APIRouter(prefix="/api/organizations", tags=[Tags.ORGANIZATION])
@router.get("", operation_id="getOrganisations", response_model=OrganizationPage)
async def get_organizations(
page: int = Query(default=0, ge=0),
page_size: int = Query(default=25, ge=1, le=100),
offset: Optional[int] = Query(default=None, ge=0),
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> OrganizationPage:
return service.get_organizations(
session=session,
access_token=access_token,
page=page,
page_size=page_size,
offset=offset,
)
@router.post(
"",
operation_id="createOrganisation",
response_model=OrganizationProfile,
status_code=status.HTTP_201_CREATED,
)
async def create_organization(
payload: CreateOrganizationRequest,
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> OrganizationProfile:
return service.create_organization(session, access_token, payload)
@router.put(
"/{organization_id}",
operation_id="updateOrganisation",
response_model=OrganizationProfile,
)
async def update_organization(
organization_id: uuid.UUID,
payload: UpdateOrganizationRequest,
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> OrganizationProfile:
return service.update_organization(
session, access_token, organization_id, payload
)
@router.delete(
"/{organization_id}",
operation_id="deleteOrganisation",
status_code=status.HTTP_204_NO_CONTENT,
)
async def delete_organization(
organization_id: uuid.UUID,
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> Response:
service.delete_organization(session, access_token, organization_id)
return Response(status_code=status.HTTP_204_NO_CONTENT)
@@ -1,183 +0,0 @@
import uuid
from typing import Optional
from fastapi import HTTPException, status
from sqlmodel import Session, func, select
from inse.auth.model import AccessToken, Account, Organization, UserRole
from .model import (
CreateOrganizationRequest,
OrganizationPage,
OrganizationProfile,
UpdateOrganizationRequest,
)
def _require_super_admin(access_token: AccessToken) -> None:
if access_token.effective_role != UserRole.SUPER_ADMIN:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Only superadmins can manage organizations.",
)
def _normalize_name(name: str) -> str:
normalized_name = name.strip()
if not normalized_name:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="Organization name must not be empty.",
)
return normalized_name
def _ensure_name_available(
session: Session,
name: str,
excluded_organization_id: Optional[uuid.UUID] = None,
) -> None:
statement = select(Organization).where(
func.lower(Organization.name) == name.lower()
)
if excluded_organization_id is not None:
statement = statement.where(Organization.id != excluded_organization_id)
if session.exec(statement).first() is not None:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="An organization with this name already exists.",
)
def _get_organization_or_404(
session: Session, organization_id: uuid.UUID
) -> Organization:
organization = session.get(Organization, organization_id)
if organization is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Organization not found.",
)
return organization
def _member_counts(
session: Session, organization_ids: list[uuid.UUID]
) -> dict[uuid.UUID, int]:
if not organization_ids:
return {}
rows = session.exec(
select(Account.organization_id, func.count(Account.id))
.where(
Account.organization_id.in_(organization_ids),
Account.deleted == False, # noqa: E712
)
.group_by(Account.organization_id)
).all()
return {organization_id: count for organization_id, count in rows}
def _to_profile(
organization: Organization, member_count: int
) -> OrganizationProfile:
return OrganizationProfile(
id=organization.id,
name=organization.name,
other_inst_id=organization.openalex_institution_id,
deleted=organization.deleted,
member_count=member_count,
)
def get_organizations(
session: Session,
access_token: AccessToken,
page: int,
page_size: int,
offset: Optional[int] = None,
) -> OrganizationPage:
statement = select(Organization)
count_statement = select(func.count()).select_from(Organization)
if access_token.effective_role != UserRole.SUPER_ADMIN:
scope_filter = Organization.id == access_token.effective_organization_id
statement = statement.where(scope_filter)
count_statement = count_statement.where(scope_filter)
total = session.exec(count_statement).one()
effective_offset = offset if offset is not None else page * page_size
organizations = session.exec(
statement.order_by(Organization.name)
.offset(effective_offset)
.limit(page_size)
).all()
organization_ids = [organization.id for organization in organizations]
counts = _member_counts(session, organization_ids)
return OrganizationPage(
items=[
_to_profile(organization, counts.get(organization.id, 0))
for organization in organizations
],
total=total,
page=page,
page_size=page_size,
)
def create_organization(
session: Session,
access_token: AccessToken,
payload: CreateOrganizationRequest,
) -> OrganizationProfile:
_require_super_admin(access_token)
name = _normalize_name(payload.name)
_ensure_name_available(session, name)
organization = Organization(
name=name,
openalex_institution_id=(payload.other_inst_id or '').strip() or None,
)
session.add(organization)
session.commit()
session.refresh(organization)
return _to_profile(organization, 0)
def update_organization(
session: Session,
access_token: AccessToken,
organization_id: uuid.UUID,
payload: UpdateOrganizationRequest,
) -> OrganizationProfile:
_require_super_admin(access_token)
organization = _get_organization_or_404(session, organization_id)
if payload.name is not None:
name = _normalize_name(payload.name)
_ensure_name_available(session, name, organization.id)
organization.name = name
if payload.other_inst_id is not None:
organization.openalex_institution_id = payload.other_inst_id.strip() or None
if payload.deleted is not None:
organization.deleted = payload.deleted
session.add(organization)
session.commit()
session.refresh(organization)
counts = _member_counts(session, [organization.id])
return _to_profile(organization, counts.get(organization.id, 0))
def delete_organization(
session: Session,
access_token: AccessToken,
organization_id: uuid.UUID,
) -> None:
_require_super_admin(access_token)
organization = _get_organization_or_404(session, organization_id)
organization.deleted = True
session.add(organization)
session.commit()
@@ -1,181 +0,0 @@
from types import SimpleNamespace
import pytest
from fastapi import HTTPException
from sqlmodel import Session, SQLModel, create_engine
from inse.auth.model import Account, Organization, UserRole
from inse.organization_management import service
from inse.organization_management.model import (
CreateOrganizationRequest,
UpdateOrganizationRequest,
)
@pytest.fixture()
def session():
engine = create_engine(
"sqlite:///:memory:", connect_args={"check_same_thread": False}
)
SQLModel.metadata.create_all(engine)
with Session(engine) as database_session:
yield database_session
def token(role: UserRole, organization_id):
return SimpleNamespace(
effective_role=role,
effective_organization_id=organization_id,
)
def test_superadmin_lists_all_organizations_with_active_member_count(session):
first = Organization(name="Alpha")
second = Organization(name="Beta", deleted=True)
session.add(first)
session.add(second)
session.flush()
session.add(
Account(
email="active@example.org",
name="Active",
password_hash="hash",
organization_id=first.id,
)
)
session.add(
Account(
email="deleted@example.org",
name="Deleted",
password_hash="hash",
organization_id=first.id,
deleted=True,
)
)
session.commit()
result = service.get_organizations(
session, token(UserRole.SUPER_ADMIN, first.id), page=0, page_size=10
)
assert result.total == 2
assert [item.name for item in result.items] == ["Alpha", "Beta"]
assert result.items[0].member_count == 1
assert result.items[1].deleted is True
def test_non_superadmin_only_sees_own_organization(session):
own = Organization(name="Own")
session.add(own)
session.add(Organization(name="Other"))
session.commit()
result = service.get_organizations(
session, token(UserRole.USER, own.id), page=0, page_size=10
)
assert result.total == 1
assert result.items[0].id == own.id
def test_superadmin_can_create_update_and_soft_delete(session):
scope = Organization(name="Scope")
session.add(scope)
session.commit()
access_token = token(UserRole.SUPER_ADMIN, scope.id)
created = service.create_organization(
session,
access_token,
CreateOrganizationRequest(name=" New tenant ", other_inst_id="I123"),
)
assert created.name == "New tenant"
assert created.other_inst_id == "I123"
updated = service.update_organization(
session,
access_token,
created.id,
UpdateOrganizationRequest(name="Renamed", other_inst_id=""),
)
assert updated.name == "Renamed"
assert updated.other_inst_id is None
service.delete_organization(session, access_token, created.id)
assert session.get(Organization, created.id).deleted is True
@pytest.mark.parametrize("role", [UserRole.ADMIN, UserRole.MANAGER, UserRole.USER])
def test_only_superadmin_can_create_organizations(session, role):
organization = Organization(name="Scope")
session.add(organization)
session.commit()
with pytest.raises(HTTPException) as error:
service.create_organization(
session,
token(role, organization.id),
CreateOrganizationRequest(name="Forbidden"),
)
assert error.value.status_code == 403
def test_organization_name_must_not_be_blank(session):
organization = Organization(name="Scope")
session.add(organization)
session.commit()
with pytest.raises(HTTPException) as error:
service.create_organization(
session,
token(UserRole.SUPER_ADMIN, organization.id),
CreateOrganizationRequest(name=" "),
)
assert error.value.status_code == 422
def test_organization_name_is_unique_ignoring_case(session):
existing = Organization(name="Unique tenant")
session.add(existing)
session.commit()
access_token = token(UserRole.SUPER_ADMIN, existing.id)
with pytest.raises(HTTPException) as create_error:
service.create_organization(
session,
access_token,
CreateOrganizationRequest(name=" unique TENANT "),
)
assert create_error.value.status_code == 409
other = Organization(name="Other tenant")
session.add(other)
session.commit()
with pytest.raises(HTTPException) as update_error:
service.update_organization(
session,
access_token,
other.id,
UpdateOrganizationRequest(name="UNIQUE TENANT"),
)
assert update_error.value.status_code == 409
def test_organization_can_keep_its_name_when_updating(session):
organization = Organization(name="Same tenant")
session.add(organization)
session.commit()
result = service.update_organization(
session,
token(UserRole.SUPER_ADMIN, organization.id),
organization.id,
UpdateOrganizationRequest(name="same TENANT"),
)
assert result.name == "same TENANT"
@@ -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()
+156
View File
@@ -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
+20
View File
@@ -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
+26 -96
View File
@@ -8,79 +8,28 @@ import json
import logging
import time
from datetime import datetime
from typing import Optional, List
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
from inse.models.openalex.author import Author
from inse.models.openalex.authors_list_response import AuthorsListResponse
from inse import util
from inse.integrations import elasticsearch
from inse.models.openalex.meta import Meta
from inse.persons.query_builder import build_authors_search_rescored
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]:
@@ -106,26 +55,20 @@ 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_ = {
"query_string": {
"default_field": "_id",
"query": author_id,
}
}
query_field = "_id"
query_value = author_id
elif query:
query_ = {
"query_string": {
"default_field": "display_name",
"query": query,
}
}
query_field = "display_name"
query_value = query
else:
return AuthorsListResponse(results=[], meta=Meta(count=0))
data = elasticsearch.search(index=ESIndex.OPENALEX_AUTHORS, query=query_)
data = elasticsearch.search(
index="openalex-authors", query_field=query_field, query_value=query_value
)
authors = []
for hit in data.get("hits", {}).get("hits", []):
@@ -278,7 +221,9 @@ def _get_publication_years_for_author(author_id: str) -> list[int]:
)
buckets = (
response.get("aggregations", {}).get("publication_years", {}).get("buckets", [])
response.get("aggregations", {})
.get("publication_years", {})
.get("buckets", [])
)
publication_years: list[int] = []
@@ -292,21 +237,20 @@ def _get_publication_years_for_author(author_id: str) -> list[int]:
return publication_years
def _classify_career_stage(active_years: int) -> str:
if active_years <= 0:
return "unknown"
if active_years <= 4:
return "Early"
return "Early Researcher"
if active_years <= 9:
return "Emerging"
if active_years <= 10:
return "Emerging Researcher"
if active_years <= 14:
return "Established"
if active_years <= 20:
return "Established Researcher"
return "Senior"
return "Senior Researcher"
def _compute_career_metrics(publication_years: list[int]) -> CareerMetrics:
@@ -427,13 +371,15 @@ 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
) -> CustomAuthorsListResponse:
source = include.split(",") if include else None
body = {
"_source": include.split(",") if include else True,
}
try:
hit = elasticsearch.get(
index="openalex-authors",
body=body,
doc_id=author_id,
source=source,
)
except NotFoundError:
raise HTTPException(
@@ -443,13 +389,7 @@ def get_person_by_id(
raise HTTPException(status_code=500, detail=f"Elasticsearch error: {str(e)}")
author = util.get_persons_data(hit)
start_time = time.time()
career_metrics = get_career_metrics_for_author(author_id)
elapsed_time = time.time() - start_time
logger.info(
f"Career metrics calculation for author {author_id} took {elapsed_time:.2f} seconds"
)
custom_author = CustomAuthor(
**author.model_dump(),
@@ -459,6 +399,7 @@ def get_person_by_id(
return CustomAuthorsListResponse(results=[custom_author])
def search_persons_by_name(
author_name: str,
limit: Optional[int] = 10,
@@ -735,22 +676,11 @@ def advanced_search_persons(
hits = response_dict.get("hits", {}).get("hits", [])
total_count = response_dict.get("hits", {}).get("total", {}).get("value", 0)
include_career_metrics = include is None or "career_metrics" in include
results = []
for hit in hits:
raw_data = util.get_persons_data(hit)
custom_author = _enrich_author_data(raw_data)
if custom_author:
if include_career_metrics:
start_time = time.time()
custom_author.career_metrics = get_career_metrics_for_author(
custom_author.id
)
elapsed_time = time.time() - start_time
logger.info(
f"Career metrics calculation for author {custom_author.id} took "
f"{elapsed_time:.2f} seconds"
)
results.append(custom_author)
return CustomAuthorsListResponse(
+1 -1
View File
@@ -53,7 +53,7 @@ def search_persons(
if include
else None
)
return logic.search_persons(author_id, query)
return logic.search_persons(author_id, query, include_set)
@router.get(
+1 -90
View File
@@ -8,7 +8,6 @@ from pydantic import BaseModel, Field, field_validator
from inse.models.bund_project import BundProject
from inse.models.eu_project import EuProject
from inse.models.cordis_eu_project import CordisEuProject
from inse.model import ESIndex
class ProjectType(StrEnum):
@@ -16,17 +15,6 @@ class ProjectType(StrEnum):
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"
@@ -34,24 +22,6 @@ class ProjectsSortBy(StrEnum):
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"
@@ -172,9 +142,6 @@ class FundingProject(BaseModel):
)
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."
)
@@ -217,7 +184,7 @@ class FundingProject(BaseModel):
title=source.get("title"),
start_date=source.get("startDate"),
end_date=source.get("endDate"),
funding_amount=source.get("ecMaxContribution"),
funding_amount=source.get("ecMacContribution"),
)
@classmethod
@@ -251,7 +218,6 @@ class FundingProject(BaseModel):
title=source.get("title"),
start_date=source.get("funding_start"),
end_date=source.get("funding_end"),
acronym=source.get("acronym"),
)
@@ -259,58 +225,3 @@ 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
+65 -37
View File
@@ -1,3 +1,4 @@
from functools import lru_cache
import logging
from typing import Annotated, Optional, Set
@@ -7,7 +8,6 @@ from inse.projects.model import (
BundProjectPage,
CordisEuProjectPage,
DfgProjectPage,
EuOrganizationProjectSummaryPage,
FundingProjectPage,
InstitutionFunderSummary,
ProjectType,
@@ -19,7 +19,12 @@ 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,
CompleteProjectsSearchClient,
DfgProjectsSearchClient,
EuProjectsSearchClient,
)
from inse.institutions.institutions_search_client import (
InstitutionsSearchClient,
)
@@ -30,29 +35,24 @@ logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/projects", tags=[Tags.PROJECTS])
@router.get(
"/author/{raw_oa_author_id}/eu",
summary="Get EU projects for an author.",
description="Returns a list of EU projects associated with the specified author ID.",
operation_id="getEuProjectsForAuthor",
responses={
status.HTTP_200_OK: {
"description": "Successful Response",
"model": CordisEuProjectPage,
},
status.HTTP_404_NOT_FOUND: {"description": "Author not found"},
},
response_model_by_alias=False,
)
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,
)
@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()
@lru_cache
def get_complete_projects_search_client() -> CompleteProjectsSearchClient:
return CompleteProjectsSearchClient()
@router.post(
@@ -70,6 +70,9 @@ def get_eu_projects_for_author(
response_model_by_alias=False,
)
async def search_bund_projects(
bund_search_client: Annotated[
BundProjectsSearchClient, Depends(get_bund_search_client)
],
institutions_search_client: Annotated[
InstitutionsSearchClient, Depends(get_institutions_search_client)
],
@@ -78,7 +81,8 @@ async def search_bund_projects(
Body(description="The filtering properties for the projects search."),
],
) -> BundProjectPage:
return projects_service.search_bund_projects(
return await projects_service.search_bund_projects(
bund_search_client=bund_search_client,
institutions_search_client=institutions_search_client,
filtering_properties=filtering_properties,
)
@@ -98,11 +102,15 @@ async def search_bund_projects(
},
response_model_by_alias=False,
)
def get_single_dfg_project(
async def get_single_dfg_project(
dfg_search_client: Annotated[
DfgProjectsSearchClient, Depends(get_dfg_search_client)
],
id: Annotated[str, Path(description="The ID of the DFG project to retrieve.")],
) -> DfgProjectDetails:
logger.debug(f"Received request to get single DFG project for id={id}")
return projects_service.get_single_dfg_project(
return await projects_service.get_single_dfg_project(
dfg_search_client=dfg_search_client,
project_id=id,
)
@@ -121,11 +129,15 @@ def get_single_dfg_project(
},
response_model_by_alias=False,
)
def get_single_bund_project(
async def get_single_bund_project(
bund_search_client: Annotated[
BundProjectsSearchClient, Depends(get_bund_search_client)
],
id: Annotated[str, Path(description="The ID of the BUND project to retrieve.")],
) -> BundProjectDetails:
logger.debug(f"Received request to get single BUND project for id={id}")
return projects_service.get_single_bund_project(
return await projects_service.get_single_bund_project(
bund_search_client=bund_search_client,
project_id=id,
)
@@ -144,7 +156,10 @@ def get_single_bund_project(
},
response_model_by_alias=False,
)
def get_institution_bund_projects_funding_over_time(
async def get_institution_bund_projects_funding_over_time(
bund_search_client: Annotated[
BundProjectsSearchClient, Depends(get_bund_search_client)
],
institutions_search_client: Annotated[
InstitutionsSearchClient, Depends(get_institutions_search_client)
],
@@ -152,7 +167,8 @@ def get_institution_bund_projects_funding_over_time(
str, Query(description="The institution ID to filter by.")
],
) -> InstitutionFunderSummary:
return projects_service.get_institution_bund_projects_funding_over_time(
return await projects_service.get_institution_bund_projects_funding_over_time(
bund_search_client=bund_search_client,
institutions_search_client=institutions_search_client,
raw_oa_institution_id=raw_oa_institution_id,
)
@@ -166,13 +182,14 @@ def get_institution_bund_projects_funding_over_time(
responses={
status.HTTP_200_OK: {
"description": "Successful Response",
"model": EuOrganizationProjectSummaryPage,
"model": CordisEuProjectPage,
},
status.HTTP_404_NOT_FOUND: {"description": "Institution not found"},
},
response_model_by_alias=False,
)
async def search_cordis_eu_projects(
eu_search_client: Annotated[EuProjectsSearchClient, Depends(get_eu_search_client)],
institutions_search_client: Annotated[
InstitutionsSearchClient, Depends(get_institutions_search_client)
],
@@ -180,8 +197,9 @@ async def search_cordis_eu_projects(
ProjectsFilteringProperties,
Body(description="The filtering properties for the projects search."),
],
) -> EuOrganizationProjectSummaryPage:
return projects_service.search_cordis_eu_projects(
) -> CordisEuProjectPage:
return await projects_service.search_cordis_eu_projects(
eu_search_client=eu_search_client,
institutions_search_client=institutions_search_client,
projects_filtering_properties=projects_filtering_properties,
)
@@ -202,6 +220,7 @@ async def search_cordis_eu_projects(
response_model_by_alias=False,
)
async def get_institution_cordis_eu_projects_funding_over_time(
eu_search_client: Annotated[EuProjectsSearchClient, Depends(get_eu_search_client)],
institutions_search_client: Annotated[
InstitutionsSearchClient, Depends(get_institutions_search_client)
],
@@ -210,6 +229,7 @@ async def get_institution_cordis_eu_projects_funding_over_time(
],
) -> InstitutionFunderSummary:
return await projects_service.get_institution_cordis_eu_projects_funding_over_time(
eu_search_client=eu_search_client,
institutions_search_client=institutions_search_client,
raw_oa_institution_id=raw_oa_institution_id,
)
@@ -230,6 +250,9 @@ async def get_institution_cordis_eu_projects_funding_over_time(
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.")
@@ -251,6 +274,7 @@ 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,
@@ -273,7 +297,10 @@ async def get_dfg_projects(
},
response_model_by_alias=False,
)
def search_projects(
async def search_projects(
complete_projects_search_client: Annotated[
CompleteProjectsSearchClient, Depends(get_complete_projects_search_client)
],
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[
@@ -292,7 +319,8 @@ def search_projects(
SortDirection, Query(description="The sort direction (asc or desc).")
] = SortDirection.ASC,
) -> FundingProjectPage:
return projects_service.search_all_projects(
return await projects_service.search_projects(
projects_search_client=complete_projects_search_client,
page=page,
size=size,
selected_project_types=selected_project_types,
+124 -96
View File
@@ -2,15 +2,17 @@ import datetime
import logging
from typing import Any, Dict, List, Optional, Set
from inse.projects import projects_search_client
from inse.projects.projects_search_client import (
get_eu_organization_project_contributions,
BundProjectsSearchClient,
CompleteProjectsSearchClient,
DfgProjectsSearchClient,
EuProjectsSearchClient,
)
from inse.projects.model import (
BundProjectPage,
CordisEuProjectPage,
DfgProjectPage,
EuOrganizationProjectSummaryPage,
EuProjectPage,
FundingProjectPage,
InstitutionFunderSummary,
ProjectType,
@@ -25,13 +27,12 @@ from inse.institutions.institutions_search_client import (
)
from inse.exceptions import NotFoundException
from inse.persons.logic import get_author_name_by_id
from inse.works.logic import get_publication_dois_of_author
logger = logging.getLogger(__name__)
def search_all_projects(
async def search_projects(
projects_search_client: CompleteProjectsSearchClient,
page: int,
size: int,
sort_by: ProjectsSortBy,
@@ -39,20 +40,18 @@ def search_all_projects(
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,
),
return await projects_search_client.search_projects(
page=page,
size=size,
selected_project_types=selected_project_types,
title=title,
sort_by=sort_by,
sort_direction=sort_direction,
)
def search_bund_projects(
async def search_bund_projects(
bund_search_client: BundProjectsSearchClient,
institutions_search_client: InstitutionsSearchClient,
filtering_properties: ProjectsFilteringProperties,
) -> BundProjectPage:
@@ -61,17 +60,15 @@ def search_bund_projects(
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(
return await get_bund_projects_by_institution_id(
bund_search_client=bund_search_client,
institutions_search_client=institutions_search_client,
filtering_properties=filtering_properties,
)
def get_bund_projects_by_institution_id(
async def get_bund_projects_by_institution_id(
bund_search_client: BundProjectsSearchClient,
institutions_search_client: InstitutionsSearchClient,
filtering_properties: ProjectsFilteringProperties,
) -> BundProjectPage:
@@ -81,41 +78,46 @@ def get_bund_projects_by_institution_id(
logger.info(
f"Fetching bund projects for institution_id={filtering_properties.raw_oa_institution_id}, page={filtering_properties.page}, size={filtering_properties.size}"
)
institution_aliases = (
institutions_search_client.get_institution_aliases_by_oa_institution_id(
filtering_properties.raw_oa_institution_id
)
institution_aliases = institutions_search_client.get_institution_aliases_by_id(
filtering_properties.raw_oa_institution_id
)
logger.debug(
f"get_bund_projects_by_institution_id: Found institution aliases for institution_id={filtering_properties.raw_oa_institution_id}: {institution_aliases}"
f"Found institution aliases for institution_id={filtering_properties.raw_oa_institution_id}: {institution_aliases}"
)
response = projects_search_client.search_bund_projects(
response = await bund_search_client.search_bund_projects(
page=filtering_properties.page,
size=filtering_properties.size,
institution_names=institution_aliases,
filter_properties=filtering_properties,
topic=filtering_properties.query,
sort_by=filtering_properties.sort_by,
sort_direction=filtering_properties.sort_direction,
)
logger.debug(f"get_bund_projects_by_institution_id response: {response}")
return response
def search_cordis_eu_projects(
async def search_cordis_eu_projects(
eu_search_client: EuProjectsSearchClient,
institutions_search_client: InstitutionsSearchClient,
projects_filtering_properties: ProjectsFilteringProperties,
) -> EuOrganizationProjectSummaryPage:
) -> CordisEuProjectPage:
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(
return await get_cordis_eu_projects_by_institution_id(
eu_search_client=eu_search_client,
institutions_search_client=institutions_search_client,
projects_filtering_properties=projects_filtering_properties,
)
def get_cordis_eu_projects_by_institution_id(
async def get_cordis_eu_projects_by_institution_id(
eu_search_client: EuProjectsSearchClient,
institutions_search_client: InstitutionsSearchClient,
projects_filtering_properties: ProjectsFilteringProperties,
) -> EuOrganizationProjectSummaryPage:
) -> CordisEuProjectPage:
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"
@@ -124,26 +126,81 @@ def get_cordis_eu_projects_by_institution_id(
logger.info(
f"Fetching CORDIS EU projects for institution_id={projects_filtering_properties.raw_oa_institution_id}, page={projects_filtering_properties.page}, size={projects_filtering_properties.size}"
)
institution_aliases = (
institutions_search_client.get_institution_aliases_by_oa_institution_id(
projects_filtering_properties.raw_oa_institution_id
)
institution_aliases = institutions_search_client.get_institution_aliases_by_id(
projects_filtering_properties.raw_oa_institution_id
)
logger.debug(
f"Found institution aliases for institution_id={projects_filtering_properties.raw_oa_institution_id}: {institution_aliases}"
)
page = get_eu_organization_project_contributions(
organization_names=institution_aliases,
institution_eu_organisation_id = await (
institutions_search_client.get_eu_organisation_id_by_oa_institution_id(
projects_filtering_properties.raw_oa_institution_id
)
)
if not institution_eu_organisation_id:
logger.debug(
f"No EU organization ID found for institution_id={projects_filtering_properties.raw_oa_institution_id}"
)
raise NotFoundException(
f"EU organization ID for institution with id {projects_filtering_properties.raw_oa_institution_id} not found"
)
cordis_eu_project_page = await eu_search_client.search_eu_projects2(
eu_organisation_id=institution_eu_organisation_id,
projects_filtering_properties=projects_filtering_properties,
)
logger.debug(f"get_cordis_eu_projects_by_institution_id response: {page}")
return cordis_eu_project_page
return page
async def get_eu_projects_by_institution_id(
eu_search_client: EuProjectsSearchClient,
institutions_search_client: InstitutionsSearchClient,
raw_oa_institution_id: str,
topic: Optional[str],
page: int,
size: int,
sort_by: str = "topic",
sort_direction: str = "asc",
) -> EuProjectPage:
logger.info(
f"Fetching EU projects for institution_id={raw_oa_institution_id}, page={page}, size={size}"
)
institution_aliases = institutions_search_client.get_institution_aliases_by_id(
raw_oa_institution_id
)
logger.debug(
f"Found institution aliases for institution_id={raw_oa_institution_id}: {institution_aliases}"
)
institution_eu_organisation_id = await (
institutions_search_client.get_eu_organisation_id_by_oa_institution_id(
raw_oa_institution_id
)
)
if not institution_eu_organisation_id:
logger.debug(
f"No EU organization ID found for institution_id={raw_oa_institution_id}"
)
raise NotFoundException(
f"EU organization ID for institution with id {raw_oa_institution_id} not found"
)
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_dfg_projects_by_author_id(
dfg_search_client: DfgProjectsSearchClient,
author_id: str,
topic: Optional[str],
page: int,
@@ -162,7 +219,7 @@ async def get_dfg_projects_by_author_id(
)
logger.debug(f"Found author name for author_id={author_id}: {name}")
response = projects_search_client.search_dfg_projects(
response = await dfg_search_client.search_dfg_projects(
page=page,
size=size,
names=[name],
@@ -174,18 +231,17 @@ async def get_dfg_projects_by_author_id(
async def get_institution_cordis_eu_projects_funding_over_time(
eu_search_client: EuProjectsSearchClient,
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(
cordis_eu_project_page = await search_cordis_eu_projects(
eu_search_client,
institutions_search_client,
ProjectsFilteringProperties(
project_type=ProjectType.EU,
raw_oa_institution_id=raw_oa_institution_id,
page=0,
size=10000,
),
@@ -193,34 +249,30 @@ async def get_institution_cordis_eu_projects_funding_over_time(
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",
projects=cordis_eu_project_page.elements,
funding_start_attr="startDate",
funding_end_attr="endDate",
funding_amount_attr="totalCost",
)
def get_institution_bund_projects_funding_over_time(
async def get_institution_bund_projects_funding_over_time(
bund_search_client: BundProjectsSearchClient,
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
)
institution_aliases = institutions_search_client.get_institution_aliases_by_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,
),
response = await bund_search_client.search_bund_projects(
page=0,
size=10000,
institution_names=institution_aliases,
)
@@ -301,49 +353,25 @@ def _calculate_funding_over_time(
)
def get_single_dfg_project(
async def get_single_dfg_project(
dfg_search_client: DfgProjectsSearchClient,
project_id: str,
) -> DfgProjectDetails:
logger.debug(f"Fetching single DFG project for id={project_id}")
project = projects_search_client.get_dfg_project_by_id(project_id)
project = await dfg_search_client.get_dfg_project_by_id(project_id)
if not project:
raise NotFoundException(f"DFG project with id {project_id} not found")
return project
def get_single_bund_project(
async def get_single_bund_project(
bund_search_client: BundProjectsSearchClient,
project_id: str,
) -> BundProjectDetails:
logger.debug(f"Fetching single BUND project for id={project_id}")
project = projects_search_client.get_bund_project_by_id(project_id)
project = await bund_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
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module defines the schema for the database
used by the service using sql alchemy.
"""
from sqlalchemy import String
from sqlalchemy.orm import DeclarativeBase
from sqlalchemy.orm import Mapped
from sqlalchemy.orm import mapped_column
class Base(DeclarativeBase):
''' Base class for all data models. '''
pass
class Item(Base):
''' Data model to represent an item. '''
__tablename__ = "item"
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
name: Mapped[str] = mapped_column(String(200))
description: Mapped[str] = mapped_column(String(2000))
def __repr__(self) -> str:
return f"Item(id={self.id!r}, name={self.name!r})"
+84
View File
@@ -0,0 +1,84 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module defines the security-related code.
"""
from typing import Optional
from typing import List
from typing import Callable
from typing import Literal
from typing import Union
from starlette.status import HTTP_403_FORBIDDEN
from fastapi import Depends
from fastapi.security import HTTPBearer
from fastapi.security import HTTPAuthorizationCredentials
from fastapi import HTTPException
from pydantic import BaseModel
from pydantic import Field
from sqlalchemy.orm import Session
import jwt
import logging
from . import config
from . import database
class Account(BaseModel):
id: int = Field(description="The id of the account.")
login: Optional[str] = Field(description="The optional login of the account.")
organization: int = Field(description="The organization id of the account.")
class Principal(BaseModel):
account: Account = Field(description="The account of the principal.")
delegate: Optional[Account] = Field(default=None, description="The optional delegate of the principal.")
roles: List[str] = Field(description="The roles of the principal.")
logger = logging.getLogger(__name__)
bearer = HTTPBearer(bearerFormat="JWT", scheme_name="bearer", description="JSON Web Token provided via bearer authorization.", auto_error=False)
def principal(credentials: Optional[HTTPAuthorizationCredentials] = Depends(bearer), db: Session = Depends(database.get)) -> Optional[Principal]:
if config.settings.auth_disabled:
account = Account(id=0, login="AUTH_DISABLED", organization=0)
return Principal(account=account, delegate=None, roles=[ 'SUPER_ADMIN' ])
if credentials is None or credentials.credentials is None:
return None
return _extract_principal(credentials.credentials, config.settings.auth_secret, 'HS256')
def _extract_principal(token: str, secret_key, algorithm: Literal['RS256', 'HS256'], token_types: List[Literal['ID', 'ACCESS', 'REFRESH']] = [ 'ACCESS' ]) -> Optional[Principal]:
try:
content = jwt.decode(token, secret_key, verify=True, issuer="my-app", algorithms=[ algorithm ], options={"require": [ "iss", "iat", "nbf", "exp", "inse"]})
except jwt.exceptions.ExpiredSignatureError as e:
logger.info(f'Received expired token, ignoring content ({e}).')
return None
except Exception as e:
logger.info(f'Received invalid token content, ignoring content ({e}).')
return None
scope = content.get("inse")
if scope is None:
return None
token_type = scope.get('t')
if token_type not in token_types:
logger.info(f'Received invalid token type, ignoring content (Type was {token_type})')
return None
a = scope.get('a', {})
account = Account(id=a.get('i', 0), login=a.get('l'), organization=a.get('o', 0))
delegate = None
d = scope.get('d')
if d is not None:
delegate = Account(id=d.get('i', 0), login=d.get('l'), organization=d.get('o', 0))
return Principal(account=account, delegate=delegate, roles=scope.get('r', []))
def roles_allowed(roles: List[str]|str) -> Callable[[Optional[Principal]], Principal]:
if isinstance(roles, str):
roles = [roles]
if len(roles) < 1:
raise ValueError("Must specify at least one role in roles_allowed.")
def verify_roles(principal: Optional[Principal] = Depends(principal)) -> Principal:
if principal is None:
logger.info("Rejecting call due to missing principal.")
raise HTTPException(status_code=HTTP_403_FORBIDDEN)
for role in roles:
if role in principal.roles:
return principal
logger.info("Rejecting call due to missing roles.")
raise HTTPException(status_code=HTTP_403_FORBIDDEN)
return verify_roles
+136 -2
View File
@@ -6,13 +6,28 @@ service.
"""
import logging
from typing import Annotated, List
from typing import Annotated, List, Optional
from fastapi import FastAPI
from fastapi import Depends
from fastapi import Path
from fastapi import Query
from fastapi import Body
from fastapi import Response
from fastapi.responses import RedirectResponse
from starlette.status import HTTP_404_NOT_FOUND
from starlette.status import HTTP_200_OK
from sqlalchemy.orm import Session
from inse.config import get_settings
from fastapi import APIRouter
from . import model
from . import logic
from . import schema
from . import database
from . import security
from . import util
logger = logging.getLogger(__name__)
@@ -27,6 +42,126 @@ router = APIRouter(
responses={404: {"description": "Not found"}},
)
# @app.get("/", include_in_schema=False)
# async def show_api():
# return RedirectResponse("api")
### items
@router.get(
"/items",
operation_id="getItems",
response_model=model.ItemPage,
summary="Returns a page of items.",
tags=["Items"],
)
def get_items(
page_offset: Annotated[
int, Query(alias="pageOffset", description="The page offset.", ge=0)
] = 0,
page_size: Annotated[
int, Query(alias="pageSize", description="The page size.", ge=0, le=1000)
] = 100,
db: Session = Depends(database.get),
principal: security.Principal = Depends(
security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])
),
):
return logic.get_page(db, schema.Item, model.Item, page_offset, page_size)
@router.get(
"/items/{id}",
operation_id="getItem",
response_model=model.Item,
summary="Returns the item with the id.",
responses={HTTP_404_NOT_FOUND: {"model": None}},
tags=["Items"],
)
def get_item(
id: Annotated[int, Path(description="The item id.", ge=0)],
db: Session = Depends(database.get),
principal: security.Principal = Depends(
security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])
),
):
return util.raise_not_found_if_none(logic.get_element(db, schema.Item, id))
@router.post(
"/items",
operation_id="addItem",
response_model=model.Item,
summary="Adds a new item.",
tags=["Items"],
)
def add_item(
item: Annotated[model.ItemCreate, Body(description="The item to add.")],
db: Session = Depends(database.get),
principal: security.Principal = Depends(
security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])
),
):
i = schema.Item()
i.name = item.name
i.description = item.description
try:
return logic.insert_element(db, i)
finally:
db.commit()
@router.put(
"/items/{id}",
operation_id="updateItem",
response_model=model.Item,
summary="Updates the item with the id.",
responses={HTTP_404_NOT_FOUND: {"model": None}},
tags=["Items"],
)
def update_item(
id: Annotated[int, Path(description="The item id.", ge=0)],
item: Annotated[model.ItemCreate, Body(description="The item data to update.")],
db: Session = Depends(database.get),
principal: security.Principal = Depends(
security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])
),
):
i = util.raise_not_found_if_none(logic.get_element(db, schema.Item, id))
i.name = item.name
i.description = item.description
db.flush()
db.refresh(i)
try:
return i
finally:
db.commit()
@router.delete(
"/items/{id}",
operation_id="deleteItem",
summary="Deletes the item with the id.",
response_model=None,
responses={HTTP_404_NOT_FOUND: {"model": None}},
tags=["Items"],
)
def delete_item(
id: Annotated[int, Path(description="The item id.", ge=0)],
db: Session = Depends(database.get),
principal: security.Principal = Depends(
security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])
),
):
util.raise_not_found_if_none(logic.get_element(db, schema.Item, id))
try:
logic.delete_element(db, schema.Item, id)
return Response(status_code=HTTP_200_OK)
finally:
db.commit()
### topics
# hierarchy cache (temporaray => should be called by a scheduled job, with new openalex data indexing)
@@ -74,7 +209,6 @@ def count_topic_hierarchy(
):
return logic.count_topic_hierarchy(topic_names)
@router.get(
"/topics/hierarchy",
operation_id="getTopicHierarchy",
+2 -6
View File
@@ -1,14 +1,10 @@
from enum import StrEnum
from enum import Enum
class Tags(StrEnum):
class Tags(Enum):
PERSON = "Person"
PERSON_NETWORK = "Person Network"
INSTITUTIONS = "Institutions"
TOPICS = "Topics"
WORKS = "Works"
NEWS = "News"
PROJECTS = "Projects"
AUTH = "Auth"
ACCOUNT = "Account"
ORGANIZATION = "Organization"
+76 -95
View File
@@ -3,7 +3,6 @@
"""
Business logic for OpenAlex topics.
"""
import logging
from copy import deepcopy
from typing import Any
@@ -157,13 +156,7 @@ def _normalize_topics_response(data: dict[str, Any]) -> dict[str, Any]:
meta = normalized.get("meta")
if isinstance(meta, dict):
for field in [
"count",
"db_response_time_ms",
"page",
"per_page",
"groups_count",
]:
for field in ["count", "db_response_time_ms", "page", "per_page", "groups_count"]:
meta[field] = _int_or_none(meta.get(field))
meta["next_cursor"] = _str_or_none(meta.get("next_cursor"))
meta["cost_usd"] = _number_or_none(meta.get("cost_usd"))
@@ -263,21 +256,10 @@ def _datetime_str_or_none(value: Any) -> str | None:
return f"{text}T00:00:00Z"
return text
# Configuration for vector search similarity thresholds and boosts
SIMILARITY_THRESHOLD = 0.62
BOOST_LEXICAL = 1.0
# higher values for semantic weights, because cosine similarity is between 0 and 1
BOOST_DISPLAY_NAME_VECTOR = 30.0
BOOST_DESCRIPTION_VECTOR = 15.0
BOOST_KEYWORD_VECTORS = 25.0
async def vector_search_topics(
*,
query: str,
limit: int = 25,
search_type: str = "hybrid",
) -> TopicsListResponse:
"""
Perform a semantic similarity search on the topicvectors index.
@@ -285,12 +267,12 @@ async def vector_search_topics(
try:
from inse.integrations import elasticsearch
from inse.util import get_model
except Exception as exc:
logger.exception("Failed to load elasticsearch integration.")
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail=f"Failed to load elasticsearch integration: {exc}",
detail=f"Failed to load elasticsearch integration: {exc}"
)
# 1. Vectorize query
@@ -301,98 +283,96 @@ async def vector_search_topics(
logger.exception("Failed to encode query text.")
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail=f"Failed to encode query text: {exc}",
detail=f"Failed to encode query text: {exc}"
)
# 2. Query Elasticsearch using standard Bool Should hybrid search
should_clauses = []
# Lexical multi_match search (only in hybrid mode)
if search_type == "hybrid":
should_clauses.append(
{
"multi_match": {
"query": query,
"fields": ["display_name^3", "keywords^2", "description^1"],
"boost": BOOST_LEXICAL,
}
}
)
# Semantic KNN clauses
should_clauses.extend(
[
{
"knn": {
"field": "display_name_vector",
"query_vector": query_vector,
"similarity": SIMILARITY_THRESHOLD,
"boost": BOOST_DISPLAY_NAME_VECTOR,
"k": 500,
"num_candidates": 500,
}
},
{
"knn": {
"field": "description_vector",
"query_vector": query_vector,
"similarity": SIMILARITY_THRESHOLD,
"boost": BOOST_DESCRIPTION_VECTOR,
"k": 500,
"num_candidates": 500,
}
},
{
"nested": {
"path": "keyword_vectors",
"query": {
"knn": {
"field": "keyword_vectors.vector",
"query_vector": query_vector,
"similarity": SIMILARITY_THRESHOLD,
"k": 500,
"num_candidates": 500,
body = {
"query": {
"bool": {
"should": [
{
"multi_match": {
"query": query,
"fields": [
"display_name^3",
"keywords^2",
"description^1"
],
"boost": 1.0
}
},
"score_mode": "max",
"boost": BOOST_KEYWORD_VECTORS,
}
},
]
)
body = {
"query": {"bool": {"should": should_clauses}},
"_source": {
"excludes": [
"display_name_vector",
"description_vector",
"keyword_vectors",
"description",
] # remove unrequired fields
{
"knn": {
"field": "display_name_vector",
"query_vector": query_vector,
"k": limit,
"num_candidates": 100,
"similarity": 0.62,
"boost": 2.0
}
},
{
"nested": {
"path": "description_vectors",
"query": {
"knn": {
"field": "description_vectors.vector",
"query_vector": query_vector,
"k": limit,
"num_candidates": 100,
"similarity": 0.62
}
},
"score_mode": "max",
"boost": 1.0
}
}
]
}
},
"size": limit,
"_source": {
"excludes": ["display_name_vector", "description_vectors", "description", "siblings"] # remove unrequired fields (description, sibling currently not needed)
},
"size": limit
}
try:
raw_results = elasticsearch.search(
index="topicvectors", body=body, cluster="nes"
index="topicvectors",
body=body,
cluster="nes"
)
except Exception as exc:
logger.exception("Elasticsearch vector search failed.")
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail=f"Elasticsearch vector search failed: {exc}",
detail=f"Elasticsearch vector search failed: {exc}"
)
# 3. Format result
hits = raw_results.get("hits", {}).get("hits", [])
# Log scores to JSON for threshold analysis TODO: Remove after finetune
try:
from .score_logger import log_scores_to_json
log_scores_to_json(hits, query)
except Exception as exc:
logger.warning(f"Could not log search scores: {exc}")
total = len(hits)
results = [hit.get("_source", {}) for hit in hits]
data = {"meta": {"count": total, "page": 1, "per_page": limit}, "results": results}
data = {
"meta": {
"count": total,
"page": 1,
"per_page": limit
},
"results": results
}
try:
normalized_data = _normalize_topics_response(data)
return TopicsListResponse.from_dict(normalized_data) or TopicsListResponse()
@@ -402,3 +382,4 @@ async def vector_search_topics(
status_code=HTTP_502_BAD_GATEWAY,
detail="Vector search response could not be parsed.",
) from exc
@@ -0,0 +1,36 @@
import json
from pathlib import Path
from typing import Any, Dict, List
def log_scores_to_json(hits: List[Dict[str, Any]], query: str) -> None:
"""
Utility function to log the names and scores of all vector search hits to a JSON file.
This helps in debugging and manually tweaking the similarity score thresholds.
"""
scores_data = []
for hit in hits:
source = hit.get("_source", {})
topic_name = source.get("display_name") or source.get("name") or "Unknown"
score = hit.get("_score", 0.0)
scores_data.append({
"topic_name": topic_name,
"score": score
})
data_dir = Path("/data")
output_file = data_dir / "search_scores.json"
log_payload = {
"query": query,
"max_score": hits[0].get("_score", 0.0) if hits else 0.0,
"results": scores_data
}
try:
with open(output_file, "w", encoding="utf-8") as f:
json.dump(log_payload, f, indent=2, ensure_ascii=False)
print(f"DEBUG: Saved search scores for query '{query}' to {output_file}")
except Exception as exc:
print(f"DEBUG: Failed to save search scores: {exc}")
-5
View File
@@ -129,14 +129,9 @@ async def vector_search_topics(
int,
Query(description="Maximum number of topics to return.", ge=1, le=100),
] = 25,
search_type: Annotated[
str,
Query(alias="searchType", description="Search approach: 'hybrid' or 'semantic'."),
] = "hybrid",
):
return await logic.vector_search_topics(
query=query,
limit=limit,
search_type=search_type,
)
@@ -0,0 +1,113 @@
import logging
from typing import List, Dict, Any
from .model import UniversityTopicData, YearlyData, UniversityRanking, ResearchTopic, DashboardMetric, RankingResponse
from inse.integrations import elasticsearch
logger = logging.getLogger(__name__)
START_YEAR = 2015
END_YEAR = 2026
async def get_ranking_data(topic: ResearchTopic, metric: DashboardMetric) -> RankingResponse:
"""
Fetches real data from Elasticsearch and computes metrics for the dashboard.
"""
query = {
"bool": {
"must": [
{
"match_phrase": {
"topics.display_name": topic
}
},
{
"term": {
"geo.country_code": "DE"
}
}
]
}
}
# Fetch top institutions for the topic by works_count
res = elasticsearch.search(
index="openalex-institutions",
query=query,
size=10,
sort=[{"works_count": "desc"}],
cluster="nes"
)
hits = res.get("hits", {}).get("hits", [])
timeseries: List[UniversityTopicData] = []
for hit in hits:
source = hit["_source"]
# Map the counts_by_year from ES to our model
# We ensure every year from START_YEAR to END_YEAR is present, defaulting to 0
es_counts = {c["year"]: c for c in source.get("counts_by_year", [])}
yearly_data = []
for year in range(START_YEAR, END_YEAR + 1):
count_item = es_counts.get(year, {})
yearly_data.append(YearlyData(
year=year,
publications=count_item.get("works_count", 0),
citations=count_item.get("cited_by_count", 0)
))
timeseries.append(UniversityTopicData(
university=source.get("display_name", "Unknown"),
topic=topic,
yearly_data=yearly_data
))
rankings = _compute_rankings(timeseries, metric)
return RankingResponse(timeseries=timeseries, rankings=rankings)
def _compute_rankings(data: List[UniversityTopicData], metric: DashboardMetric) -> List[UniversityRanking]:
"""Computes ranking metrics based on the timeseries data."""
latest_year = END_YEAR
five_years_ago = latest_year - 5
three_years_ago = latest_year - 3
processed: List[Dict[str, Any]] = []
for item in data:
latest = next((d for d in item.yearly_data if d.year == latest_year), YearlyData(year=latest_year, publications=0, citations=0))
prev = next((d for d in item.yearly_data if d.year == latest_year - 1), YearlyData(year=latest_year-1, publications=0, citations=0))
start_range = next((d for d in item.yearly_data if d.year == five_years_ago), YearlyData(year=five_years_ago, publications=0, citations=0))
mover_range = next((d for d in item.yearly_data if d.year == three_years_ago), YearlyData(year=three_years_ago, publications=0, citations=0))
curr_val = getattr(latest, metric) or 0
prev_val = getattr(prev, metric) or 0
old_val = getattr(start_range, metric) or 0
mover_old_val = getattr(mover_range, metric) or 0
growth_rate = ((curr_val - old_val) / old_val * 100) if old_val > 0 else 0
recent_growth = ((curr_val - mover_old_val) / mover_old_val * 100) if mover_old_val > 0 else 0
processed.append({
"university": item.university,
"publications": latest.publications,
"citations": latest.citations,
"growth_rate": growth_rate,
"trend": 'up' if curr_val > prev_val else ('down' if curr_val < prev_val else 'stable'),
"recent_growth": recent_growth,
"sort_val": curr_val
})
processed.sort(key=lambda x: x["sort_val"], reverse=True)
# Top movers: top 2 by recent growth
growth_sorted = sorted([p["recent_growth"] for p in processed], reverse=True)
threshold = growth_sorted[1] if len(growth_sorted) > 1 else 0
return [
UniversityRanking(
rank=i + 1,
is_top_mover=p["recent_growth"] >= threshold and p["recent_growth"] > 0,
**{k: v for k, v in p.items() if k != "sort_val" and k != "recent_growth"}
)
for i, p in enumerate(processed)
]
@@ -0,0 +1,30 @@
from pydantic import BaseModel
from typing import List, Literal
ResearchTopic = Literal['Artificial Intelligence', 'Quantum Computing', 'Renewable Energy', 'Biotechnology']
DashboardMetric = Literal['publications', 'citations']
class YearlyData(BaseModel):
year: int
publications: int
citations: int
class UniversityTopicData(BaseModel):
university: str
topic: ResearchTopic
yearly_data: List[YearlyData]
class UniversityRanking(BaseModel):
rank: int
university: str
publications: int
citations: int
growth_rate: float
trend: Literal['up', 'down', 'stable']
is_top_mover: bool
class RankingResponse(BaseModel):
# Raw timeseries data for the ECharts line race
timeseries: List[UniversityTopicData]
# Computed metrics for the ranking table
rankings: List[UniversityRanking]
@@ -0,0 +1,23 @@
from fastapi import APIRouter, Query
from . import service
from .model import RankingResponse, ResearchTopic, DashboardMetric
from inse.tags import Tags
router = APIRouter(
prefix="/api/inse-service/university-rankings",
tags=[Tags.INSTITUTIONS]
)
@router.get(
"",
response_model=RankingResponse,
summary="Returns data for the University Ranking Dashboard."
)
async def get_rankings(
topic: ResearchTopic = Query(
...,
description="Research topic (e.g., 'Artificial Intelligence')"
),
metric: DashboardMetric = Query("publications", description="Metric to rank by")
):
return await service.get_university_dashboard_data(topic, metric)
@@ -0,0 +1,6 @@
from . import logic
from .model import RankingResponse, ResearchTopic, DashboardMetric
async def get_university_dashboard_data(topic: ResearchTopic, metric: DashboardMetric) -> RankingResponse:
"""Orchestrates data retrieval and computation for the dashboard."""
return await logic.get_ranking_data(topic, metric)
+1 -3
View File
@@ -38,7 +38,6 @@ def get_persons_data(hit:dict):
return author
from sentence_transformers import SentenceTransformer
from .config import settings
# Sentence Transformer Model
_model: SentenceTransformer | None = None
@@ -56,6 +55,5 @@ def get_model():
if os.environ.get("SENTENCE_TRANSFORMERS_HOME") == "/models":
os.environ["HF_HUB_OFFLINE"] = "1"
model_name = settings.sentence_transformers_model_name
_model = SentenceTransformer(model_name)
_model = SentenceTransformer("paraphrase-multilingual-mpnet-base-v2")
return _model
+14 -160
View File
@@ -29,26 +29,6 @@ from .search_client import OpenAlexWorksSearchClient
logger = logging.getLogger(__name__)
TOPIC_DETAIL_SOURCE_FIELDS = [
"id",
"display_name",
"description",
"subfield",
"field",
"domain",
]
TOPIC_HIERARCHY_DESCRIPTION_INDICES = {
"subfield": "openalex-subfields",
"field": "openalex-fields",
"domain": "openalex-domains",
}
TOPIC_HIERARCHY_DESCRIPTION_SOURCE_FIELDS = [
"id",
"description",
]
async def get_author_works(
author_id: str,
@@ -141,7 +121,6 @@ async def get_primary_topic_counts(
name=name,
count=item["count"],
description=info.get("description"),
**_topic_hierarchy_fields(info),
)
)
@@ -229,7 +208,7 @@ def _get_topic_details(topic_ids: List[str]) -> dict[str, dict]:
response = elasticsearch.search(
index="openalex-topics",
query={"terms": {"id": topic_ids}},
source=TOPIC_DETAIL_SOURCE_FIELDS,
source=["id", "display_name", "description"],
size=len(topic_ids),
)
except httpx.HTTPError:
@@ -246,94 +225,11 @@ def _get_topic_details(topic_ids: List[str]) -> dict[str, dict]:
details[topic_id] = {
"display_name": source.get("display_name"),
"description": source.get("description"),
"subfield": _extract_topic_hierarchy_item(source, "subfield"),
"field": _extract_topic_hierarchy_item(source, "field"),
"domain": _extract_topic_hierarchy_item(source, "domain"),
}
_enrich_topic_hierarchy_descriptions(details)
return details
def _extract_topic_hierarchy_item(source: dict, key: str) -> dict[str, str | None]:
hierarchy_item = source.get(key)
if not isinstance(hierarchy_item, dict):
return {"id": None, "display_name": None, "description": None}
return {
"id": hierarchy_item.get("id"),
"display_name": hierarchy_item.get("display_name"),
"description": hierarchy_item.get("description"),
}
def _enrich_topic_hierarchy_descriptions(details: dict[str, dict]) -> None:
for hierarchy_key, index in TOPIC_HIERARCHY_DESCRIPTION_INDICES.items():
hierarchy_ids = {
item.get(hierarchy_key, {}).get("id")
for item in details.values()
if item.get(hierarchy_key, {}).get("id")
}
descriptions = _get_topic_hierarchy_descriptions(index, list(hierarchy_ids))
for item in details.values():
hierarchy_item = item.get(hierarchy_key) or {}
hierarchy_id = hierarchy_item.get("id")
if hierarchy_id and hierarchy_id in descriptions:
hierarchy_item["description"] = descriptions[hierarchy_id]
def _get_topic_hierarchy_descriptions(
index: str,
hierarchy_ids: list[str],
) -> dict[str, str | None]:
if not hierarchy_ids:
return {}
try:
response = elasticsearch.search(
index=index,
query={"terms": {"id": hierarchy_ids}},
source=TOPIC_HIERARCHY_DESCRIPTION_SOURCE_FIELDS,
size=len(hierarchy_ids),
)
except httpx.HTTPError:
logger.exception("Could not load topic hierarchy details from %s.", index)
return {}
descriptions = {}
for hit in response.get("hits", {}).get("hits", []):
source = hit.get("_source", {})
hierarchy_id = source.get("id")
if hierarchy_id:
descriptions[hierarchy_id] = source.get("description")
return descriptions
def _topic_hierarchy_fields(topic_details: dict) -> dict[str, str | None]:
subfield = topic_details.get("subfield") or {}
field = topic_details.get("field") or {}
domain = topic_details.get("domain") or {}
return {
"subfield_id": subfield.get("id"),
"subfield_name": subfield.get("display_name"),
"subfield_description": subfield.get("description"),
"field_id": field.get("id"),
"field_name": field.get("display_name"),
"field_description": field.get("description"),
"domain_id": domain.get("id"),
"domain_name": domain.get("display_name"),
"domain_description": domain.get("description"),
}
def _limit_works_by_complete_years(
work_results: list[Work],
target_publications: int,
@@ -549,7 +445,6 @@ async def _get_topics_by_time_by_author_from_work_pages(
name=topic["name"],
count=topic["count"],
description=info.get("description"),
**_topic_hierarchy_fields(info),
)
)
@@ -567,7 +462,6 @@ async def _get_topics_by_time_by_author_from_work_pages(
name=topic["name"],
count=topic["count"],
description=info.get("description"),
**_topic_hierarchy_fields(info),
)
)
@@ -755,7 +649,9 @@ def _author_works_query(author_id: str) -> dict[str, Any]:
def _parse_year_count_buckets(response: dict) -> list[dict]:
return (
response.get("aggregations", {}).get("publication_years", {}).get("buckets", [])
response.get("aggregations", {})
.get("publication_years", {})
.get("buckets", [])
)
@@ -795,9 +691,13 @@ 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", [])
primary_buckets = (
year_bucket.get("primary_topics", {}).get("buckets", [])
)
topic_buckets = (
year_bucket.get("topics_nested", {}).get("topics", {}).get("buckets", [])
year_bucket.get("topics_nested", {})
.get("topics", {})
.get("buckets", [])
)
for bucket in primary_buckets + topic_buckets:
@@ -823,7 +723,9 @@ def _build_timeline_elements_from_aggregations(
continue
topics = _build_topic_counts_from_buckets(
year_bucket.get("topics_nested", {}).get("topics", {}).get("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,
@@ -874,13 +776,11 @@ def _build_topic_counts_from_buckets(
name=display_name,
count=count,
description=info.get("description"),
**_topic_hierarchy_fields(info),
)
)
return topics
async def _search_author_works_data(
search_client: OpenAlexWorksSearchClient,
author_id: str,
@@ -960,50 +860,4 @@ def _parse_full_work_search_response(data: dict) -> tuple[list[Work], int]:
detail="OpenAlex works search response could not be parsed.",
) 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
return elements, total
@@ -32,7 +32,6 @@ class OpenAlexWorksSearchClient:
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,
+11
View File
@@ -7,11 +7,13 @@ REST API for publication works.
from typing import Annotated
from fastapi import APIRouter
from fastapi import Depends
from fastapi import Path
from fastapi import Query
from inse.tags import Tags
from .. import security
from . import logic
from inse.models.openalex.work_page import WorkPage
from inse.models.openalex.work import Work
@@ -54,6 +56,9 @@ async def get_author_works(
list[str] | None,
Query(description="Filter by OpenAlex topic id. Can be repeated."),
] = None,
principal: security.Principal = Depends(
security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])
),
):
return await logic.get_author_works(
author_id,
@@ -73,6 +78,7 @@ async def get_author_works(
summary="Returns all works for an author.")
async def get_all_author_works(
author_id: Annotated[str, Path(description="The author id, for example A5023888391.")],
principal: security.Principal = Depends(security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])),
):
return await logic.get_all_author_works(author_id)
@@ -83,6 +89,7 @@ async def get_all_author_works(
summary="Returns work counts per primary topic for an author.")
async def get_primary_topic_counts(
author_id: Annotated[str, Path(description="The author id, for example A5023888391.")],
principal: security.Principal = Depends(security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])),
):
return await logic.get_primary_topic_counts(author_id)
@@ -105,6 +112,7 @@ async def get_topics_by_time_by_author(
bool,
Query(description="If true, all publications are used for the timeline."),
] = False,
principal: security.Principal = Depends(security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])),
):
return await logic.get_topics_by_time_by_author(
author_id,
@@ -124,5 +132,8 @@ async def get_work(
work_id: Annotated[
str, Path(description="The OpenAlex work id, for example W2741809807.")
],
principal: security.Principal = Depends(
security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])
),
):
return await logic.get_work(work_id)
+68 -68
View File
@@ -2,10 +2,8 @@ version = 1
revision = 3
requires-python = ">=3.12"
resolution-markers = [
"python_full_version >= '3.14' and sys_platform != 'darwin'",
"python_full_version < '3.14' and sys_platform != 'darwin'",
"python_full_version >= '3.14' and sys_platform == 'darwin'",
"python_full_version < '3.14' and sys_platform == 'darwin'",
"sys_platform != 'darwin'",
"sys_platform == 'darwin'",
]
[[package]]
@@ -39,49 +37,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/da/42/e921fccf5015463e32a3cf6ee7f980a6ed0f395ceeaa45060b61d86486c2/anyio-4.13.0-py3-none-any.whl", hash = "sha256:08b310f9e24a9594186fd75b4f73f4a4152069e3853f1ed8bfbf58369f4ad708", size = 114353, upload-time = "2026-03-24T12:59:08.246Z" },
]
[[package]]
name = "argon2-cffi"
version = "25.1.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "argon2-cffi-bindings" },
]
sdist = { url = "https://files.pythonhosted.org/packages/0e/89/ce5af8a7d472a67cc819d5d998aa8c82c5d860608c4db9f46f1162d7dab9/argon2_cffi-25.1.0.tar.gz", hash = "sha256:694ae5cc8a42f4c4e2bf2ca0e64e51e23a040c6a517a85074683d3959e1346c1", size = 45706, upload-time = "2025-06-03T06:55:32.073Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/4f/d3/a8b22fa575b297cd6e3e3b0155c7e25db170edf1c74783d6a31a2490b8d9/argon2_cffi-25.1.0-py3-none-any.whl", hash = "sha256:fdc8b074db390fccb6eb4a3604ae7231f219aa669a2652e0f20e16ba513d5741", size = 14657, upload-time = "2025-06-03T06:55:30.804Z" },
]
[[package]]
name = "argon2-cffi-bindings"
version = "25.1.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "cffi" },
]
sdist = { url = "https://files.pythonhosted.org/packages/5c/2d/db8af0df73c1cf454f71b2bbe5e356b8c1f8041c979f505b3d3186e520a9/argon2_cffi_bindings-25.1.0.tar.gz", hash = "sha256:b957f3e6ea4d55d820e40ff76f450952807013d361a65d7f28acc0acbf29229d", size = 1783441, upload-time = "2025-07-30T10:02:05.147Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/60/97/3c0a35f46e52108d4707c44b95cfe2afcafc50800b5450c197454569b776/argon2_cffi_bindings-25.1.0-cp314-cp314t-macosx_10_13_universal2.whl", hash = "sha256:3d3f05610594151994ca9ccb3c771115bdb4daef161976a266f0dd8aa9996b8f", size = 54393, upload-time = "2025-07-30T10:01:40.97Z" },
{ url = "https://files.pythonhosted.org/packages/9d/f4/98bbd6ee89febd4f212696f13c03ca302b8552e7dbf9c8efa11ea4a388c3/argon2_cffi_bindings-25.1.0-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:8b8efee945193e667a396cbc7b4fb7d357297d6234d30a489905d96caabde56b", size = 29328, upload-time = "2025-07-30T10:01:41.916Z" },
{ url = "https://files.pythonhosted.org/packages/43/24/90a01c0ef12ac91a6be05969f29944643bc1e5e461155ae6559befa8f00b/argon2_cffi_bindings-25.1.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:3c6702abc36bf3ccba3f802b799505def420a1b7039862014a65db3205967f5a", size = 31269, upload-time = "2025-07-30T10:01:42.716Z" },
{ url = "https://files.pythonhosted.org/packages/d4/d3/942aa10782b2697eee7af5e12eeff5ebb325ccfb86dd8abda54174e377e4/argon2_cffi_bindings-25.1.0-cp314-cp314t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a1c70058c6ab1e352304ac7e3b52554daadacd8d453c1752e547c76e9c99ac44", size = 86558, upload-time = "2025-07-30T10:01:43.943Z" },
{ url = "https://files.pythonhosted.org/packages/0d/82/b484f702fec5536e71836fc2dbc8c5267b3f6e78d2d539b4eaa6f0db8bf8/argon2_cffi_bindings-25.1.0-cp314-cp314t-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e2fd3bfbff3c5d74fef31a722f729bf93500910db650c925c2d6ef879a7e51cb", size = 92364, upload-time = "2025-07-30T10:01:44.887Z" },
{ url = "https://files.pythonhosted.org/packages/c9/c1/a606ff83b3f1735f3759ad0f2cd9e038a0ad11a3de3b6c673aa41c24bb7b/argon2_cffi_bindings-25.1.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:c4f9665de60b1b0e99bcd6be4f17d90339698ce954cfd8d9cf4f91c995165a92", size = 85637, upload-time = "2025-07-30T10:01:46.225Z" },
{ url = "https://files.pythonhosted.org/packages/44/b4/678503f12aceb0262f84fa201f6027ed77d71c5019ae03b399b97caa2f19/argon2_cffi_bindings-25.1.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:ba92837e4a9aa6a508c8d2d7883ed5a8f6c308c89a4790e1e447a220deb79a85", size = 91934, upload-time = "2025-07-30T10:01:47.203Z" },
{ url = "https://files.pythonhosted.org/packages/f0/c7/f36bd08ef9bd9f0a9cff9428406651f5937ce27b6c5b07b92d41f91ae541/argon2_cffi_bindings-25.1.0-cp314-cp314t-win32.whl", hash = "sha256:84a461d4d84ae1295871329b346a97f68eade8c53b6ed9a7ca2d7467f3c8ff6f", size = 28158, upload-time = "2025-07-30T10:01:48.341Z" },
{ url = "https://files.pythonhosted.org/packages/b3/80/0106a7448abb24a2c467bf7d527fe5413b7fdfa4ad6d6a96a43a62ef3988/argon2_cffi_bindings-25.1.0-cp314-cp314t-win_amd64.whl", hash = "sha256:b55aec3565b65f56455eebc9b9f34130440404f27fe21c3b375bf1ea4d8fbae6", size = 32597, upload-time = "2025-07-30T10:01:49.112Z" },
{ url = "https://files.pythonhosted.org/packages/05/b8/d663c9caea07e9180b2cb662772865230715cbd573ba3b5e81793d580316/argon2_cffi_bindings-25.1.0-cp314-cp314t-win_arm64.whl", hash = "sha256:87c33a52407e4c41f3b70a9c2d3f6056d88b10dad7695be708c5021673f55623", size = 28231, upload-time = "2025-07-30T10:01:49.92Z" },
{ url = "https://files.pythonhosted.org/packages/1d/57/96b8b9f93166147826da5f90376e784a10582dd39a393c99bb62cfcf52f0/argon2_cffi_bindings-25.1.0-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:aecba1723ae35330a008418a91ea6cfcedf6d31e5fbaa056a166462ff066d500", size = 54121, upload-time = "2025-07-30T10:01:50.815Z" },
{ url = "https://files.pythonhosted.org/packages/0a/08/a9bebdb2e0e602dde230bdde8021b29f71f7841bd54801bcfd514acb5dcf/argon2_cffi_bindings-25.1.0-cp39-abi3-macosx_10_9_x86_64.whl", hash = "sha256:2630b6240b495dfab90aebe159ff784d08ea999aa4b0d17efa734055a07d2f44", size = 29177, upload-time = "2025-07-30T10:01:51.681Z" },
{ url = "https://files.pythonhosted.org/packages/b6/02/d297943bcacf05e4f2a94ab6f462831dc20158614e5d067c35d4e63b9acb/argon2_cffi_bindings-25.1.0-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:7aef0c91e2c0fbca6fc68e7555aa60ef7008a739cbe045541e438373bc54d2b0", size = 31090, upload-time = "2025-07-30T10:01:53.184Z" },
{ url = "https://files.pythonhosted.org/packages/c1/93/44365f3d75053e53893ec6d733e4a5e3147502663554b4d864587c7828a7/argon2_cffi_bindings-25.1.0-cp39-abi3-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1e021e87faa76ae0d413b619fe2b65ab9a037f24c60a1e6cc43457ae20de6dc6", size = 81246, upload-time = "2025-07-30T10:01:54.145Z" },
{ url = "https://files.pythonhosted.org/packages/09/52/94108adfdd6e2ddf58be64f959a0b9c7d4ef2fa71086c38356d22dc501ea/argon2_cffi_bindings-25.1.0-cp39-abi3-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d3e924cfc503018a714f94a49a149fdc0b644eaead5d1f089330399134fa028a", size = 87126, upload-time = "2025-07-30T10:01:55.074Z" },
{ url = "https://files.pythonhosted.org/packages/72/70/7a2993a12b0ffa2a9271259b79cc616e2389ed1a4d93842fac5a1f923ffd/argon2_cffi_bindings-25.1.0-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:c87b72589133f0346a1cb8d5ecca4b933e3c9b64656c9d175270a000e73b288d", size = 80343, upload-time = "2025-07-30T10:01:56.007Z" },
{ url = "https://files.pythonhosted.org/packages/78/9a/4e5157d893ffc712b74dbd868c7f62365618266982b64accab26bab01edc/argon2_cffi_bindings-25.1.0-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:1db89609c06afa1a214a69a462ea741cf735b29a57530478c06eb81dd403de99", size = 86777, upload-time = "2025-07-30T10:01:56.943Z" },
{ url = "https://files.pythonhosted.org/packages/74/cd/15777dfde1c29d96de7f18edf4cc94c385646852e7c7b0320aa91ccca583/argon2_cffi_bindings-25.1.0-cp39-abi3-win32.whl", hash = "sha256:473bcb5f82924b1becbb637b63303ec8d10e84c8d241119419897a26116515d2", size = 27180, upload-time = "2025-07-30T10:01:57.759Z" },
{ url = "https://files.pythonhosted.org/packages/e2/c6/a759ece8f1829d1f162261226fbfd2c6832b3ff7657384045286d2afa384/argon2_cffi_bindings-25.1.0-cp39-abi3-win_amd64.whl", hash = "sha256:a98cd7d17e9f7ce244c0803cad3c23a7d379c301ba618a5fa76a67d116618b98", size = 31715, upload-time = "2025-07-30T10:01:58.56Z" },
{ url = "https://files.pythonhosted.org/packages/42/b9/f8d6fa329ab25128b7e98fd83a3cb34d9db5b059a9847eddb840a0af45dd/argon2_cffi_bindings-25.1.0-cp39-abi3-win_arm64.whl", hash = "sha256:b0fdbcf513833809c882823f98dc2f931cf659d9a1429616ac3adebb49f5db94", size = 27149, upload-time = "2025-07-30T10:01:59.329Z" },
]
[[package]]
name = "certifi"
version = "2026.5.20"
@@ -223,6 +178,36 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/b2/b7/545d2c10c1fc15e48653c91efde329a790f2eecfbbf2bd16003b5db2bab0/dotenv-0.9.9-py2.py3-none-any.whl", hash = "sha256:29cf74a087b31dafdb5a446b6d7e11cbce8ed2741540e2339c69fbef92c94ce9", size = 1892, upload-time = "2025-02-19T22:15:01.647Z" },
]
[[package]]
name = "elastic-transport"
version = "9.4.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "certifi" },
{ name = "sniffio" },
{ name = "urllib3" },
]
sdist = { url = "https://files.pythonhosted.org/packages/0f/a8/dd1431b95daa54d4859c1d250362433df6df9cfaab7bfac3eafd410d019a/elastic_transport-9.4.1.tar.gz", hash = "sha256:d12c86ea73528690ebf63a488d9ae323292e6aa5ee55e1e29f14293472f4197f", size = 79170, upload-time = "2026-05-25T14:16:47.416Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/5c/f6/508c1e541b840b6eaf60a46a8994ba55affd07bf6a311cffc860781ae06a/elastic_transport-9.4.1-py3-none-any.whl", hash = "sha256:186a29e6c66ff269487e33f7b17176316e18b6061702c25eb0bb15681302e91d", size = 66229, upload-time = "2026-05-25T14:16:45.882Z" },
]
[[package]]
name = "elasticsearch"
version = "9.4.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "anyio" },
{ name = "elastic-transport" },
{ name = "python-dateutil" },
{ name = "sniffio" },
{ name = "typing-extensions" },
]
sdist = { url = "https://files.pythonhosted.org/packages/e0/4b/9b753f0a8f56ae508dced2f7ac87bef7a27ce8f890e349e16812e9f7f4fa/elasticsearch-9.4.1.tar.gz", hash = "sha256:1d78fdfba97a903ec35a5eb5808a74e33392b7c620bd5f742d465a3a26c27d75", size = 908138, upload-time = "2026-05-26T16:28:40.132Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/cf/8e/2c93805e93e724a90156004a9212572ec86473974deede4605a33b8b169a/elasticsearch-9.4.1-py3-none-any.whl", hash = "sha256:71ab71c3d1b20fd88c2922fb82c3277cce7ea03c160686e7b9368b265c2b4cac", size = 993647, upload-time = "2026-05-26T16:28:36.556Z" },
]
[[package]]
name = "fastapi"
version = "0.115.14"
@@ -814,6 +799,18 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/f0/d7/a812a0bd0f5160823e647524488cc9734f93782f2c273b8f77e8afc60a37/pytest-8.1.2-py3-none-any.whl", hash = "sha256:6c06dc309ff46a05721e6fd48e492a775ed8165d2ecdf57f156a80c7e95bb142", size = 337456, upload-time = "2024-04-26T18:05:15.452Z" },
]
[[package]]
name = "python-dateutil"
version = "2.9.0.post0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "six" },
]
sdist = { url = "https://files.pythonhosted.org/packages/66/c0/0c8b6ad9f17a802ee498c46e004a0eb49bc148f2fd230864601a86dcf6db/python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 342432, upload-time = "2024-03-01T18:36:20.211Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892, upload-time = "2024-03-01T18:36:18.57Z" },
]
[[package]]
name = "python-dotenv"
version = "1.2.2"
@@ -1128,9 +1125,9 @@ name = "service"
version = "0.1.0"
source = { virtual = "." }
dependencies = [
{ name = "argon2-cffi" },
{ name = "cryptography" },
{ name = "dotenv" },
{ name = "elasticsearch" },
{ name = "fastapi" },
{ name = "httpx" },
{ name = "openai" },
@@ -1141,7 +1138,7 @@ dependencies = [
{ name = "python-multipart" },
{ name = "pyyaml" },
{ name = "sentence-transformers" },
{ name = "sqlmodel" },
{ name = "sqlalchemy" },
{ name = "torch", version = "2.12.0", source = { registry = "https://download.pytorch.org/whl/cpu" }, marker = "sys_platform == 'darwin'" },
{ name = "torch", version = "2.12.0+cpu", source = { registry = "https://download.pytorch.org/whl/cpu" }, marker = "sys_platform != 'darwin'" },
{ name = "uvicorn" },
@@ -1149,9 +1146,9 @@ dependencies = [
[package.metadata]
requires-dist = [
{ name = "argon2-cffi", specifier = "~=25.1.0" },
{ name = "cryptography", specifier = "~=42.0.0" },
{ name = "dotenv", specifier = ">=0.9.9" },
{ name = "elasticsearch", specifier = "~=9.4.0" },
{ name = "fastapi", specifier = "~=0.115.0" },
{ name = "httpx", specifier = "~=0.27.0" },
{ name = "openai", specifier = "~=2.41.0" },
@@ -1162,7 +1159,7 @@ requires-dist = [
{ name = "python-multipart", specifier = "~=0.0.19" },
{ name = "pyyaml", specifier = "~=6.0.1" },
{ name = "sentence-transformers", specifier = "~=5.5.1" },
{ name = "sqlmodel", specifier = "~=0.0.33" },
{ name = "sqlalchemy", specifier = "~=2.0.0" },
{ name = "torch", index = "https://download.pytorch.org/whl/cpu" },
{ name = "uvicorn", specifier = "~=0.29.0" },
]
@@ -1185,6 +1182,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/e0/f9/0595336914c5619e5f28a1fb793285925a8cd4b432c9da0a987836c7f822/shellingham-1.5.4-py2.py3-none-any.whl", hash = "sha256:7ecfff8f2fd72616f7481040475a65b2bf8af90a56c89140852d1120324e8686", size = 9755, upload-time = "2023-10-24T04:13:38.866Z" },
]
[[package]]
name = "six"
version = "1.17.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031, upload-time = "2024-12-04T17:35:28.174Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" },
]
[[package]]
name = "sniffio"
version = "1.3.1"
@@ -1235,19 +1241,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/d0/10/f7220e9b784d295d241c86ed99aeb537f92afcd469a64861f2717e9bb077/sqlalchemy-2.0.50-py3-none-any.whl", hash = "sha256:92064363517a3ff8212b5a93b8c62876579d8dfd1ca5b561335f30152d884fa9", size = 1943861, upload-time = "2026-05-24T19:59:01.119Z" },
]
[[package]]
name = "sqlmodel"
version = "0.0.33"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "pydantic" },
{ name = "sqlalchemy" },
]
sdist = { url = "https://files.pythonhosted.org/packages/c4/62/22c287122598e61d07d005eec0b4eb97e6bde9a1b051bcd66c2bca846ea8/sqlmodel-0.0.33.tar.gz", hash = "sha256:b473544ed5fc2097894d89033049e569e1f138363dd3ec2ed4b6932cc9f29f5f", size = 95578, upload-time = "2026-02-11T15:23:39.504Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/63/39/13891bae4658133b489a4d8b6a2f193d56110e392289560f312748e796dc/sqlmodel-0.0.33-py3-none-any.whl", hash = "sha256:9045bb4d97d2ba099c5a068ee9525af2d106972dda1ff8488e187ce50556bf73", size = 27444, upload-time = "2026-02-11T15:23:38.678Z" },
]
[[package]]
name = "starlette"
version = "0.46.2"
@@ -1312,8 +1305,7 @@ name = "torch"
version = "2.12.0"
source = { registry = "https://download.pytorch.org/whl/cpu" }
resolution-markers = [
"python_full_version >= '3.14' and sys_platform == 'darwin'",
"python_full_version < '3.14' and sys_platform == 'darwin'",
"sys_platform == 'darwin'",
]
dependencies = [
{ name = "filelock", marker = "sys_platform == 'darwin'" },
@@ -1337,8 +1329,7 @@ name = "torch"
version = "2.12.0+cpu"
source = { registry = "https://download.pytorch.org/whl/cpu" }
resolution-markers = [
"python_full_version >= '3.14' and sys_platform != 'darwin'",
"python_full_version < '3.14' and sys_platform != 'darwin'",
"sys_platform != 'darwin'",
]
dependencies = [
{ name = "filelock", marker = "sys_platform != 'darwin'" },
@@ -1430,6 +1421,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/18/67/36e9267722cc04a6b9f15c7f3441c2363321a3ea07da7ae0c0707beb2a9c/typing_extensions-4.15.0-py3-none-any.whl", hash = "sha256:f0fa19c6845758ab08074a0cfa8b7aecb71c999ca73d62883bc25cc018c4e548", size = 44614, upload-time = "2025-08-25T13:49:24.86Z" },
]
[[package]]
name = "urllib3"
version = "2.7.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/53/0c/06f8b233b8fd13b9e5ee11424ef85419ba0d8ba0b3138bf360be2ff56953/urllib3-2.7.0.tar.gz", hash = "sha256:231e0ec3b63ceb14667c67be60f2f2c40a518cb38b03af60abc813da26505f4c", size = 433602, upload-time = "2026-05-07T16:13:18.596Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/7f/3e/5db95bcf282c52709639744ca2a8b149baccf648e39c8cc87553df9eae0c/urllib3-2.7.0-py3-none-any.whl", hash = "sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897", size = 131087, upload-time = "2026-05-07T16:13:17.151Z" },
]
[[package]]
name = "uvicorn"
version = "0.29.0"
+4 -187
View File
@@ -17,21 +17,6 @@ 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==
@@ -62,73 +47,6 @@ Content-Type: application/json
}
}
# 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==
@@ -161,26 +79,6 @@ 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": {
@@ -203,38 +101,6 @@ 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_*_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==
@@ -266,27 +132,18 @@ Content-Type: application/json
"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"
]
"term": {
"name.keyword": "UNIVERSITAET DUISBURG-ESSEN"
}
}
]
}
},
"aggs": {
"organisation_ids": {
"specific_org_rcn_values": {
"terms": {
"field": "organisationID",
"size": 10000
"size": 1000
}
}
}
@@ -1195,46 +1052,6 @@ Content-Type: application/json
###
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"
}
}
]
}
}
}
###
GET https://project.nes.uni-due.de/elastic/openalex-authors/_search
Authorization: ApiKey am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ==
Content-Type: application/json
+1 -1
View File
@@ -3,7 +3,7 @@
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve --proxy-config src/proxy.conf.json",
"start": "ng serve",
"build": "ng build",
"generate:api": "openapi-generator-cli generate --generator-key inse-service",
"watch": "ng build --watch --configuration development",
+11 -27
View File
@@ -4,13 +4,12 @@ README.md
api.base.service.ts
api.module.ts
api/api.ts
api/auth.service.ts
api/companyConnections.service.ts
api/funding.service.ts
api/iNSEAccountService.service.ts
api/iNSEService.service.ts
api/institutions.service.ts
api/news.service.ts
api/patents.service.ts
api/items.service.ts
api/personNetwork.service.ts
api/persons.service.ts
api/projects.service.ts
@@ -20,10 +19,9 @@ configuration.ts
encoder.ts
git_push.sh
index.ts
model/accessResponse.ts
model/accessToken.ts
model/accountPage.ts
model/accountProfile.ts
model/accessGrant.ts
model/authAccount.ts
model/authScope.ts
model/author.ts
model/authorAffiliationsInner.ts
model/authorCountsByYearInner.ts
@@ -39,10 +37,7 @@ model/autocompleteResponse.ts
model/autocompleteResponseMeta.ts
model/autocompleteResponseResultsInner.ts
model/award.ts
model/bodyChangePassword.ts
model/bodyGetAccessToken.ts
model/bodyLogin.ts
model/bodyRequestOtk.ts
model/bodyCreateUser.ts
model/bundProject.ts
model/bundProjectDetails.ts
model/bundProjectPage.ts
@@ -55,7 +50,6 @@ model/companyConnectionsResponse.ts
model/cordisEuProject.ts
model/cordisEuProjectPage.ts
model/costUsd.ts
model/createAccountRequest.ts
model/customAuthor.ts
model/customAuthorsListResponse.ts
model/dehydratedAuthor.ts
@@ -65,8 +59,6 @@ model/dehydratedSource.ts
model/dfgProjectDetails.ts
model/dfgProjectPage.ts
model/dfgProjectSummary.ts
model/euOrganizationProjectSummary.ts
model/euOrganizationProjectSummaryPage.ts
model/filterInformation.ts
model/filterProperties.ts
model/funderByAuthor.ts
@@ -76,7 +68,7 @@ model/fundingProjectPage.ts
model/fwci.ts
model/groupByResult.ts
model/hTTPValidationError.ts
model/idToken.ts
model/identityGrant.ts
model/institution.ts
model/institutionFunderSummary.ts
model/institutionGeo.ts
@@ -85,23 +77,18 @@ model/institutionInformation.ts
model/institutionNetworkNode.ts
model/institutionPage.ts
model/institutionsListResponse.ts
model/item.ts
model/itemCreate.ts
model/itemPage.ts
model/keywords.ts
model/latitude.ts
model/location.ts
model/loginResponse.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/organizationProfile.ts
model/patentEntry.ts
model/patentsByAuthorResponse.ts
model/personBio.ts
model/projectType.ts
model/projectsFilteringProperties.ts
@@ -110,10 +97,8 @@ model/publicationDetailByFunder.ts
model/publicationIdsByAuthorPosition.ts
model/publicationsByAuthorResponse.ts
model/rankingResponse.ts
model/refreshToken.ts
model/score.ts
model/sortDirection.ts
model/tokenType.ts
model/topic.ts
model/topicCount.ts
model/topicDomain.ts
@@ -126,8 +111,7 @@ model/topicsByYear.ts
model/topicsListResponse.ts
model/universityRanking.ts
model/universityTopicData.ts
model/updateAccountRequest.ts
model/userRole.ts
model/user.ts
model/validationError.ts
model/validationErrorLocInner.ts
model/value.ts
+5 -7
View File
@@ -1,17 +1,15 @@
export * from './auth.service';
import { AuthService } from './auth.service';
export * from './companyConnections.service';
import { CompanyConnectionsService } from './companyConnections.service';
export * from './funding.service';
import { FundingService } from './funding.service';
export * from './iNSEAccountService.service';
import { INSEAccountServiceService } from './iNSEAccountService.service';
export * from './iNSEService.service';
import { INSEServiceService } from './iNSEService.service';
export * from './institutions.service';
import { InstitutionsService } from './institutions.service';
export * from './news.service';
import { NewsService } from './news.service';
export * from './patents.service';
import { PatentsService } from './patents.service';
export * from './items.service';
import { ItemsService } from './items.service';
export * from './personNetwork.service';
import { PersonNetworkService } from './personNetwork.service';
export * from './persons.service';
@@ -22,4 +20,4 @@ export * from './topics.service';
import { TopicsService } from './topics.service';
export * from './works.service';
import { WorksService } from './works.service';
export const APIS = [AuthService, CompanyConnectionsService, FundingService, INSEServiceService, InstitutionsService, NewsService, PatentsService, PersonNetworkService, PersonsService, ProjectsService, TopicsService, WorksService];
export const APIS = [CompanyConnectionsService, FundingService, INSEAccountServiceService, INSEServiceService, InstitutionsService, ItemsService, PersonNetworkService, PersonsService, ProjectsService, TopicsService, WorksService];
-871
View File
@@ -1,871 +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.
*/
/* 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 { AccessResponse } from '../model/accessResponse';
// @ts-ignore
import { AccessToken } from '../model/accessToken';
// @ts-ignore
import { AccountPage } from '../model/accountPage';
// @ts-ignore
import { AccountProfile } from '../model/accountProfile';
// @ts-ignore
import { BodyChangePassword } from '../model/bodyChangePassword';
// @ts-ignore
import { BodyGetAccessToken } from '../model/bodyGetAccessToken';
// @ts-ignore
import { BodyLogin } from '../model/bodyLogin';
// @ts-ignore
import { BodyRequestOtk } from '../model/bodyRequestOtk';
// @ts-ignore
import { CreateAccountRequest } from '../model/createAccountRequest';
// @ts-ignore
import { HTTPValidationError } from '../model/hTTPValidationError';
// @ts-ignore
import { LoginResponse } from '../model/loginResponse';
// @ts-ignore
import { OrganizationProfile } from '../model/organizationProfile';
// @ts-ignore
import { UpdateAccountRequest } from '../model/updateAccountRequest';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service';
@Injectable({
providedIn: 'root'
})
export class AuthService extends BaseService {
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
super(basePath, configuration);
}
/**
* Change Password
* Change the user\&#39;s password and invalidate existing tokens.
* @endpoint post /api/auth/v2/change-password
* @param bodyChangePassword
* @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 changePassword(bodyChangePassword: BodyChangePassword, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
public changePassword(bodyChangePassword: BodyChangePassword, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
public changePassword(bodyChangePassword: BodyChangePassword, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
public changePassword(bodyChangePassword: BodyChangePassword, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (bodyChangePassword === null || bodyChangePassword === undefined) {
throw new Error('Required parameter bodyChangePassword was null or undefined when calling changePassword.');
}
let localVarHeaders = this.defaultHeaders;
// authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
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/auth/v2/change-password`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<any>('post', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: bodyChangePassword,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Create Account
* @endpoint post /api/accounts
* @param createAccountRequest
* @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 createAccount(createAccountRequest: CreateAccountRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccountProfile>;
public createAccount(createAccountRequest: CreateAccountRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountProfile>>;
public createAccount(createAccountRequest: CreateAccountRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountProfile>>;
public createAccount(createAccountRequest: CreateAccountRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (createAccountRequest === null || createAccountRequest === undefined) {
throw new Error('Required parameter createAccountRequest was null or undefined when calling createAccount.');
}
let localVarHeaders = this.defaultHeaders;
// authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
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/accounts`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<AccountProfile>('post', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: createAccountRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Delete Account
* @endpoint delete /api/accounts/{account_id}
* @param accountId
* @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 deleteAccount(accountId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
public deleteAccount(accountId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
public deleteAccount(accountId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
public deleteAccount(accountId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (accountId === null || accountId === undefined) {
throw new Error('Required parameter accountId was null or undefined when calling deleteAccount.');
}
let localVarHeaders = this.defaultHeaders;
// authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
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/accounts/${this.configuration.encodeParam({name: "accountId", value: accountId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: "uuid"})}`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<any>('delete', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Get Access Token
* Retrieve an access token for the authenticated user.
* @endpoint post /api/auth/v2/access
* @param bodyGetAccessToken
* @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 getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccessResponse>;
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccessResponse>>;
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccessResponse>>;
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (bodyGetAccessToken === null || bodyGetAccessToken === undefined) {
throw new Error('Required parameter bodyGetAccessToken was null or undefined when calling getAccessToken.');
}
let localVarHeaders = this.defaultHeaders;
// authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
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/auth/v2/access`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<AccessResponse>('post', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: bodyGetAccessToken,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Get Current Account
* @endpoint get /api/accounts/me
* @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 getCurrentAccount(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccountProfile>;
public getCurrentAccount(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountProfile>>;
public getCurrentAccount(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountProfile>>;
public getCurrentAccount(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarHeaders = this.defaultHeaders;
// authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
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/accounts/me`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<AccountProfile>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Health Check
* @endpoint get /api/auth/v2/health
* @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 healthCheckApiAuthV2HealthGet(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
public healthCheckApiAuthV2HealthGet(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
public healthCheckApiAuthV2HealthGet(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
public healthCheckApiAuthV2HealthGet(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
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/auth/v2/health`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<any>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* List Organizations
* @endpoint get /api/accounts/organizations
* @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 listAccountOrganizations(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Array<OrganizationProfile>>;
public listAccountOrganizations(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Array<OrganizationProfile>>>;
public listAccountOrganizations(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Array<OrganizationProfile>>>;
public listAccountOrganizations(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarHeaders = this.defaultHeaders;
// authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
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/accounts/organizations`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<OrganizationProfile>>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* List Accounts
* @endpoint get /api/accounts
* @param page
* @param pageSize
* @param offset
* @param search
* @param organizationId
* @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 listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccountPage>;
public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountPage>>;
public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountPage>>;
public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: 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, 'page_size');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>offset, 'offset');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>search, 'search');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>organizationId, 'organization_id');
let localVarHeaders = this.defaultHeaders;
// authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
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/accounts`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<AccountPage>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Login with One-Time Key
* Login using a one-time key (OTK) sent to the user\&#39;s email.
* @endpoint post /api/auth/v2/login
* @param bodyLogin
* @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 login(bodyLogin: BodyLogin, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<LoginResponse>;
public login(bodyLogin: BodyLogin, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<LoginResponse>>;
public login(bodyLogin: BodyLogin, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<LoginResponse>>;
public login(bodyLogin: BodyLogin, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (bodyLogin === null || bodyLogin === undefined) {
throw new Error('Required parameter bodyLogin was null or undefined when calling login.');
}
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/auth/v2/login`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<LoginResponse>('post', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: bodyLogin,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Logout
* Logout the authenticated user.
* @endpoint post /api/auth/v2/logout
* @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 logout(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
public logout(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
public logout(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
public logout(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarHeaders = this.defaultHeaders;
// authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
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/auth/v2/logout`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<any>('post', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Refresh Access Token
* Refresh the access token using a valid refresh token.
* @endpoint post /api/auth/v2/refresh
* @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 refreshAccessToken(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccessToken>;
public refreshAccessToken(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccessToken>>;
public refreshAccessToken(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccessToken>>;
public refreshAccessToken(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarHeaders = this.defaultHeaders;
// authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
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/auth/v2/refresh`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<AccessToken>('post', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Request One-Time Key
* Request a one-time key (OTK) for authentication using email and password.
* @endpoint post /api/auth/v2/request-otk
* @param bodyRequestOtk
* @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 requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (bodyRequestOtk === null || bodyRequestOtk === undefined) {
throw new Error('Required parameter bodyRequestOtk was null or undefined when calling requestOtk.');
}
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/auth/v2/request-otk`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<any>('post', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: bodyRequestOtk,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Update Account
* @endpoint put /api/accounts/{account_id}
* @param accountId
* @param updateAccountRequest
* @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 updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccountProfile>;
public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountProfile>>;
public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountProfile>>;
public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (accountId === null || accountId === undefined) {
throw new Error('Required parameter accountId was null or undefined when calling updateAccount.');
}
if (updateAccountRequest === null || updateAccountRequest === undefined) {
throw new Error('Required parameter updateAccountRequest was null or undefined when calling updateAccount.');
}
let localVarHeaders = this.defaultHeaders;
// authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
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/accounts/${this.configuration.encodeParam({name: "accountId", value: accountId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: "uuid"})}`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<AccountProfile>('put', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: updateAccountRequest,
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 { 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
}
);
}
}
@@ -0,0 +1,282 @@
/**
* 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 { AccessGrant } from '../model/accessGrant';
// @ts-ignore
import { BodyCreateUser } from '../model/bodyCreateUser';
// @ts-ignore
import { HTTPValidationError } from '../model/hTTPValidationError';
// @ts-ignore
import { IdentityGrant } from '../model/identityGrant';
// @ts-ignore
import { User } from '../model/user';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service';
@Injectable({
providedIn: 'root'
})
export class INSEAccountServiceService extends BaseService {
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
super(basePath, configuration);
}
/**
* Create User
* @endpoint post /inse-account/create
* @param bodyCreateUser
* @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 createUser(bodyCreateUser: BodyCreateUser, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<User>;
public createUser(bodyCreateUser: BodyCreateUser, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<User>>;
public createUser(bodyCreateUser: BodyCreateUser, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<User>>;
public createUser(bodyCreateUser: BodyCreateUser, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (bodyCreateUser === null || bodyCreateUser === undefined) {
throw new Error('Required parameter bodyCreateUser was null or undefined when calling createUser.');
}
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 = `/inse-account/create`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<User>('post', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: bodyCreateUser,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Get Access Grant
* @endpoint post /inse-account/auth/access
* @param secret
* @param account
* @param organization
* @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 getAccessGrant(secret: string, account: number, organization: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccessGrant>;
public getAccessGrant(secret: string, account: number, organization: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccessGrant>>;
public getAccessGrant(secret: string, account: number, organization: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccessGrant>>;
public getAccessGrant(secret: string, account: number, organization: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (secret === null || secret === undefined) {
throw new Error('Required parameter secret was null or undefined when calling getAccessGrant.');
}
if (account === null || account === undefined) {
throw new Error('Required parameter account was null or undefined when calling getAccessGrant.');
}
if (organization === null || organization === undefined) {
throw new Error('Required parameter organization was null or undefined when calling getAccessGrant.');
}
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/x-www-form-urlencoded'
];
const canConsumeForm = this.canConsumeForm(consumes);
let localVarFormParams: { append(param: string, value: any): any; };
let localVarUseForm = false;
let localVarConvertFormParamsToString = false;
if (localVarUseForm) {
localVarFormParams = new FormData();
} else {
localVarFormParams = new HttpParams({encoder: this.encoder});
}
if (secret !== undefined) {
localVarFormParams = localVarFormParams.append('secret', <any>secret) as any || localVarFormParams;
}
if (account !== undefined) {
localVarFormParams = localVarFormParams.append('account', <any>account) as any || localVarFormParams;
}
if (organization !== undefined) {
localVarFormParams = localVarFormParams.append('organization', <any>organization) as any || localVarFormParams;
}
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 = `/inse-account/auth/access`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<AccessGrant>('post', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Get Identity Grant
* @endpoint post /inse-account/auth/id
* @param username
* @param password
* @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 getIdentityGrant(username: string, password: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<IdentityGrant>;
public getIdentityGrant(username: string, password: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<IdentityGrant>>;
public getIdentityGrant(username: string, password: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<IdentityGrant>>;
public getIdentityGrant(username: string, password: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (username === null || username === undefined) {
throw new Error('Required parameter username was null or undefined when calling getIdentityGrant.');
}
if (password === null || password === undefined) {
throw new Error('Required parameter password was null or undefined when calling getIdentityGrant.');
}
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/x-www-form-urlencoded'
];
const canConsumeForm = this.canConsumeForm(consumes);
let localVarFormParams: { append(param: string, value: any): any; };
let localVarUseForm = false;
let localVarConvertFormParamsToString = false;
if (localVarUseForm) {
localVarFormParams = new FormData();
} else {
localVarFormParams = new HttpParams({encoder: this.encoder});
}
if (username !== undefined) {
localVarFormParams = localVarFormParams.append('username', <any>username) as any || localVarFormParams;
}
if (password !== undefined) {
localVarFormParams = localVarFormParams.append('password', <any>password) as any || localVarFormParams;
}
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 = `/inse-account/auth/id`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<IdentityGrant>('post', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
}
@@ -18,6 +18,12 @@ import { Observable } from 'rxjs';
// @ts-ignore
import { HTTPValidationError } from '../model/hTTPValidationError';
// @ts-ignore
import { Item } from '../model/item';
// @ts-ignore
import { ItemCreate } from '../model/itemCreate';
// @ts-ignore
import { ItemPage } from '../model/itemPage';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
@@ -35,6 +41,74 @@ export class INSEServiceService extends BaseService {
super(basePath, configuration);
}
/**
* Adds a new item.
* @endpoint post /api/inse-service/items
* @param itemCreate
* @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 addItem(itemCreate: ItemCreate, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Item>;
public addItem(itemCreate: ItemCreate, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Item>>;
public addItem(itemCreate: ItemCreate, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Item>>;
public addItem(itemCreate: ItemCreate, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (itemCreate === null || itemCreate === undefined) {
throw new Error('Required parameter itemCreate was null or undefined when calling addItem.');
}
let localVarHeaders = this.defaultHeaders;
// authentication (bearer) required
localVarHeaders = this.configuration.addCredentialToHeaders('bearer', 'Authorization', localVarHeaders, 'Bearer ');
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/inse-service/items`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Item>('post', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: itemCreate,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Builds the topic hierarchy cache.
* @endpoint get /api/inse-service/topics/cache
@@ -159,6 +233,185 @@ export class INSEServiceService extends BaseService {
);
}
/**
* Deletes the item with the id.
* @endpoint delete /api/inse-service/items/{id}
* @param id The item 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 deleteItem(id: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
public deleteItem(id: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
public deleteItem(id: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
public deleteItem(id: number, 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 deleteItem.');
}
let localVarHeaders = this.defaultHeaders;
// authentication (bearer) required
localVarHeaders = this.configuration.addCredentialToHeaders('bearer', 'Authorization', localVarHeaders, 'Bearer ');
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/items/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: undefined})}`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<any>('delete', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Returns the item with the id.
* @endpoint get /api/inse-service/items/{id}
* @param id The item 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 getItem(id: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Item>;
public getItem(id: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Item>>;
public getItem(id: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Item>>;
public getItem(id: number, 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 getItem.');
}
let localVarHeaders = this.defaultHeaders;
// authentication (bearer) required
localVarHeaders = this.configuration.addCredentialToHeaders('bearer', 'Authorization', localVarHeaders, 'Bearer ');
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/items/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: undefined})}`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Item>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Returns a page of items.
* @endpoint get /api/inse-service/items
* @param pageOffset The page offset.
* @param pageSize The page size.
* @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 getItems(pageOffset?: number, pageSize?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<ItemPage>;
public getItems(pageOffset?: number, pageSize?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<ItemPage>>;
public getItems(pageOffset?: number, pageSize?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<ItemPage>>;
public getItems(pageOffset?: number, pageSize?: number, 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>pageOffset, 'pageOffset');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>pageSize, 'pageSize');
let localVarHeaders = this.defaultHeaders;
// authentication (bearer) required
localVarHeaders = this.configuration.addCredentialToHeaders('bearer', 'Authorization', localVarHeaders, 'Bearer ');
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/items`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<ItemPage>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Returns the nested topic hierarchy (Domains -&gt; Fields -&gt; Subfields -&gt; Topics).
* @endpoint get /api/inse-service/topics/hierarchy
@@ -210,4 +463,76 @@ export class INSEServiceService extends BaseService {
);
}
/**
* Updates the item with the id.
* @endpoint put /api/inse-service/items/{id}
* @param id The item id.
* @param itemCreate
* @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 updateItem(id: number, itemCreate: ItemCreate, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Item>;
public updateItem(id: number, itemCreate: ItemCreate, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Item>>;
public updateItem(id: number, itemCreate: ItemCreate, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Item>>;
public updateItem(id: number, itemCreate: ItemCreate, 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 updateItem.');
}
if (itemCreate === null || itemCreate === undefined) {
throw new Error('Required parameter itemCreate was null or undefined when calling updateItem.');
}
let localVarHeaders = this.defaultHeaders;
// authentication (bearer) required
localVarHeaders = this.configuration.addCredentialToHeaders('bearer', 'Authorization', localVarHeaders, 'Bearer ');
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/inse-service/items/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: undefined})}`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Item>('put', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: itemCreate,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
}
+363
View File
@@ -0,0 +1,363 @@
/**
* 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 { Item } from '../model/item';
// @ts-ignore
import { ItemCreate } from '../model/itemCreate';
// @ts-ignore
import { ItemPage } from '../model/itemPage';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service';
@Injectable({
providedIn: 'root'
})
export class ItemsService extends BaseService {
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
super(basePath, configuration);
}
/**
* Adds a new item.
* @endpoint post /api/inse-service/items
* @param itemCreate
* @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 addItem(itemCreate: ItemCreate, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Item>;
public addItem(itemCreate: ItemCreate, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Item>>;
public addItem(itemCreate: ItemCreate, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Item>>;
public addItem(itemCreate: ItemCreate, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (itemCreate === null || itemCreate === undefined) {
throw new Error('Required parameter itemCreate was null or undefined when calling addItem.');
}
let localVarHeaders = this.defaultHeaders;
// authentication (bearer) required
localVarHeaders = this.configuration.addCredentialToHeaders('bearer', 'Authorization', localVarHeaders, 'Bearer ');
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/inse-service/items`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Item>('post', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: itemCreate,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Deletes the item with the id.
* @endpoint delete /api/inse-service/items/{id}
* @param id The item 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 deleteItem(id: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
public deleteItem(id: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
public deleteItem(id: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
public deleteItem(id: number, 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 deleteItem.');
}
let localVarHeaders = this.defaultHeaders;
// authentication (bearer) required
localVarHeaders = this.configuration.addCredentialToHeaders('bearer', 'Authorization', localVarHeaders, 'Bearer ');
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/items/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: undefined})}`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<any>('delete', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Returns the item with the id.
* @endpoint get /api/inse-service/items/{id}
* @param id The item 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 getItem(id: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Item>;
public getItem(id: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Item>>;
public getItem(id: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Item>>;
public getItem(id: number, 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 getItem.');
}
let localVarHeaders = this.defaultHeaders;
// authentication (bearer) required
localVarHeaders = this.configuration.addCredentialToHeaders('bearer', 'Authorization', localVarHeaders, 'Bearer ');
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/items/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: undefined})}`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Item>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Returns a page of items.
* @endpoint get /api/inse-service/items
* @param pageOffset The page offset.
* @param pageSize The page size.
* @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 getItems(pageOffset?: number, pageSize?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<ItemPage>;
public getItems(pageOffset?: number, pageSize?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<ItemPage>>;
public getItems(pageOffset?: number, pageSize?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<ItemPage>>;
public getItems(pageOffset?: number, pageSize?: number, 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>pageOffset, 'pageOffset');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>pageSize, 'pageSize');
let localVarHeaders = this.defaultHeaders;
// authentication (bearer) required
localVarHeaders = this.configuration.addCredentialToHeaders('bearer', 'Authorization', localVarHeaders, 'Bearer ');
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/items`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<ItemPage>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Updates the item with the id.
* @endpoint put /api/inse-service/items/{id}
* @param id The item id.
* @param itemCreate
* @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 updateItem(id: number, itemCreate: ItemCreate, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Item>;
public updateItem(id: number, itemCreate: ItemCreate, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Item>>;
public updateItem(id: number, itemCreate: ItemCreate, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Item>>;
public updateItem(id: number, itemCreate: ItemCreate, 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 updateItem.');
}
if (itemCreate === null || itemCreate === undefined) {
throw new Error('Required parameter itemCreate was null or undefined when calling updateItem.');
}
let localVarHeaders = this.defaultHeaders;
// authentication (bearer) required
localVarHeaders = this.configuration.addCredentialToHeaders('bearer', 'Authorization', localVarHeaders, 'Bearer ');
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/inse-service/items/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: undefined})}`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Item>('put', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: itemCreate,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
}
-554
View File
@@ -1,554 +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.
*/
/* 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: \&#39;desc\&#39; (newest first) or \&#39;asc\&#39; (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: \&#39;desc\&#39; (newest first) or \&#39;asc\&#39; (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: \&#39;desc\&#39; (newest first) or \&#39;asc\&#39; (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: \&#39;desc\&#39; (newest first) or \&#39;asc\&#39; (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
}
);
}
}
+158
View File
@@ -0,0 +1,158 @@
/**
* Innovation Search Engine API
*/
/* 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 { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service';
export interface PatentEntry {
patent_id: string;
source: string;
title: string | null;
abstract: string | null;
publication_date: string | null;
publication_year: string | null;
inventors: string[];
assignees: string[];
ipc: string[];
country: string | null;
confidence_score: number;
}
export interface PatentsByAuthorResponse {
author_id: string;
author_name: string | null;
patent_count: number;
patents: PatentEntry[];
}
type GetPatentsByAuthorOptions = {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
};
@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 by author.
* @endpoint get /api/inse-service/authors/{author_id}/patents
* @param authorId
* @param observe
* @param reportProgress
*/
public getPatentsByAuthor(
authorId: string,
observe?: 'body',
reportProgress?: boolean,
options?: GetPatentsByAuthorOptions,
): Observable<PatentsByAuthorResponse>;
public getPatentsByAuthor(
authorId: string,
observe?: 'response',
reportProgress?: boolean,
options?: GetPatentsByAuthorOptions,
): Observable<HttpResponse<PatentsByAuthorResponse>>;
public getPatentsByAuthor(
authorId: string,
observe?: 'events',
reportProgress?: boolean,
options?: GetPatentsByAuthorOptions,
): Observable<HttpEvent<PatentsByAuthorResponse>>;
public getPatentsByAuthor(
authorId: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: GetPatentsByAuthorOptions,
): 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,
},
);
}
}
+158 -95
View File
@@ -1,95 +1,158 @@
/**
* 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
}
);
}
}
/**
* Innovation Search Engine API
*/
/* 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 { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service';
export interface PatentEntry {
patent_id: string;
source: string;
title: string | null;
abstract: string | null;
publication_date: string | null;
publication_year: string | null;
inventors: string[];
assignees: string[];
ipc: string[];
country: string | null;
confidence_score: number;
}
export interface PatentsByAuthorResponse {
author_id: string;
author_name: string | null;
patent_count: number;
patents: PatentEntry[];
}
type GetPatentsByAuthorOptions = {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
};
@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 by author.
* @endpoint get /api/inse-service/authors/{author_id}/patents
* @param authorId
* @param observe
* @param reportProgress
*/
public getPatentsByAuthor(
authorId: string,
observe?: 'body',
reportProgress?: boolean,
options?: GetPatentsByAuthorOptions,
): Observable<PatentsByAuthorResponse>;
public getPatentsByAuthor(
authorId: string,
observe?: 'response',
reportProgress?: boolean,
options?: GetPatentsByAuthorOptions,
): Observable<HttpResponse<PatentsByAuthorResponse>>;
public getPatentsByAuthor(
authorId: string,
observe?: 'events',
reportProgress?: boolean,
options?: GetPatentsByAuthorOptions,
): Observable<HttpEvent<PatentsByAuthorResponse>>;
public getPatentsByAuthor(
authorId: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: GetPatentsByAuthorOptions,
): 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,
},
);
}
}
+4 -62
View File
@@ -27,8 +27,6 @@ import { DfgProjectDetails } from '../model/dfgProjectDetails';
// @ts-ignore
import { DfgProjectPage } from '../model/dfgProjectPage';
// @ts-ignore
import { EuOrganizationProjectSummaryPage } from '../model/euOrganizationProjectSummaryPage';
// @ts-ignore
import { FundingProjectPage } from '../model/fundingProjectPage';
// @ts-ignore
import { HTTPValidationError } from '../model/hTTPValidationError';
@@ -135,62 +133,6 @@ 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.
@@ -499,9 +441,9 @@ export class ProjectsService 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 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?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<CordisEuProjectPage>;
public searchCordisEuProjects(projectsFilteringProperties: ProjectsFilteringProperties, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<CordisEuProjectPage>>;
public searchCordisEuProjects(projectsFilteringProperties: ProjectsFilteringProperties, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<CordisEuProjectPage>>;
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.');
@@ -543,7 +485,7 @@ export class ProjectsService extends BaseService {
let localVarPath = `/api/projects/institution/eu/search`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<EuOrganizationProjectSummaryPage>('post', `${basePath}${localVarPath}`,
return this.httpClient.request<CordisEuProjectPage>('post', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: projectsFilteringProperties,
+4 -7
View File
@@ -372,14 +372,13 @@ export class TopicsService extends BaseService {
* @endpoint get /api/topics/vector-search
* @param query Word or sentence to search by similarity.
* @param limit Maximum number of topics to return.
* @param searchType Search approach: \&#39;hybrid\&#39; or \&#39;semantic\&#39;.
* @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 vectorSearchTopics(query: string, limit?: number, searchType?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<TopicsListResponse>;
public vectorSearchTopics(query: string, limit?: number, searchType?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<TopicsListResponse>>;
public vectorSearchTopics(query: string, limit?: number, searchType?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<TopicsListResponse>>;
public vectorSearchTopics(query: string, limit?: number, searchType?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
public vectorSearchTopics(query: string, limit?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<TopicsListResponse>;
public vectorSearchTopics(query: string, limit?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<TopicsListResponse>>;
public vectorSearchTopics(query: string, limit?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<TopicsListResponse>>;
public vectorSearchTopics(query: string, limit?: 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 vectorSearchTopics.');
}
@@ -389,8 +388,6 @@ export class TopicsService extends BaseService {
<any>query, 'query');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>limit, 'limit');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>searchType, 'searchType');
let localVarHeaders = this.defaultHeaders;
+15
View File
@@ -62,6 +62,9 @@ export class WorksService extends BaseService {
let localVarHeaders = this.defaultHeaders;
// authentication (bearer) required
localVarHeaders = this.configuration.addCredentialToHeaders('bearer', 'Authorization', localVarHeaders, 'Bearer ');
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
@@ -160,6 +163,9 @@ export class WorksService extends BaseService {
let localVarHeaders = this.defaultHeaders;
// authentication (bearer) required
localVarHeaders = this.configuration.addCredentialToHeaders('bearer', 'Authorization', localVarHeaders, 'Bearer ');
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
@@ -216,6 +222,9 @@ export class WorksService extends BaseService {
let localVarHeaders = this.defaultHeaders;
// authentication (bearer) required
localVarHeaders = this.configuration.addCredentialToHeaders('bearer', 'Authorization', localVarHeaders, 'Bearer ');
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
@@ -282,6 +291,9 @@ export class WorksService extends BaseService {
let localVarHeaders = this.defaultHeaders;
// authentication (bearer) required
localVarHeaders = this.configuration.addCredentialToHeaders('bearer', 'Authorization', localVarHeaders, 'Bearer ');
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
@@ -338,6 +350,9 @@ export class WorksService extends BaseService {
let localVarHeaders = this.defaultHeaders;
// authentication (bearer) required
localVarHeaders = this.configuration.addCredentialToHeaders('bearer', 'Authorization', localVarHeaders, 'Bearer ');
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
+3 -3
View File
@@ -91,9 +91,9 @@ constructor({ accessToken, apiKeys, basePath, credentials, encodeParam, encoder,
this.encodeParam = encodeParam ?? (param => this.defaultEncodeParam(param));
this.credentials = credentials ?? {};
// init default HTTPBearer credential
if (!this.credentials['HTTPBearer']) {
this.credentials['HTTPBearer'] = () => {
// init default bearer credential
if (!this.credentials['bearer']) {
this.credentials['bearer'] = () => {
return typeof this.accessToken === 'function'
? this.accessToken()
: this.accessToken;

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