Compare commits
134
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eb4937bedf | ||
|
|
3fc0b5ca19 | ||
|
|
8a77a3425f | ||
|
|
e24a6ca49b | ||
|
|
7d869d8a82 | ||
|
|
152679e3e9 | ||
|
|
b88f459bde | ||
|
|
28a77796a2 | ||
|
|
fdc59d8b0b | ||
|
|
1874f41fb0 | ||
|
|
7d7bd87201 | ||
|
|
3437a8288d | ||
|
|
4536adafc4 | ||
|
|
0780271109 | ||
|
|
32fdd1281c | ||
|
|
7f2d0aa6b0 | ||
|
|
997c573295 | ||
|
|
96b59888f3 | ||
|
|
6aaeaad580 | ||
|
|
7657a61674 | ||
|
|
2b6f6bfc51 | ||
|
|
0d16159a23 | ||
|
|
89ab84bcb6 | ||
|
|
0c52b6f324 | ||
|
|
15392b5757 | ||
|
|
12f866a9d4 | ||
|
|
bca5bf74bf | ||
|
|
5fa764e7e8 | ||
|
|
f417374827 | ||
|
|
ecc6aabfa3 | ||
|
|
4e1ea6d04c | ||
|
|
f288fb7306 | ||
|
|
2836cf02a7 | ||
|
|
f7c7a9751a | ||
|
|
c2b8f54fb7 | ||
|
|
229c4126de | ||
|
|
b657508f1a | ||
|
|
16d302842c | ||
|
|
b0b2ca2085 | ||
|
|
9bd86b391b | ||
|
|
560af6a1eb | ||
|
|
8e284916e6 | ||
|
|
6979aaef8d | ||
|
|
abe96098b5 | ||
|
|
0f212d189e | ||
|
|
486ea0d2ba | ||
|
|
103b783635 | ||
|
|
84f1cdfead | ||
|
|
517b974ef2 | ||
|
|
d4eaf343e7 | ||
|
|
b114e33767 | ||
|
|
0ed80e2b36 | ||
|
|
d516660e36 | ||
|
|
fc123d81aa | ||
|
|
58156025e9 | ||
|
|
aa28aa0e02 | ||
|
|
fe89113ad6 | ||
|
|
903ee594a3 | ||
|
|
f0a8363536 | ||
|
|
bc99b6deb8 | ||
|
|
e9d931fe74 | ||
|
|
16d2f3ecf5 | ||
|
|
5b8a20b0ac | ||
|
|
5e49e75160 | ||
|
|
9746346919 | ||
|
|
9479192f01 | ||
|
|
72dc3bd852 | ||
|
|
91eb08a083 | ||
|
|
7ff0eda286 | ||
|
|
59035f97ed | ||
|
|
c58a8da461 | ||
|
|
6eb2ecb466 | ||
|
|
a247ff7cac | ||
|
|
68f239e808 | ||
|
|
bd958d1621 | ||
|
|
3c08bc1866 | ||
|
|
88f9474443 | ||
|
|
78990d9b73 | ||
|
|
701931d641 | ||
|
|
fc03a69ad3 | ||
|
|
4a909ab166 | ||
|
|
90d3a8aa21 | ||
|
|
e9b4cbc0c7 | ||
|
|
0ae41ef95e | ||
|
|
a5f7204b59 | ||
|
|
81c7bee3d8 | ||
|
|
e758fb5f96 | ||
|
|
585ac19c12 | ||
|
|
8dc9f0bccd | ||
|
|
b62dd33a33 | ||
|
|
b41b19a40f | ||
|
|
b7c8a6cfdc | ||
|
|
a00e8a88e4 | ||
|
|
17607d856b | ||
|
|
250b5c2de9 | ||
|
|
9cfd4e9b87 | ||
|
|
282d761c02 | ||
|
|
5a83c7eb52 | ||
|
|
05fabbb231 | ||
|
|
ad900a69d7 | ||
|
|
cad97057cf | ||
|
|
efd9d62477 | ||
|
|
60fa0e0a45 | ||
|
|
4ff574e9f1 | ||
|
|
c9601b06a2 | ||
|
|
a82e76bdef | ||
|
|
cf43330206 | ||
|
|
351f43aca6 | ||
|
|
0f838e3429 | ||
|
|
9a6166b4ee | ||
|
|
4701f294d0 | ||
|
|
755488fef7 | ||
|
|
a7a579ef57 | ||
|
|
038fdb8899 | ||
|
|
8d412fef4a | ||
|
|
52efe1a45a | ||
|
|
801f7419c5 | ||
|
|
c75203c755 | ||
|
|
770f2b31e1 | ||
|
|
3325590735 | ||
|
|
8e1ac13ca7 | ||
|
|
d79d0b842e | ||
|
|
6e64b3a633 | ||
|
|
8ce107f9e0 | ||
|
|
41f34a2e1b | ||
|
|
c482a917b2 | ||
|
|
472ff1208e | ||
|
|
f903e417ad | ||
|
|
f01f17dbaf | ||
|
|
ac69aa3915 | ||
|
|
68c354ad82 | ||
|
|
135705adc9 | ||
|
|
ca6ab84465 | ||
|
|
44bd8c6ce5 |
Executable
+11
@@ -0,0 +1,11 @@
|
||||
#!/bin/sh
|
||||
FILES=$(git diff --cached --name-only --diff-filter=ACMR | sed 's| |\\ |g')
|
||||
[ -z "$FILES" ] && exit 0
|
||||
|
||||
# Prettify all selected files
|
||||
echo "$FILES" | xargs ./node_modules/.bin/prettier --ignore-unknown --write
|
||||
|
||||
# Add back the modified/prettified files to staging
|
||||
echo "$FILES" | xargs git add
|
||||
|
||||
exit 0
|
||||
+20
-17
@@ -1,17 +1,20 @@
|
||||
# Ignore Gradle project-specific cache directory
|
||||
.gradle
|
||||
# Ignore Gradle build output directory
|
||||
build
|
||||
# Ignore vscode metadata
|
||||
.vscode
|
||||
# Ingore pyhton cache
|
||||
__pycache__
|
||||
# Ignore macos
|
||||
.DS_Store
|
||||
# Ignore generated python code
|
||||
src/python/account/
|
||||
|
||||
*.pyc
|
||||
|
||||
node_modules/
|
||||
angular-app/.angular
|
||||
# Ignore Gradle project-specific cache directory
|
||||
.gradle
|
||||
# Ignore Gradle build output directory
|
||||
build
|
||||
# Ignore vscode metadata
|
||||
.vscode
|
||||
# Ingore pyhton cache
|
||||
__pycache__
|
||||
# Ignore macos
|
||||
.DS_Store
|
||||
# Ignore generated python code
|
||||
src/python/account/
|
||||
|
||||
*.pyc
|
||||
|
||||
node_modules/
|
||||
angular-app/.angular
|
||||
|
||||
# Ignore sentence-transformer local model cache
|
||||
service/sentence_transformer/models/␍
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"tabWidth": 2,
|
||||
"useTabs": false,
|
||||
"singleQuote": true,
|
||||
"semi": true,
|
||||
"bracketSpacing": true,
|
||||
"arrowParens": "always",
|
||||
"trailingComma": "all",
|
||||
"bracketSameLine": true,
|
||||
"printWidth": 80
|
||||
}
|
||||
@@ -12,11 +12,11 @@ A minimal full-stack web application using Docker, Gradle, FastAPI and Angular.
|
||||
|
||||
## Build System: Gradle (Root)
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| build.gradle | Root config defining Docker image name (`inse`), prefix, and version (`1.0.0`) |
|
||||
| settings.gradle | Declares the three submodules: `:service`, `:webapp`, `:app` |
|
||||
| libs.versions.toml | Centralized dependency version catalog |
|
||||
| File | Purpose |
|
||||
| ------------------ | ------------------------------------------------------------------------------ |
|
||||
| build.gradle | Root config defining Docker image name (`inse`), prefix, and version (`1.0.0`) |
|
||||
| settings.gradle | Declares the three submodules: `:service`, `:webapp`, `:app` |
|
||||
| libs.versions.toml | Centralized dependency version catalog |
|
||||
|
||||
Gradle orchestrates the entire build, including Docker image creation and the Angular frontend.
|
||||
|
||||
@@ -26,36 +26,38 @@ Gradle orchestrates the entire build, including Docker image creation and the An
|
||||
|
||||
A REST API running in Docker, exposing **three mounted FastAPI sub-applications**:
|
||||
|
||||
| Mount path | Description |
|
||||
|---|---|
|
||||
| `/inse-service` | Main resource API (items CRUD) |
|
||||
| `/inse-webapp` | Serves the static Angular SPA |
|
||||
| Mount path | Description |
|
||||
| --------------- | ------------------------------------- |
|
||||
| `/inse-service` | Main resource API (items CRUD) |
|
||||
| `/inse-webapp` | Serves the static Angular SPA |
|
||||
| `/inse-account` | Authentication service (login/tokens) |
|
||||
|
||||
### Key source files in inse:
|
||||
|
||||
| File | Role |
|
||||
|---|---|
|
||||
| main.py | FastAPI app bootstrap, mounts the three sub-apps |
|
||||
| service.py | CRUD REST endpoints for `Item` resources (GET, POST, PUT, DELETE), protected by JWT roles |
|
||||
| model.py | Pydantic response models: `Item`, `ItemCreate`, `ItemPage` (generic pagination) |
|
||||
| schema.py | SQLAlchemy ORM table definitions — `Item` table in SQLite |
|
||||
| logic.py | Business logic layer (called by the service) |
|
||||
| database.py | SQLAlchemy engine/session setup, reads from `config` |
|
||||
| security.py | JWT decoding, `Principal` / `Account` models, role-based access via `roles_allowed()` |
|
||||
| config.py | App settings via env vars prefixed `inse_` (DB URL, auth secret, feature flags) |
|
||||
| webapp.py | Mounts the static Angular build as a `StaticFiles` app |
|
||||
| util.py | Utility helpers (e.g. `raise_not_found_if_none`) |
|
||||
| File | Role |
|
||||
| ----------- | ----------------------------------------------------------------------------------------- |
|
||||
| main.py | FastAPI app bootstrap, mounts the three sub-apps |
|
||||
| service.py | CRUD REST endpoints for `Item` resources (GET, POST, PUT, DELETE), protected by JWT roles |
|
||||
| model.py | Pydantic response models: `Item`, `ItemCreate`, `ItemPage` (generic pagination) |
|
||||
| schema.py | SQLAlchemy ORM table definitions — `Item` table in SQLite |
|
||||
| logic.py | Business logic layer (called by the service) |
|
||||
| database.py | SQLAlchemy engine/session setup, reads from `config` |
|
||||
| security.py | JWT decoding, `Principal` / `Account` models, role-based access via `roles_allowed()` |
|
||||
| config.py | App settings via env vars prefixed `inse_` (DB URL, auth secret, feature flags) |
|
||||
| webapp.py | Mounts the static Angular build as a `StaticFiles` app |
|
||||
| util.py | Utility helpers (e.g. `raise_not_found_if_none`) |
|
||||
|
||||
### `account/` sub-package (account):
|
||||
|
||||
Handles authentication independently:
|
||||
|
||||
- account/service.py — `POST /auth/id` (username+password → identity token) and `POST /auth/access` (ID token → access token)
|
||||
- account/logic.py — validates users from users.json
|
||||
- account/model.py — Pydantic models for `IdentityGrant`, `AccessGrant`
|
||||
- account/security.py — JWT signing
|
||||
|
||||
### Data & Config:
|
||||
|
||||
- users.json — Hardcoded user accounts (superadmin/user)
|
||||
- log-config.yaml — Logging configuration
|
||||
- entrypoint.sh — Docker entrypoint script
|
||||
@@ -69,20 +71,20 @@ An **Angular 18 SPA** using Angular Material, built with Node.js + Gradle.
|
||||
|
||||
### App structure in app:
|
||||
|
||||
| Directory/File | Role |
|
||||
|---|---|
|
||||
| app.routes.ts | Routes: `/login` → `AppLoginComponent`, `/items` → `ListItemComponent` (guarded), `**` → redirect to login |
|
||||
| app.config.ts | Angular app bootstrap config (providers, interceptors) |
|
||||
| `app-login/` | Login form component |
|
||||
| `app-layout/` | Shell/layout wrapper component |
|
||||
| `app-menu/` | Navigation menu component |
|
||||
| `list-item/` | The main feature page — lists `Item` resources with pagination |
|
||||
| `confirmation-dialog/` | Reusable dialog for destructive actions |
|
||||
| `guards/` | Route guards: `user.guard.ts` (authenticated), `admin.guard.ts` (admin role) |
|
||||
| `interceptors/` | authentication.interceptor.ts — attaches JWT Bearer token to all requests except auth endpoints |
|
||||
| `services/` | api.service.ts (CRUD calls to `/inse-service`), `credential.service.ts` (token management), `pagination.service.ts` |
|
||||
| `pipes/` | `truncate.pipe.ts` — truncates long strings in templates |
|
||||
| `utils/` | Utility helpers |
|
||||
| Directory/File | Role |
|
||||
| ---------------------- | ------------------------------------------------------------------------------------------------------------------- |
|
||||
| app.routes.ts | Routes: `/login` → `AppLoginComponent`, `/items` → `ListItemComponent` (guarded), `**` → redirect to login |
|
||||
| app.config.ts | Angular app bootstrap config (providers, interceptors) |
|
||||
| `app-login/` | Login form component |
|
||||
| `app-layout/` | Shell/layout wrapper component |
|
||||
| `app-menu/` | Navigation menu component |
|
||||
| `list-item/` | The main feature page — lists `Item` resources with pagination |
|
||||
| `confirmation-dialog/` | Reusable dialog for destructive actions |
|
||||
| `guards/` | Route guards: `user.guard.ts` (authenticated), `admin.guard.ts` (admin role) |
|
||||
| `interceptors/` | authentication.interceptor.ts — attaches JWT Bearer token to all requests except auth endpoints |
|
||||
| `services/` | api.service.ts (CRUD calls to `/inse-service`), `credential.service.ts` (token management), `pagination.service.ts` |
|
||||
| `pipes/` | `truncate.pipe.ts` — truncates long strings in templates |
|
||||
| `utils/` | Utility helpers |
|
||||
|
||||
---
|
||||
|
||||
@@ -111,7 +113,6 @@ Browser
|
||||
|
||||
**Auth flow**: The Angular interceptor calls `/inse-account/auth/id` with credentials → receives an ID token → exchanges it for an access JWT via `/inse-account/auth/access` → attaches the access token as `Authorization: Bearer` on all subsequent requests. The backend's security.py decodes and validates this JWT to enforce role-based access control (`SUPER_ADMIN`, `UNI_ADMIN`).
|
||||
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Docker
|
||||
@@ -155,7 +156,22 @@ The app will be available at `http://localhost:8080/inse-webapp/`.
|
||||
|
||||
Defined in `service/src/data/users.json`:
|
||||
|
||||
| Username | Password | Role |
|
||||
|-------------|-------------|-------------|
|
||||
| superadmin | superadmin | SUPER_ADMIN |
|
||||
| user | user | UNI_ADMIN |
|
||||
| Username | Password | Role |
|
||||
| ---------- | ---------- | ----------- |
|
||||
| superadmin | superadmin | SUPER_ADMIN |
|
||||
| user | user | UNI_ADMIN |
|
||||
|
||||
## Prettier pre-commit hook
|
||||
|
||||
- Install Prettier
|
||||
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
|
||||
- To enable automatic code formatting with Prettier on commit, copy the pre-commit hook script to the Git hooks directory and make it executable:
|
||||
|
||||
```shell
|
||||
cp .githooks/pre-commit .git/hooks/pre-commit
|
||||
chmod +x .git/hooks/pre-commit
|
||||
```
|
||||
|
||||
Generated
+28
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"name": "smartguide",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"devDependencies": {
|
||||
"prettier": "^3.8.3"
|
||||
}
|
||||
},
|
||||
"node_modules/prettier": {
|
||||
"version": "3.8.3",
|
||||
"resolved": "https://registry.npmjs.org/prettier/-/prettier-3.8.3.tgz",
|
||||
"integrity": "sha512-7igPTM53cGHMW8xWuVTydi2KO233VFiTNyF5hLJqpilHfmn8C8gPf+PS7dUT64YcXFbiMGZxS9pCSxL/Dxm/Jw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"prettier": "bin/prettier.cjs"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/prettier/prettier?sponsor=1"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"devDependencies": {
|
||||
"prettier": "^3.8.3"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
UNIVERSITAET DUISBURG-ESSEN
|
||||
UNIVERSITAET DUISBURG-ESSEN - STANDORT DUISBURG
|
||||
UNIVERSITÄT DUISBURG-ESSEN
|
||||
UNIVERSITAET DUISBURG-ESSEN - STANDORT ESSEN
|
||||
UNIVERSITAET DUISBURG-ESSEN (UNIVERSITY OF DUISBURG-ESSEN)
|
||||
UNIVERSITAT DUISBURG-ESSEN
|
||||
UNIVERSITY OF DUISBURG-ESSEN
|
||||
UNIVERSITÄT DUISBURG ESSEN
|
||||
+3
-5
@@ -1,9 +1,7 @@
|
||||
FROM python:3.12-slim-bookworm
|
||||
ARG BASE_IMAGE=inse-base-static:latest
|
||||
FROM $BASE_IMAGE
|
||||
|
||||
RUN mkdir /test && \
|
||||
mkdir /data && \
|
||||
pip install --root-user-action=ignore --no-cache-dir --upgrade pip && \
|
||||
pip install --root-user-action=ignore --no-cache-dir --disable-pip-version-check \
|
||||
RUN pip install --root-user-action=ignore --no-cache-dir --disable-pip-version-check \
|
||||
"fastapi~=0.115.0" \
|
||||
"SQLAlchemy~=2.0.0" \
|
||||
"pyjwt~=2.8.0" \
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
FROM python:3.12-slim-bookworm
|
||||
|
||||
RUN mkdir /test && \
|
||||
mkdir /data && \
|
||||
pip install --root-user-action=ignore --no-cache-dir --upgrade pip && \
|
||||
pip install --root-user-action=ignore --no-cache-dir torch --index-url https://download.pytorch.org/whl/cpu && \
|
||||
pip install --root-user-action=ignore --no-cache-dir "sentence-transformers~=5.5.1"
|
||||
|
||||
ENV SENTENCE_TRANSFORMERS_HOME=/models
|
||||
RUN python -c "from sentence_transformers import SentenceTransformer; SentenceTransformer('paraphrase-multilingual-mpnet-base-v2')"
|
||||
+2
-2
@@ -10,8 +10,8 @@ To build the container: `./gradlew :service:build`
|
||||
|
||||
To launch the service with hot-reload: `./gradlew :service:serve`
|
||||
|
||||
This mounts the source directory into the container and enables uvicorn hot-reloading. Press *ENTER* to stop.
|
||||
This mounts the source directory into the container and enables uvicorn hot-reloading. Press _ENTER_ to stop.
|
||||
|
||||
## Testing
|
||||
|
||||
Run tests: `./gradlew :service:test`
|
||||
Run tests: `./gradlew :service:test`
|
||||
|
||||
@@ -2,7 +2,32 @@ plugins {
|
||||
id 'base'
|
||||
}
|
||||
|
||||
task createBaseImage(type: Exec) {
|
||||
commandLine 'docker', 'build', '--platform', "${targetPlatform}", '-f', 'Dockerfile.base', '-t', "${imagePrefix}-base-static:latest", '.'
|
||||
}
|
||||
|
||||
task buildBaseImageIfNeeded {
|
||||
doLast {
|
||||
def baseImage = "${imagePrefix}-base-static:latest"
|
||||
def checkCmd = ["docker", "image", "inspect", baseImage]
|
||||
def process = checkCmd.execute()
|
||||
process.waitFor()
|
||||
if (process.exitValue() != 0) {
|
||||
println "Base image ${baseImage} not found. Building it..."
|
||||
def buildCmd = ["docker", "build", "--platform", "${targetPlatform}", "-f", "Dockerfile.base", "-t", baseImage, "."]
|
||||
def buildProcess = buildCmd.execute([], projectDir)
|
||||
buildProcess.consumeProcessOutput(System.out, System.err)
|
||||
if (buildProcess.waitFor() != 0) {
|
||||
throw new GradleException("Failed to build base image.")
|
||||
}
|
||||
} else {
|
||||
println "Base image ${baseImage} found. Skipping build."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
task createImage(type: Exec) {
|
||||
dependsOn buildBaseImageIfNeeded
|
||||
commandLine 'docker', 'build', '--platform', "${targetPlatform}", '-t', "${imagePrefix}-service:${imageVersion}", '.'
|
||||
}
|
||||
|
||||
|
||||
@@ -19,4 +19,14 @@ dependencies = [
|
||||
"pyyaml~=6.0.1",
|
||||
"sqlalchemy~=2.0.0",
|
||||
"uvicorn~=0.29.0",
|
||||
"sentence-transformers~=5.5.1",
|
||||
"torch",
|
||||
]
|
||||
|
||||
[[tool.uv.index]]
|
||||
name = "pytorch-cpu"
|
||||
url = "https://download.pytorch.org/whl/cpu"
|
||||
explicit = true
|
||||
|
||||
[tool.uv.sources]
|
||||
torch = { index = "pytorch-cpu" }
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Download the sentence-transformers model to the default cache directory
|
||||
so it is available for local runs or testing.
|
||||
|
||||
Usage (run once from project root):
|
||||
python service/sentence_transformer/download_model.py
|
||||
"""
|
||||
from sentence_transformers import SentenceTransformer
|
||||
|
||||
MODEL_NAME = "paraphrase-multilingual-mpnet-base-v2"
|
||||
print(f"Downloading '{MODEL_NAME}' to default cache directory...")
|
||||
model = SentenceTransformer(MODEL_NAME)
|
||||
print("Done.")
|
||||
@@ -0,0 +1,259 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
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
|
||||
current_dir = Path(__file__).parent.resolve()
|
||||
project_root = current_dir.parent.parent.resolve()
|
||||
env_path = project_root / "service" / "src" / "main" / "inse" / ".env"
|
||||
load_dotenv(dotenv_path=env_path)
|
||||
|
||||
sys.path.append(str(project_root / "service" / "src" / "main"))
|
||||
from inse.config import settings
|
||||
|
||||
ELASTIC_URL = settings.elasticsearch_url
|
||||
API_KEY = settings.elasticsearch_api_key
|
||||
MODEL_NAME = "paraphrase-multilingual-mpnet-base-v2"
|
||||
|
||||
# Import sentence-transformers
|
||||
from sentence_transformers import SentenceTransformer
|
||||
|
||||
headers = {
|
||||
"Authorization": f"ApiKey {API_KEY}",
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
def float_array_to_base64(vector):
|
||||
"""
|
||||
Convert a float vector into a Base64 string representing 32-bit big-endian float bytes.
|
||||
Elasticsearch expects big-endian floats for binary/Base64 dense_vector encoding.
|
||||
"""
|
||||
arr = np.asarray(vector, dtype=np.float32)
|
||||
big_endian_bytes = arr.astype('>f4').tobytes()
|
||||
return base64.b64encode(big_endian_bytes).decode('utf-8')
|
||||
|
||||
def split_into_sentences(text):
|
||||
if not text:
|
||||
return []
|
||||
# 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 check_and_update_mapping():
|
||||
print("Checking 'topicvectors' index...")
|
||||
|
||||
with httpx.Client(timeout=30.0) as client:
|
||||
exists_resp = client.head(f"{ELASTIC_URL}topicvectors", headers=headers)
|
||||
if exists_resp.status_code == 404:
|
||||
print("Index 'topicvectors' does not exist. Creating index with mapping...")
|
||||
create_payload = {
|
||||
"mappings": {
|
||||
"properties": {
|
||||
"id": {"type": "keyword"},
|
||||
"display_name": {
|
||||
"type": "text",
|
||||
"fields": {
|
||||
"keyword": {"type": "keyword", "ignore_above": 256}
|
||||
}
|
||||
},
|
||||
"display_name_vector": {
|
||||
"type": "dense_vector",
|
||||
"dims": 768,
|
||||
"index": True,
|
||||
"similarity": "cosine",
|
||||
"index_options": {
|
||||
"type": "int8_hnsw",
|
||||
"m": 16,
|
||||
"ef_construction": 100
|
||||
}
|
||||
},
|
||||
"description": {"type": "text"},
|
||||
"description_vectors": {
|
||||
"type": "nested",
|
||||
"properties": {
|
||||
"vector": {
|
||||
"type": "dense_vector",
|
||||
"dims": 768,
|
||||
"index": True,
|
||||
"similarity": "cosine",
|
||||
"index_options": {
|
||||
"type": "int8_hnsw",
|
||||
"m": 16,
|
||||
"ef_construction": 100
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"keywords": {
|
||||
"type": "text",
|
||||
"fields": {
|
||||
"keyword": {"type": "keyword"}
|
||||
}
|
||||
},
|
||||
"cited_by_count": {"type": "long"},
|
||||
"works_count": {"type": "long"},
|
||||
"updated_date": {"type": "date"},
|
||||
"created_date": {"type": "date"}
|
||||
}
|
||||
}
|
||||
}
|
||||
resp = client.put(
|
||||
f"{ELASTIC_URL}topicvectors",
|
||||
json=create_payload,
|
||||
headers=headers
|
||||
)
|
||||
if resp.status_code == 200:
|
||||
print("Successfully created 'topicvectors' index.")
|
||||
else:
|
||||
print(f"Failed to create index: {resp.status_code} - {resp.text}")
|
||||
resp.raise_for_status()
|
||||
else:
|
||||
print("Index 'topicvectors' already exists.")
|
||||
|
||||
def fetch_all_topics():
|
||||
print("Fetching topics from 'openalex-topics'...")
|
||||
topics = []
|
||||
size = 1000
|
||||
offset = 0
|
||||
|
||||
with httpx.Client(timeout=60.0) as client:
|
||||
while True:
|
||||
payload = {
|
||||
"query": {"match_all": {}},
|
||||
"from": offset,
|
||||
"size": size
|
||||
}
|
||||
resp = client.post(
|
||||
f"{ELASTIC_URL}openalex-topics/_search",
|
||||
json=payload,
|
||||
headers=headers
|
||||
)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
hits = data.get("hits", {}).get("hits", [])
|
||||
if not hits:
|
||||
break
|
||||
topics.extend(hits)
|
||||
offset += len(hits)
|
||||
print(f"Fetched {len(topics)} topics so far...")
|
||||
if len(hits) < size:
|
||||
break
|
||||
|
||||
print(f"Total topics fetched: {len(topics)}")
|
||||
return topics
|
||||
|
||||
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_list = nested_description_vectors[i:i+batch_size]
|
||||
|
||||
bulk_lines = []
|
||||
for t, name_vec, desc_vecs in zip(batch_topics, batch_name_vecs, batch_desc_vecs_list):
|
||||
source = t["_source"]
|
||||
|
||||
# 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 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",
|
||||
content=payload,
|
||||
headers={"Authorization": f"ApiKey {API_KEY}", "Content-Type": "application/x-ndjson"}
|
||||
)
|
||||
resp.raise_for_status()
|
||||
resp_data = resp.json()
|
||||
if resp_data.get("errors"):
|
||||
print("Bulk indexing encountered errors! First few failed items:")
|
||||
failed_items = [item for item in resp_data.get("items", []) if item.get("index", {}).get("status", 200) >= 400]
|
||||
for item in failed_items[:5]:
|
||||
print(json.dumps(item, indent=2))
|
||||
raise ValueError("Bulk indexing failed with document errors.")
|
||||
print(f"Indexed batch {i} to {i + len(batch_topics)}")
|
||||
|
||||
def main():
|
||||
check_and_update_mapping()
|
||||
|
||||
topics = fetch_all_topics()
|
||||
if not topics:
|
||||
print("No topics found. Exiting.")
|
||||
return
|
||||
|
||||
print(f"Initializing SentenceTransformer model '{MODEL_NAME}'...")
|
||||
model = SentenceTransformer(MODEL_NAME)
|
||||
|
||||
# 1. Gather all texts to embed
|
||||
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 ""
|
||||
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 = []
|
||||
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
|
||||
|
||||
# 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
|
||||
nested_description_vectors.append(topic_desc_vecs)
|
||||
|
||||
# Bulk index
|
||||
bulk_index_topics(topics, display_name_vectors, nested_description_vectors)
|
||||
print("Done!")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,150 @@
|
||||
{
|
||||
"query": "Robotics",
|
||||
"max_score": 22.734766,
|
||||
"results": [
|
||||
{
|
||||
"topic_name": "Soft Robotics and Applications",
|
||||
"score": 22.734766
|
||||
},
|
||||
{
|
||||
"topic_name": "Robotics and Automated Systems",
|
||||
"score": 21.997686
|
||||
},
|
||||
{
|
||||
"topic_name": "Educational Robotics and Engineering",
|
||||
"score": 21.919401
|
||||
},
|
||||
{
|
||||
"topic_name": "Prosthetics and Rehabilitation Robotics",
|
||||
"score": 21.846806
|
||||
},
|
||||
{
|
||||
"topic_name": "Micro and Nano Robotics",
|
||||
"score": 21.820261
|
||||
},
|
||||
{
|
||||
"topic_name": "Reinforcement Learning in Robotics",
|
||||
"score": 21.757397
|
||||
},
|
||||
{
|
||||
"topic_name": "Robotics and Sensor-Based Localization",
|
||||
"score": 19.993645
|
||||
},
|
||||
{
|
||||
"topic_name": "Social Robot Interaction and HRI",
|
||||
"score": 13.187252
|
||||
},
|
||||
{
|
||||
"topic_name": "Robotic Locomotion and Control",
|
||||
"score": 12.283064
|
||||
},
|
||||
{
|
||||
"topic_name": "Power Line Inspection Robots",
|
||||
"score": 11.873396
|
||||
},
|
||||
{
|
||||
"topic_name": "Mechatronics Education and Applications",
|
||||
"score": 11.171629
|
||||
},
|
||||
{
|
||||
"topic_name": "Educational Technology and Optimization",
|
||||
"score": 10.924184
|
||||
},
|
||||
{
|
||||
"topic_name": "Mechanical and Thermal Properties Analysis",
|
||||
"score": 10.924184
|
||||
},
|
||||
{
|
||||
"topic_name": "Psychiatry, Mental Health, Neuroscience",
|
||||
"score": 10.687462
|
||||
},
|
||||
{
|
||||
"topic_name": "Advanced Materials and Mechanics",
|
||||
"score": 10.460782
|
||||
},
|
||||
{
|
||||
"topic_name": "Wetland Management and Conservation",
|
||||
"score": 10.460782
|
||||
},
|
||||
{
|
||||
"topic_name": "Artificial Intelligence Applications",
|
||||
"score": 10.243518
|
||||
},
|
||||
{
|
||||
"topic_name": "Digitalization, Law, and Regulation",
|
||||
"score": 10.243518
|
||||
},
|
||||
{
|
||||
"topic_name": "Engineering and Technology Innovations",
|
||||
"score": 10.243518
|
||||
},
|
||||
{
|
||||
"topic_name": "Advanced Algorithms and Applications",
|
||||
"score": 10.035095
|
||||
},
|
||||
{
|
||||
"topic_name": "Teaching and Learning Programming",
|
||||
"score": 10.035095
|
||||
},
|
||||
{
|
||||
"topic_name": "Distributed Control Multi-Agent Systems",
|
||||
"score": 10.035095
|
||||
},
|
||||
{
|
||||
"topic_name": "Advanced Scientific and Engineering Studies",
|
||||
"score": 9.834986
|
||||
},
|
||||
{
|
||||
"topic_name": "Space Satellite Systems and Control",
|
||||
"score": 9.6427
|
||||
},
|
||||
{
|
||||
"topic_name": "Smart Agriculture and AI",
|
||||
"score": 9.279837
|
||||
},
|
||||
{
|
||||
"topic_name": "Underwater Vehicles and Communication Systems",
|
||||
"score": 9.279837
|
||||
},
|
||||
{
|
||||
"topic_name": "Modular Robots and Swarm Intelligence",
|
||||
"score": 7.7584143
|
||||
},
|
||||
{
|
||||
"topic_name": "Diverse Perspectives in Modern Studies",
|
||||
"score": 5.6107
|
||||
},
|
||||
{
|
||||
"topic_name": "Teleoperation and Haptic Systems",
|
||||
"score": 5.2510495
|
||||
},
|
||||
{
|
||||
"topic_name": "Optimization and Search Problems",
|
||||
"score": 5.1682277
|
||||
},
|
||||
{
|
||||
"topic_name": "Adaptive Dynamic Programming Control",
|
||||
"score": 4.8615155
|
||||
},
|
||||
{
|
||||
"topic_name": "Robotic Mechanisms and Dynamics",
|
||||
"score": 2.6450925
|
||||
},
|
||||
{
|
||||
"topic_name": "Control and Dynamics of Mobile Robots",
|
||||
"score": 2.5917463
|
||||
},
|
||||
{
|
||||
"topic_name": "Robot Manipulation and Learning",
|
||||
"score": 2.5859585
|
||||
},
|
||||
{
|
||||
"topic_name": "Robotic Process Automation Applications",
|
||||
"score": 1.7370787
|
||||
},
|
||||
{
|
||||
"topic_name": "Robotic Path Planning Algorithms",
|
||||
"score": 1.6302633
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -27095,4 +27095,4 @@
|
||||
"field": "Medicine",
|
||||
"domain": "Health Sciences"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+17
-17
@@ -1,18 +1,18 @@
|
||||
{
|
||||
"users": [
|
||||
{
|
||||
"account": 0,
|
||||
"organization": 0,
|
||||
"username": "superadmin",
|
||||
"password": "superadmin",
|
||||
"superadmin": true
|
||||
},
|
||||
{
|
||||
"account": 1,
|
||||
"organization": 1,
|
||||
"username": "user",
|
||||
"password": "user",
|
||||
"superadmin": false
|
||||
}
|
||||
]
|
||||
}
|
||||
"users": [
|
||||
{
|
||||
"account": 0,
|
||||
"organization": 0,
|
||||
"username": "superadmin",
|
||||
"password": "superadmin",
|
||||
"superadmin": true
|
||||
},
|
||||
{
|
||||
"account": 1,
|
||||
"organization": 1,
|
||||
"username": "user",
|
||||
"password": "user",
|
||||
"superadmin": false
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
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==
|
||||
|
||||
LLM_API_URL=https://project.nes.uni-due.de/llm2/v1/
|
||||
LLM_API_KEY=c2d5e7ccf7a4760dd3d19bed2caed9d85ff7437400e0ea82a6d6f912ebc2f212
|
||||
LLM_MODEL=gemma4-e4b
|
||||
LLM_MODEL=gemma4-e4b
|
||||
|
||||
ELASTICSEARCH_INSE_URL=https://inse.nes.uni-due.de/elastic
|
||||
ELASTICSEARCH_INSE_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
|
||||
@@ -3,7 +3,7 @@ from typing import List, Optional, Set
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from inse.models.work_topic import WorkTopic
|
||||
from inse.models.openalex.work_topic import WorkTopic
|
||||
from inse.utils import extract_raw_topic_id
|
||||
|
||||
|
||||
|
||||
@@ -26,11 +26,11 @@ from inse.utils import (
|
||||
extract_raw_topic_id,
|
||||
extract_raw_work_id,
|
||||
)
|
||||
from inse.models.author import Author
|
||||
from inse.models.authorship import Authorship
|
||||
from inse.models.dehydrated_author import DehydratedAuthor
|
||||
from inse.models.dehydrated_institution import DehydratedInstitution
|
||||
from inse.models.institution import Institution
|
||||
from inse.models.openalex.author import Author
|
||||
from inse.models.openalex.authorship import Authorship
|
||||
from inse.models.openalex.dehydrated_author import DehydratedAuthor
|
||||
from inse.models.openalex.dehydrated_institution import DehydratedInstitution
|
||||
from inse.models.openalex.institution import Institution
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -47,6 +47,8 @@ class Settings(BaseSettings):
|
||||
# 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
|
||||
|
||||
model_config = SettingsConfigDict(env_file=".env")
|
||||
|
||||
@@ -56,6 +58,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"
|
||||
|
||||
|
||||
settings = Settings()
|
||||
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
class NotFoundException(Exception):
|
||||
def __init__(self, message: str):
|
||||
super().__init__(message)
|
||||
@@ -78,22 +78,53 @@ class FundedPublicationsSearchClient:
|
||||
"doi",
|
||||
"title",
|
||||
"display_name",
|
||||
"abstract_inverted_index",
|
||||
"publication_year",
|
||||
"publication_date",
|
||||
"type",
|
||||
"language",
|
||||
"cited_by_count",
|
||||
"is_retracted",
|
||||
"primary_location.landing_page_url",
|
||||
"primary_location.pdf_url",
|
||||
"primary_location.is_oa",
|
||||
"primary_location.license",
|
||||
"primary_location.source.display_name",
|
||||
"primary_location.source.type",
|
||||
"best_oa_location.landing_page_url",
|
||||
"best_oa_location.pdf_url",
|
||||
"best_oa_location.is_oa",
|
||||
"best_oa_location.license",
|
||||
"best_oa_location.source.display_name",
|
||||
"open_access.oa_url",
|
||||
"open_access.is_oa",
|
||||
"open_access.oa_status",
|
||||
"open_access.any_repository_has_fulltext",
|
||||
"topics.display_name",
|
||||
"topics.score",
|
||||
"primary_topic.display_name",
|
||||
"primary_topic.subfield.display_name",
|
||||
"primary_topic.field.display_name",
|
||||
"primary_topic.domain.display_name",
|
||||
"keywords.display_name",
|
||||
"keywords.score",
|
||||
"counts_by_year.year",
|
||||
"counts_by_year.cited_by_count",
|
||||
"authorships.author.id",
|
||||
"authorships.author.display_name",
|
||||
"authorships.author_position",
|
||||
"authorships.institutions.display_name",
|
||||
"authorships.institutions.country_code",
|
||||
"authorships.countries",
|
||||
"funders.id",
|
||||
"funders.display_name",
|
||||
"funders.ror",
|
||||
"awards.id",
|
||||
"awards.display_name",
|
||||
"awards.funder_id",
|
||||
"awards.funder_display_name",
|
||||
"awards.funder_award_id",
|
||||
"awards.doi",
|
||||
]
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -242,6 +242,246 @@ def _resolve_publication_url(publication: dict) -> str | None:
|
||||
return publication.get("id")
|
||||
|
||||
|
||||
def _publication_author_names(publication: dict) -> list[str]:
|
||||
names: list[str] = []
|
||||
for authorship in publication.get("authorships", []):
|
||||
author_name = authorship.get("author", {}).get("display_name")
|
||||
if author_name:
|
||||
names.append(author_name)
|
||||
return names
|
||||
|
||||
|
||||
def _unique_strings(values: list[Any], limit: int | None = None) -> list[str]:
|
||||
seen: set[str] = set()
|
||||
unique_values: list[str] = []
|
||||
for value in values:
|
||||
if not value:
|
||||
continue
|
||||
text = str(value).strip()
|
||||
if not text or text in seen:
|
||||
continue
|
||||
seen.add(text)
|
||||
unique_values.append(text)
|
||||
if limit and len(unique_values) >= limit:
|
||||
break
|
||||
return unique_values
|
||||
|
||||
|
||||
def _publication_pdf_url(publication: dict) -> str | None:
|
||||
primary_location = publication.get("primary_location") or {}
|
||||
best_oa_location = publication.get("best_oa_location") or {}
|
||||
return primary_location.get("pdf_url") or best_oa_location.get("pdf_url")
|
||||
|
||||
|
||||
def _publication_source(publication: dict) -> dict:
|
||||
primary_location = publication.get("primary_location") or {}
|
||||
best_oa_location = publication.get("best_oa_location") or {}
|
||||
primary_source = primary_location.get("source") or {}
|
||||
best_oa_source = best_oa_location.get("source") or {}
|
||||
return primary_source or best_oa_source
|
||||
|
||||
|
||||
def _publication_license(publication: dict) -> str | None:
|
||||
primary_location = publication.get("primary_location") or {}
|
||||
best_oa_location = publication.get("best_oa_location") or {}
|
||||
return primary_location.get("license") or best_oa_location.get("license")
|
||||
|
||||
|
||||
def _publication_is_open_access(publication: dict) -> bool:
|
||||
primary_location = publication.get("primary_location") or {}
|
||||
best_oa_location = publication.get("best_oa_location") or {}
|
||||
open_access = publication.get("open_access") or {}
|
||||
return bool(
|
||||
open_access.get("is_oa")
|
||||
or open_access.get("oa_url")
|
||||
or primary_location.get("is_oa")
|
||||
or best_oa_location.get("is_oa")
|
||||
)
|
||||
|
||||
|
||||
def _publication_has_fulltext(publication: dict) -> bool:
|
||||
open_access = publication.get("open_access") or {}
|
||||
return bool(open_access.get("any_repository_has_fulltext") or _publication_pdf_url(publication))
|
||||
|
||||
|
||||
def _publication_topic_names(publication: dict) -> list[str]:
|
||||
topics = publication.get("topics")
|
||||
if not isinstance(topics, list):
|
||||
return []
|
||||
|
||||
sorted_topics = sorted(
|
||||
topics,
|
||||
key=lambda topic: topic.get("score", 0) if isinstance(topic, dict) else 0,
|
||||
reverse=True,
|
||||
)
|
||||
return _unique_strings(
|
||||
[topic.get("display_name") for topic in sorted_topics if isinstance(topic, dict)],
|
||||
limit=6,
|
||||
)
|
||||
|
||||
|
||||
def _publication_keyword_names(publication: dict) -> list[str]:
|
||||
keywords = publication.get("keywords")
|
||||
if not isinstance(keywords, list):
|
||||
return []
|
||||
|
||||
sorted_keywords = sorted(
|
||||
keywords,
|
||||
key=lambda keyword: keyword.get("score", 0) if isinstance(keyword, dict) else 0,
|
||||
reverse=True,
|
||||
)
|
||||
return _unique_strings(
|
||||
[keyword.get("display_name") for keyword in sorted_keywords if isinstance(keyword, dict)],
|
||||
limit=8,
|
||||
)
|
||||
|
||||
|
||||
def _publication_institutions(publication: dict) -> list[str]:
|
||||
institution_names: list[str] = []
|
||||
for authorship in publication.get("authorships", []):
|
||||
if not isinstance(authorship, dict):
|
||||
continue
|
||||
for institution in authorship.get("institutions") or []:
|
||||
if isinstance(institution, dict):
|
||||
institution_names.append(institution.get("display_name"))
|
||||
return _unique_strings(institution_names, limit=8)
|
||||
|
||||
|
||||
def _publication_countries(publication: dict) -> list[str]:
|
||||
countries: list[str] = []
|
||||
for authorship in publication.get("authorships", []):
|
||||
if not isinstance(authorship, dict):
|
||||
continue
|
||||
countries.extend(authorship.get("countries") or [])
|
||||
for institution in authorship.get("institutions") or []:
|
||||
if isinstance(institution, dict):
|
||||
countries.append(institution.get("country_code"))
|
||||
return _unique_strings(countries, limit=8)
|
||||
|
||||
|
||||
def _publication_counts_by_year(publication: dict) -> list[dict[str, int]]:
|
||||
counts_by_year = publication.get("counts_by_year")
|
||||
if not isinstance(counts_by_year, list):
|
||||
return []
|
||||
|
||||
sanitized_counts: list[dict[str, int]] = []
|
||||
for year_count in counts_by_year:
|
||||
if not isinstance(year_count, dict):
|
||||
continue
|
||||
year = year_count.get("year")
|
||||
cited_by_count = year_count.get("cited_by_count")
|
||||
if isinstance(year, int) and isinstance(cited_by_count, int):
|
||||
sanitized_counts.append({"year": year, "cited_by_count": cited_by_count})
|
||||
|
||||
return sorted(sanitized_counts, key=lambda year_count: year_count["year"], reverse=True)[:6]
|
||||
|
||||
|
||||
def _publication_funder_names(publication: dict) -> list[str]:
|
||||
names: list[Any] = []
|
||||
for funder in publication.get("funders", []):
|
||||
if isinstance(funder, dict):
|
||||
names.append(funder.get("display_name"))
|
||||
|
||||
for award in publication.get("awards", []):
|
||||
if isinstance(award, dict):
|
||||
names.append(award.get("funder_display_name"))
|
||||
|
||||
return sorted(_unique_strings(names), key=str.casefold)
|
||||
|
||||
|
||||
def _publication_grant_labels(
|
||||
publication: dict,
|
||||
funder_id: str | None,
|
||||
funder_name: str | None,
|
||||
) -> list[str]:
|
||||
labels: list[str] = []
|
||||
for award in publication.get("awards", []):
|
||||
if not isinstance(award, dict):
|
||||
continue
|
||||
award_funder_id = award.get("funder_id")
|
||||
award_funder_name = award.get("funder_display_name")
|
||||
matches_funder_id = bool(funder_id and award_funder_id == funder_id)
|
||||
matches_funder_name = bool(funder_name and award_funder_name == funder_name)
|
||||
has_funder_reference = bool(award_funder_id or award_funder_name)
|
||||
if has_funder_reference and not (matches_funder_id or matches_funder_name):
|
||||
continue
|
||||
|
||||
display_name = award.get("display_name")
|
||||
if display_name:
|
||||
labels.append(display_name)
|
||||
|
||||
return _unique_strings(labels, limit=6)
|
||||
|
||||
|
||||
def _publication_abstract(publication: dict) -> str | None:
|
||||
inverted_index = publication.get("abstract_inverted_index")
|
||||
if not isinstance(inverted_index, dict):
|
||||
return None
|
||||
|
||||
words: list[tuple[int, str]] = []
|
||||
for word, positions in inverted_index.items():
|
||||
if not isinstance(positions, list):
|
||||
continue
|
||||
for position in positions:
|
||||
if isinstance(position, int):
|
||||
words.append((position, word))
|
||||
|
||||
if not words:
|
||||
return None
|
||||
|
||||
return " ".join(word for _, word in sorted(words))
|
||||
|
||||
|
||||
def _publication_detail_summary(
|
||||
publication: dict,
|
||||
publication_id: str,
|
||||
publication_url: str | None,
|
||||
author_position: str,
|
||||
funder_id: str | None,
|
||||
funder_name: str | None,
|
||||
) -> dict[str, Any]:
|
||||
title = publication.get("title") or publication.get("display_name") or publication_id
|
||||
source = _publication_source(publication)
|
||||
open_access = publication.get("open_access") or {}
|
||||
primary_topic = publication.get("primary_topic") or {}
|
||||
topic_field = primary_topic.get("field") or {}
|
||||
topic_subfield = primary_topic.get("subfield") or {}
|
||||
topic_domain = primary_topic.get("domain") or {}
|
||||
return {
|
||||
"id": publication_id,
|
||||
"title": title,
|
||||
"abstract": _publication_abstract(publication),
|
||||
"doi": publication.get("doi"),
|
||||
"publication_year": publication.get("publication_year"),
|
||||
"publication_date": publication.get("publication_date"),
|
||||
"publication_type": publication.get("type"),
|
||||
"language": publication.get("language"),
|
||||
"publication_url": publication_url,
|
||||
"pdf_url": _publication_pdf_url(publication),
|
||||
"source_name": source.get("display_name"),
|
||||
"source_type": source.get("type"),
|
||||
"is_open_access": _publication_is_open_access(publication),
|
||||
"open_access_status": open_access.get("oa_status"),
|
||||
"has_fulltext": _publication_has_fulltext(publication),
|
||||
"license": _publication_license(publication),
|
||||
"cited_by_count": publication.get("cited_by_count"),
|
||||
"is_retracted": publication.get("is_retracted"),
|
||||
"primary_topic": primary_topic.get("display_name"),
|
||||
"topic_field": topic_field.get("display_name"),
|
||||
"topic_subfield": topic_subfield.get("display_name"),
|
||||
"topic_domain": topic_domain.get("display_name"),
|
||||
"author_position": author_position,
|
||||
"authors": _publication_author_names(publication),
|
||||
"funder_names": _publication_funder_names(publication),
|
||||
"institutions": _publication_institutions(publication),
|
||||
"countries": _publication_countries(publication),
|
||||
"topics": _publication_topic_names(publication),
|
||||
"keywords": _publication_keyword_names(publication),
|
||||
"grant_labels": _publication_grant_labels(publication, funder_id, funder_name),
|
||||
"counts_by_year": _publication_counts_by_year(publication),
|
||||
}
|
||||
|
||||
|
||||
def _collect_funders_from_publications(
|
||||
results: list[dict],
|
||||
author_id: str,
|
||||
@@ -291,6 +531,7 @@ def _collect_funders_from_publications(
|
||||
},
|
||||
"publication_urls": {},
|
||||
"publication_titles": {},
|
||||
"publication_details": {},
|
||||
}
|
||||
|
||||
entry = funder_counts[key]
|
||||
@@ -302,4 +543,12 @@ def _collect_funders_from_publications(
|
||||
if publication_id:
|
||||
title = publication.get("display_name") or publication.get("title") or publication_id
|
||||
entry["publication_titles"][publication_id] = title
|
||||
entry["publication_details"][publication_id] = _publication_detail_summary(
|
||||
publication,
|
||||
publication_id,
|
||||
publication_url,
|
||||
author_position,
|
||||
funder_id,
|
||||
funder_name,
|
||||
)
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
from typing import Any
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic import Field
|
||||
|
||||
|
||||
class PublicationsByAuthorResponse(BaseModel):
|
||||
@@ -27,6 +28,40 @@ class AuthorPositionCount(BaseModel):
|
||||
unknown: int = 0
|
||||
|
||||
|
||||
class PublicationDetailByFunder(BaseModel):
|
||||
id: str
|
||||
title: str
|
||||
abstract: str | None = None
|
||||
doi: str | None = None
|
||||
publication_year: int | None = None
|
||||
publication_date: str | None = None
|
||||
publication_type: str | None = None
|
||||
language: str | None = None
|
||||
publication_url: str | None = None
|
||||
pdf_url: str | None = None
|
||||
source_name: str | None = None
|
||||
source_type: str | None = None
|
||||
is_open_access: bool | None = None
|
||||
open_access_status: str | None = None
|
||||
has_fulltext: bool | None = None
|
||||
license: str | None = None
|
||||
cited_by_count: int | None = None
|
||||
is_retracted: bool | None = None
|
||||
primary_topic: str | None = None
|
||||
topic_field: str | None = None
|
||||
topic_subfield: str | None = None
|
||||
topic_domain: str | None = None
|
||||
author_position: str | None = None
|
||||
authors: list[str] = Field(default_factory=list)
|
||||
funder_names: list[str] = Field(default_factory=list)
|
||||
institutions: list[str] = Field(default_factory=list)
|
||||
countries: list[str] = Field(default_factory=list)
|
||||
topics: list[str] = Field(default_factory=list)
|
||||
keywords: list[str] = Field(default_factory=list)
|
||||
grant_labels: list[str] = Field(default_factory=list)
|
||||
counts_by_year: list[dict[str, Any]] = Field(default_factory=list)
|
||||
|
||||
|
||||
class FunderByAuthor(BaseModel):
|
||||
funder_id: str | None = None
|
||||
funder_name: str | None = None
|
||||
@@ -35,6 +70,7 @@ class FunderByAuthor(BaseModel):
|
||||
publication_ids: PublicationIdsByAuthorPosition
|
||||
publication_urls: dict[str, str] = {}
|
||||
publication_titles: dict[str, str] = {}
|
||||
publication_details: dict[str, PublicationDetailByFunder] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class FundersByAuthorResponse(BaseModel):
|
||||
|
||||
@@ -21,7 +21,11 @@ def _funded_publication_hit(
|
||||
author_position: str = "first",
|
||||
award_funder_id: str | None = None,
|
||||
award_funder_name: str | None = None,
|
||||
award_display_name: str | None = None,
|
||||
award_number: str | None = None,
|
||||
pdf_url: str | None = None,
|
||||
abstract_inverted_index: dict | None = None,
|
||||
extra_source: dict | None = None,
|
||||
) -> dict:
|
||||
source: dict = {
|
||||
"id": work_id,
|
||||
@@ -40,6 +44,10 @@ def _funded_publication_hit(
|
||||
"funders": [],
|
||||
"awards": [],
|
||||
}
|
||||
if abstract_inverted_index:
|
||||
source["abstract_inverted_index"] = abstract_inverted_index
|
||||
if extra_source:
|
||||
source.update(extra_source)
|
||||
if funder_id or funder_name:
|
||||
source["funders"].append(
|
||||
{
|
||||
@@ -52,6 +60,8 @@ def _funded_publication_hit(
|
||||
{
|
||||
"funder_id": award_funder_id,
|
||||
"funder_display_name": award_funder_name,
|
||||
"display_name": award_display_name,
|
||||
"funder_award_id": award_number,
|
||||
}
|
||||
)
|
||||
return {"_source": source}
|
||||
@@ -74,6 +84,59 @@ async def test_get_funders_by_author_id_aggregates_funders_and_awards(monkeypatc
|
||||
funder_name="Funder A",
|
||||
author_position="first",
|
||||
pdf_url="https://example.org/w1.pdf",
|
||||
abstract_inverted_index={
|
||||
"This": [0],
|
||||
"is": [1],
|
||||
"an": [2],
|
||||
"abstract.": [3],
|
||||
},
|
||||
extra_source={
|
||||
"title": "Example publication: full detail",
|
||||
"funders": [
|
||||
{
|
||||
"id": "https://openalex.org/F456",
|
||||
"display_name": "Funder B",
|
||||
}
|
||||
],
|
||||
"publication_year": 2020,
|
||||
"publication_date": "2020-05-10",
|
||||
"type": "article",
|
||||
"language": "en",
|
||||
"cited_by_count": 12,
|
||||
"is_retracted": False,
|
||||
"primary_location": {
|
||||
"pdf_url": "https://example.org/w1.pdf",
|
||||
"is_oa": True,
|
||||
"license": "cc-by",
|
||||
"source": {
|
||||
"display_name": "Example Journal",
|
||||
"type": "journal",
|
||||
},
|
||||
},
|
||||
"open_access": {
|
||||
"is_oa": True,
|
||||
"oa_status": "gold",
|
||||
"any_repository_has_fulltext": True,
|
||||
},
|
||||
"primary_topic": {
|
||||
"display_name": "Clinical Trials",
|
||||
"subfield": {"display_name": "Medicine"},
|
||||
"field": {"display_name": "Health Sciences"},
|
||||
"domain": {"display_name": "Life Sciences"},
|
||||
},
|
||||
"topics": [
|
||||
{"display_name": "Trials", "score": 0.8},
|
||||
{"display_name": "Guidelines", "score": 0.6},
|
||||
],
|
||||
"keywords": [
|
||||
{"display_name": "randomised trials", "score": 0.9},
|
||||
{"display_name": "reporting guideline", "score": 0.7},
|
||||
],
|
||||
"counts_by_year": [
|
||||
{"year": 2024, "cited_by_count": 3},
|
||||
{"year": 2023, "cited_by_count": 2},
|
||||
],
|
||||
},
|
||||
),
|
||||
_funded_publication_hit(
|
||||
"https://openalex.org/W2",
|
||||
@@ -81,6 +144,8 @@ async def test_get_funders_by_author_id_aggregates_funders_and_awards(monkeypatc
|
||||
funder_name=None,
|
||||
award_funder_id="https://openalex.org/F123",
|
||||
award_funder_name="Funder A",
|
||||
award_display_name="Project Grant",
|
||||
award_number="PG-42",
|
||||
author_position="last",
|
||||
),
|
||||
],
|
||||
@@ -108,7 +173,7 @@ async def test_get_funders_by_author_id_aggregates_funders_and_awards(monkeypatc
|
||||
|
||||
assert response.author_id == "https://openalex.org/A5023888391"
|
||||
assert response.author_name == "Example Author"
|
||||
assert response.funder_count == 1
|
||||
assert response.funder_count == 2
|
||||
assert response.funders[0].funder_id == "https://openalex.org/F123"
|
||||
assert response.funders[0].funder_name == "Funder A"
|
||||
assert response.funders[0].publication_count == 2
|
||||
@@ -118,6 +183,76 @@ async def test_get_funders_by_author_id_aggregates_funders_and_awards(monkeypatc
|
||||
assert response.funders[0].publication_ids.last == ["https://openalex.org/W2"]
|
||||
assert response.funders[0].publication_urls["https://openalex.org/W1"] == "https://example.org/w1.pdf"
|
||||
assert response.funders[0].publication_urls["https://openalex.org/W2"] == "https://openalex.org/W2"
|
||||
publication_detail = response.funders[0].publication_details["https://openalex.org/W1"]
|
||||
assert publication_detail.title == "Example publication: full detail"
|
||||
assert publication_detail.funder_names == ["Funder A", "Funder B"]
|
||||
assert publication_detail.abstract == "This is an abstract."
|
||||
assert publication_detail.publication_date == "2020-05-10"
|
||||
assert publication_detail.publication_type == "article"
|
||||
assert publication_detail.source_name == "Example Journal"
|
||||
assert publication_detail.source_type == "journal"
|
||||
assert publication_detail.is_open_access is True
|
||||
assert publication_detail.open_access_status == "gold"
|
||||
assert publication_detail.has_fulltext is True
|
||||
assert publication_detail.license == "cc-by"
|
||||
assert publication_detail.cited_by_count == 12
|
||||
assert publication_detail.primary_topic == "Clinical Trials"
|
||||
assert publication_detail.topic_field == "Health Sciences"
|
||||
assert publication_detail.topic_subfield == "Medicine"
|
||||
assert publication_detail.topic_domain == "Life Sciences"
|
||||
assert publication_detail.topics == ["Trials", "Guidelines"]
|
||||
assert publication_detail.keywords == ["randomised trials", "reporting guideline"]
|
||||
assert publication_detail.counts_by_year == [
|
||||
{"year": 2024, "cited_by_count": 3},
|
||||
{"year": 2023, "cited_by_count": 2},
|
||||
]
|
||||
assert response.funders[0].publication_details["https://openalex.org/W2"].grant_labels == [
|
||||
"Project Grant"
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_publication_grant_labels_ignore_funder_award_id_without_display_name(monkeypatch):
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"hits": {
|
||||
"total": {"value": 1},
|
||||
"hits": [
|
||||
_funded_publication_hit(
|
||||
"https://openalex.org/W3",
|
||||
funder_id="https://openalex.org/F123",
|
||||
funder_name="Funder A",
|
||||
award_funder_id="https://openalex.org/F123",
|
||||
award_funder_name="Funder A",
|
||||
award_display_name=None,
|
||||
award_number="ANR-12-1234",
|
||||
),
|
||||
],
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
monkeypatch.setattr(
|
||||
logic.person_logic,
|
||||
"search_persons",
|
||||
lambda author_id: type(
|
||||
"Result",
|
||||
(),
|
||||
{"results": [type("Author", (), {"display_name": "Example Author"})()]},
|
||||
)(),
|
||||
)
|
||||
|
||||
client = FundedPublicationsSearchClient(
|
||||
base_url="https://project.nes.uni-due.de/elastic",
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
|
||||
response = await logic.get_funders_by_author_id("A5023888391", client=client)
|
||||
|
||||
assert response.funders[0].publication_details["https://openalex.org/W3"].grant_labels == []
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
import logging
|
||||
from typing import List, Set
|
||||
|
||||
import httpx
|
||||
|
||||
from inse.models.openalex.institution import Institution
|
||||
from inse.exceptions import NotFoundException
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class InstitutionsSearchClient:
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str,
|
||||
api_key: str,
|
||||
):
|
||||
self.base_url = base_url
|
||||
self.api_key = api_key
|
||||
self.headers = {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": f"ApiKey {self.api_key}",
|
||||
}
|
||||
|
||||
async def get_institution_by_id(self, raw_institution_id: str) -> Institution:
|
||||
query = {
|
||||
"query": {
|
||||
"match": {
|
||||
"id": f"https://openalex.org/{raw_institution_id.upper()}",
|
||||
}
|
||||
},
|
||||
"size": 1,
|
||||
}
|
||||
authors = await self.get_authors_by_institution_id(raw_institution_id)
|
||||
logger.debug(
|
||||
"Retrieved authors for institution_id=%s: %s", raw_institution_id, authors
|
||||
)
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.post(
|
||||
f"{self.base_url}/openalex-institutions/_search",
|
||||
json=query,
|
||||
headers=self.headers,
|
||||
)
|
||||
response.raise_for_status()
|
||||
hits = response.json().get("hits", {}).get("hits", [])
|
||||
if not hits:
|
||||
raise NotFoundException(
|
||||
f"Institution with ID '{raw_institution_id}' not found."
|
||||
)
|
||||
|
||||
return Institution.from_dict(hits[0]["_source"])
|
||||
|
||||
async def get_authors_by_institution_id(self, raw_institution_id: str) -> List[str]:
|
||||
query = {
|
||||
"query": {
|
||||
"nested": {
|
||||
"path": "affiliations",
|
||||
"query": {
|
||||
"bool": {
|
||||
"must": [
|
||||
{
|
||||
"term": {
|
||||
"affiliations.institution.id": f"https://openalex.org/{raw_institution_id.upper()}"
|
||||
}
|
||||
},
|
||||
{
|
||||
"range": {
|
||||
"affiliations.years": {"gte": 2026, "lte": 2026}
|
||||
}
|
||||
},
|
||||
]
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
logger.debug(
|
||||
"Fetching authors for institution_id=%s with query: %s",
|
||||
raw_institution_id,
|
||||
query,
|
||||
)
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.post(
|
||||
"https://project.nes.uni-due.de/elastic/openalex-authors/_search",
|
||||
json=query,
|
||||
headers=self.headers,
|
||||
)
|
||||
try:
|
||||
response.raise_for_status()
|
||||
except httpx.HTTPStatusError as e:
|
||||
logger.exception(
|
||||
"Error fetching authors for institution_id=%s: %s, response content: %s",
|
||||
raw_institution_id,
|
||||
str(e),
|
||||
response.text,
|
||||
)
|
||||
return []
|
||||
hits = response.json().get("hits", {}).get("hits", [])
|
||||
authors = set()
|
||||
for hit in hits:
|
||||
authors.update(
|
||||
auth["author"]["display_name"]
|
||||
for auth in hit["_source"].get("authorships", [])
|
||||
)
|
||||
return list(authors)
|
||||
|
||||
async 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_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 = await 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_institution_id)
|
||||
)
|
||||
logger.debug(
|
||||
"Retrieved aliases for institution_id=%s: %s", raw_institution_id, aliases
|
||||
)
|
||||
return aliases
|
||||
|
||||
def get_predefined_institution_aliases(self, raw_institution_id: str) -> Set[str]:
|
||||
"""Get predefined aliases for a given institution ID.
|
||||
|
||||
Args:
|
||||
raw_institution_id (str): The raw institution ID for which to retrieve predefined aliases.
|
||||
|
||||
Returns:
|
||||
Set[str]: A set of predefined aliases for the given institution ID.
|
||||
"""
|
||||
raw_institution_id = raw_institution_id.upper()
|
||||
predefined_aliases = {
|
||||
"I62318514": [
|
||||
"universität duisburg-essen",
|
||||
"university of duisburg-essen",
|
||||
"universitaet duisburg-essen",
|
||||
"universität duisburg-essen",
|
||||
"universitat duisburg-essen",
|
||||
],
|
||||
}
|
||||
|
||||
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.
|
||||
|
||||
Args:
|
||||
aliases (Set[str]): A set of aliases to augment.
|
||||
|
||||
Returns:
|
||||
Set[str]: A set of augmented aliases.
|
||||
"""
|
||||
augmented_aliases = set()
|
||||
for alias in aliases:
|
||||
augmented_aliases.update(self.augment_alias(alias))
|
||||
return augmented_aliases
|
||||
|
||||
def augment_alias(self, alias: str) -> List[str]:
|
||||
"""Augment an alias by replacing German umlauts and ß with their alternative spellings.
|
||||
|
||||
Args:
|
||||
alias (str): The alias to augment.
|
||||
|
||||
Returns:
|
||||
List[str]: A list of augmented aliases.
|
||||
"""
|
||||
alias = alias.lower()
|
||||
aliases = [alias]
|
||||
aliases.append(
|
||||
alias.replace("ä", "ae")
|
||||
.replace("ö", "oe")
|
||||
.replace("ü", "ue")
|
||||
.replace("ß", "ss")
|
||||
)
|
||||
aliases.append(
|
||||
alias.replace("ae", "ä")
|
||||
.replace("oe", "ö")
|
||||
.replace("ue", "ü")
|
||||
.replace("ss", "ß")
|
||||
)
|
||||
aliases.append(
|
||||
alias.replace("ä", "a")
|
||||
.replace("ö", "o")
|
||||
.replace("ü", "u")
|
||||
.replace("ß", "s")
|
||||
)
|
||||
aliases.append(alias.replace("-", " "))
|
||||
return aliases
|
||||
@@ -3,9 +3,10 @@
|
||||
"""
|
||||
Business logic for OpenAlex institutions.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from copy import deepcopy
|
||||
from typing import Any
|
||||
from typing import Any, Optional
|
||||
|
||||
import httpx
|
||||
from fastapi import HTTPException
|
||||
@@ -13,11 +14,15 @@ from pydantic import ValidationError
|
||||
from starlette.status import HTTP_400_BAD_REQUEST
|
||||
from starlette.status import HTTP_502_BAD_GATEWAY
|
||||
|
||||
from inse.models.autocomplete_response import AutocompleteResponse
|
||||
from inse.models.autocomplete_response_meta import AutocompleteResponseMeta
|
||||
from inse.models.autocomplete_response_results_inner import AutocompleteResponseResultsInner
|
||||
from inse.models.institutions_list_response import InstitutionsListResponse
|
||||
from inse.models.openalex.autocomplete_response import AutocompleteResponse
|
||||
from inse.models.openalex.autocomplete_response_meta import AutocompleteResponseMeta
|
||||
from inse.models.openalex.autocomplete_response_results_inner import (
|
||||
AutocompleteResponseResultsInner,
|
||||
)
|
||||
from inse.models.openalex.institutions_list_response import InstitutionsListResponse
|
||||
from inse.models.openalex.institution import Institution
|
||||
from .search_client import OpenAlexInstitutionsClient
|
||||
from inse.institutions.institutions_search_client import InstitutionsSearchClient
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -33,6 +38,12 @@ _VALID_INSTITUTION_TYPES = {
|
||||
}
|
||||
|
||||
|
||||
async def get_institution_by_id(
|
||||
raw_institution_id: str, client: InstitutionsSearchClient
|
||||
) -> Institution:
|
||||
return await client.get_institution_by_id(raw_institution_id)
|
||||
|
||||
|
||||
async def list_institutions(
|
||||
*,
|
||||
search: str | None = None,
|
||||
@@ -85,7 +96,10 @@ async def list_institutions(
|
||||
|
||||
try:
|
||||
normalized_data = _normalize_institutions_response(data)
|
||||
return InstitutionsListResponse.from_dict(normalized_data) or InstitutionsListResponse()
|
||||
return (
|
||||
InstitutionsListResponse.from_dict(normalized_data)
|
||||
or InstitutionsListResponse()
|
||||
)
|
||||
except ValidationError as exc:
|
||||
logger.exception("OpenAlex institutions response could not be parsed.")
|
||||
raise HTTPException(
|
||||
@@ -114,10 +128,7 @@ async def autocomplete_institutions(
|
||||
sort="works_count:desc",
|
||||
per_page=limit,
|
||||
page=1,
|
||||
select=(
|
||||
"id,ror,display_name,country_code,type,works_count,"
|
||||
"cited_by_count,geo"
|
||||
),
|
||||
select=("id,ror,display_name,country_code,type,works_count,cited_by_count,geo"),
|
||||
client=client,
|
||||
)
|
||||
|
||||
@@ -165,7 +176,13 @@ def _normalize_institutions_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"))
|
||||
@@ -187,7 +204,10 @@ def _normalize_institutions_response(data: dict[str, Any]) -> dict[str, Any]:
|
||||
institution[field] = _str_or_none(institution.get(field))
|
||||
|
||||
institution_type = institution.get("type")
|
||||
if institution_type is not None and institution_type not in _VALID_INSTITUTION_TYPES:
|
||||
if (
|
||||
institution_type is not None
|
||||
and institution_type not in _VALID_INSTITUTION_TYPES
|
||||
):
|
||||
institution["type"] = None
|
||||
else:
|
||||
institution["type"] = _str_or_none(institution_type)
|
||||
@@ -202,7 +222,9 @@ def _normalize_institutions_response(data: dict[str, Any]) -> dict[str, Any]:
|
||||
institution["works_count"] = _int_or_none(institution.get("works_count"))
|
||||
institution["cited_by_count"] = _int_or_none(institution.get("cited_by_count"))
|
||||
institution["created_date"] = _date_str_or_none(institution.get("created_date"))
|
||||
institution["updated_date"] = _datetime_str_or_none(institution.get("updated_date"))
|
||||
institution["updated_date"] = _datetime_str_or_none(
|
||||
institution.get("updated_date")
|
||||
)
|
||||
|
||||
summary_stats = institution.get("summary_stats")
|
||||
if isinstance(summary_stats, dict):
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
"""
|
||||
HTTP client for OpenAlex institutions.
|
||||
"""
|
||||
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
@@ -19,8 +20,14 @@ class OpenAlexInstitutionsClient:
|
||||
transport: httpx.AsyncBaseTransport | None = None,
|
||||
):
|
||||
self.base_url = (base_url or config.settings.openalex_api_base_url).rstrip("/")
|
||||
self.api_key = api_key if api_key is not None else config.settings.openalex_api_key
|
||||
self.timeout = timeout if timeout is not None else config.settings.openalex_api_timeout_seconds
|
||||
self.api_key = (
|
||||
api_key if api_key is not None else config.settings.openalex_api_key
|
||||
)
|
||||
self.timeout = (
|
||||
timeout
|
||||
if timeout is not None
|
||||
else config.settings.openalex_api_timeout_seconds
|
||||
)
|
||||
self.transport = transport
|
||||
|
||||
def list_institutions_params(
|
||||
|
||||
@@ -3,20 +3,60 @@
|
||||
"""
|
||||
REST API for OpenAlex institutions.
|
||||
"""
|
||||
|
||||
from functools import lru_cache
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter
|
||||
from fastapi import Query
|
||||
from fastapi import APIRouter, Depends, status, Query
|
||||
|
||||
from inse.models.autocomplete_response import AutocompleteResponse
|
||||
from inse.models.institutions_list_response import InstitutionsListResponse
|
||||
from inse.models.openalex.autocomplete_response import AutocompleteResponse
|
||||
from inse.models.openalex.institutions_list_response import InstitutionsListResponse
|
||||
from inse.tags import Tags
|
||||
from inse.config import get_settings
|
||||
from inse.models.openalex.institution import Institution
|
||||
from . import logic
|
||||
from inse.institutions.institutions_search_client import InstitutionsSearchClient
|
||||
|
||||
|
||||
router = APIRouter(prefix="/api/institutions", tags=[Tags.INSTITUTIONS])
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_institutions_search_client() -> InstitutionsSearchClient:
|
||||
settings = get_settings()
|
||||
if not settings.elasticsearch_url:
|
||||
raise ValueError("Elasticsearch URL is missing in settings.")
|
||||
if not settings.elasticsearch_api_key:
|
||||
raise ValueError("Elasticsearch API key is missing in settings.")
|
||||
|
||||
return InstitutionsSearchClient(
|
||||
api_key=settings.elasticsearch_api_key,
|
||||
base_url=settings.elasticsearch_url,
|
||||
)
|
||||
|
||||
|
||||
@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(
|
||||
"/autocomplete",
|
||||
operation_id="autocompleteInstitutions",
|
||||
@@ -27,7 +67,10 @@ router = APIRouter(prefix="/api/institutions", tags=[Tags.INSTITUTIONS])
|
||||
async def autocomplete_institutions(
|
||||
query: Annotated[
|
||||
str,
|
||||
Query(description="Institution search text, for example 'Duisburg Essen'.", min_length=1),
|
||||
Query(
|
||||
description="Institution search text, for example 'Duisburg Essen'.",
|
||||
min_length=1,
|
||||
),
|
||||
],
|
||||
country_code: Annotated[
|
||||
str | None,
|
||||
@@ -64,7 +107,9 @@ async def list_institutions(
|
||||
] = None,
|
||||
filter: Annotated[
|
||||
str | None,
|
||||
Query(description="OpenAlex filter, for example 'country_code:DE,type:education'."),
|
||||
Query(
|
||||
description="OpenAlex filter, for example 'country_code:DE,type:education'."
|
||||
),
|
||||
] = None,
|
||||
sort: Annotated[
|
||||
str | None,
|
||||
@@ -88,7 +133,11 @@ async def list_institutions(
|
||||
] = None,
|
||||
sample: Annotated[
|
||||
int | None,
|
||||
Query(description="Random sample size. Cannot be combined with sort or page.", ge=1, le=10000),
|
||||
Query(
|
||||
description="Random sample size. Cannot be combined with sort or page.",
|
||||
ge=1,
|
||||
le=10000,
|
||||
),
|
||||
] = None,
|
||||
select: Annotated[
|
||||
str | None,
|
||||
|
||||
@@ -3,6 +3,16 @@ import httpx
|
||||
from .. import config
|
||||
|
||||
|
||||
def _cluster_credentials(cluster: str) -> tuple[str, str]:
|
||||
|
||||
if cluster == "nes":
|
||||
return config.settings.elasticsearch_url, config.settings.elasticsearch_api_key
|
||||
elif cluster == "inse":
|
||||
return config.settings.elasticsearch_inse_url, config.settings.elasticsearch_inse_api_key
|
||||
else:
|
||||
raise ValueError(f"Unbekannter Cluster: {cluster!r} (erlaubt: 'nes', 'inse')")
|
||||
|
||||
|
||||
def search(
|
||||
index: str,
|
||||
query_field: str = None,
|
||||
@@ -13,11 +23,14 @@ def search(
|
||||
offset:int = None,
|
||||
sort: list = None,
|
||||
body: dict = None,
|
||||
track_total_hits = False
|
||||
track_total_hits = False,
|
||||
cluster: str = "nes",
|
||||
) -> dict[str, Any]:
|
||||
|
||||
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
||||
|
||||
headers = {
|
||||
"Authorization": f"ApiKey {config.settings.elasticsearch_api_key}",
|
||||
"Authorization": f"ApiKey {api_key}",
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
@@ -45,22 +58,27 @@ def search(
|
||||
}
|
||||
}
|
||||
|
||||
with httpx.Client() as client:
|
||||
with httpx.Client(timeout=httpx.Timeout(30.0)) as client:
|
||||
response = client.post(
|
||||
f"{config.settings.elasticsearch_url}/{index}/_search",
|
||||
f"{elasticsearch_url}/{index}/_search",
|
||||
json=payload,
|
||||
headers=headers
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
|
||||
def get(
|
||||
index: str,
|
||||
doc_id: str,
|
||||
source: list = None,
|
||||
cluster: str = "nes",
|
||||
) -> dict[str, Any]:
|
||||
|
||||
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
||||
|
||||
headers = {
|
||||
"Authorization": f"ApiKey {config.settings.elasticsearch_api_key}",
|
||||
"Authorization": f"ApiKey {api_key}",
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
@@ -70,11 +88,9 @@ def get(
|
||||
|
||||
with httpx.Client() as client:
|
||||
response = client.get(
|
||||
f"{config.settings.elasticsearch_url}/{index}/_doc/{doc_id}",
|
||||
f"{elasticsearch_url}/{index}/_doc/{doc_id}",
|
||||
params=params,
|
||||
headers=headers
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
|
||||
|
||||
@@ -20,10 +20,10 @@ from . import model
|
||||
from . import config
|
||||
|
||||
|
||||
from inse.models.topic import Topic
|
||||
from inse.models.topic_subfield import TopicSubfield
|
||||
from inse.models.topic_field import TopicField
|
||||
from inse.models.topic_domain import TopicDomain
|
||||
from inse.models.openalex.topic import Topic
|
||||
from inse.models.openalex.topic_subfield import TopicSubfield
|
||||
from inse.models.openalex.topic_field import TopicField
|
||||
from inse.models.openalex.topic_domain import TopicDomain
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -7,8 +7,8 @@ webapp.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from fastapi import FastAPI
|
||||
from fastapi.responses import RedirectResponse
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.responses import JSONResponse, RedirectResponse
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from inse.collaboration_network.router import router as collaboration_network_router
|
||||
from inse.institutions.service import router as institutions_service_router
|
||||
@@ -16,7 +16,11 @@ from inse.topics.service import router as topics_service_router
|
||||
from inse.works.service import router as works_service_router
|
||||
from inse.persons.service import router as persons_service_router
|
||||
from inse.funders.service import router as funders_service_router
|
||||
from inse.projects.router import router as projects_router
|
||||
|
||||
# caching
|
||||
from inse.middleware.etag_cache import ETagCacheMiddleware
|
||||
from inse.exceptions import NotFoundException
|
||||
from . import config
|
||||
from .service import router as service_router
|
||||
from .account.service import router as account_router
|
||||
@@ -43,15 +47,27 @@ app.include_router(funders_service_router)
|
||||
app.include_router(service_router)
|
||||
app.include_router(account_router)
|
||||
|
||||
app.include_router(projects_router)
|
||||
|
||||
app.add_middleware(
|
||||
ETagCacheMiddleware,
|
||||
ttl=300, # 5 minutes expiration time
|
||||
)
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=settings.allowed_origins,
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
expose_headers=["ETag"],
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(NotFoundException)
|
||||
async def handle_not_found(request: Request, exc: NotFoundException):
|
||||
return JSONResponse(status_code=404, content={"message": str(exc)})
|
||||
|
||||
|
||||
@app.exception_handler(404)
|
||||
async def redirect(_, __):
|
||||
return RedirectResponse(url="/inse-webapp/")
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
# middleware/etag_cache.py
|
||||
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)
|
||||
self.ttl = ttl # timeout in seconds
|
||||
self.cache: dict[str, dict] = {} # key → {body, etag, expires}
|
||||
|
||||
def _cache_key(self, request: Request) -> str:
|
||||
# Include query params and relevant headers in the key
|
||||
return f"{request.url.path}?{request.url.query}"
|
||||
|
||||
async def dispatch(self, request: Request, call_next):
|
||||
if request.method != "GET":
|
||||
return await call_next(request)
|
||||
|
||||
key = self._cache_key(request)
|
||||
entry = self.cache.get(key)
|
||||
client_etag = request.headers.get("if-none-match")
|
||||
|
||||
# Cache hit + not expired
|
||||
if entry and time.time() < entry["expires"]:
|
||||
if client_etag == entry["etag"]:
|
||||
return Response(status_code=304, headers={"ETag": entry["etag"]})
|
||||
|
||||
# Client has stale ETag - return fresh cached body
|
||||
return Response(
|
||||
content=entry["body"],
|
||||
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()}"'
|
||||
|
||||
self.cache[key] = {
|
||||
"body": body,
|
||||
"etag": etag,
|
||||
"expires": time.time() + self.ttl
|
||||
}
|
||||
return Response(
|
||||
content=body,
|
||||
status_code=response.status_code,
|
||||
media_type="application/json",
|
||||
headers={"ETag": etag, "Cache-Control": f"max-age={self.ttl}"}
|
||||
)
|
||||
@@ -1,128 +1 @@
|
||||
# coding: utf-8
|
||||
|
||||
# flake8: noqa
|
||||
"""
|
||||
OpenAlex API
|
||||
|
||||
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Contact: support@openalex.org
|
||||
Generated by OpenAPI Generator (https://openapi-generator.tech)
|
||||
|
||||
Do not edit the class manually.
|
||||
""" # noqa: E501
|
||||
|
||||
# import models into model package
|
||||
from inse.models.author import Author
|
||||
from inse.models.author_affiliations_inner import AuthorAffiliationsInner
|
||||
from inse.models.author_counts_by_year_inner import AuthorCountsByYearInner
|
||||
from inse.models.author_ids import AuthorIds
|
||||
from inse.models.author_parsed_longest_name import AuthorParsedLongestName
|
||||
from inse.models.author_summary_stats import AuthorSummaryStats
|
||||
from inse.models.author_topics_inner import AuthorTopicsInner
|
||||
from inse.models.authors_list_response import AuthorsListResponse
|
||||
from inse.models.authorship import Authorship
|
||||
from inse.models.autocomplete_response import AutocompleteResponse
|
||||
from inse.models.autocomplete_response_meta import AutocompleteResponseMeta
|
||||
from inse.models.autocomplete_response_results_inner import AutocompleteResponseResultsInner
|
||||
from inse.models.award import Award
|
||||
from inse.models.award_full import AwardFull
|
||||
from inse.models.award_full_funder import AwardFullFunder
|
||||
from inse.models.awards_list_response import AwardsListResponse
|
||||
from inse.models.concept import Concept
|
||||
from inse.models.concept_ids import ConceptIds
|
||||
from inse.models.concepts_list_response import ConceptsListResponse
|
||||
from inse.models.continent import Continent
|
||||
from inse.models.continent_ids import ContinentIds
|
||||
from inse.models.continents_list_response import ContinentsListResponse
|
||||
from inse.models.countries_list_response import CountriesListResponse
|
||||
from inse.models.country import Country
|
||||
from inse.models.country_continent import CountryContinent
|
||||
from inse.models.country_ids import CountryIds
|
||||
from inse.models.dehydrated_author import DehydratedAuthor
|
||||
from inse.models.dehydrated_funder import DehydratedFunder
|
||||
from inse.models.dehydrated_institution import DehydratedInstitution
|
||||
from inse.models.dehydrated_source import DehydratedSource
|
||||
from inse.models.domain import Domain
|
||||
from inse.models.domain_fields_inner import DomainFieldsInner
|
||||
from inse.models.domain_ids import DomainIds
|
||||
from inse.models.domains_list_response import DomainsListResponse
|
||||
from inse.models.error import Error
|
||||
from inse.models.fields_list_response import FieldsListResponse
|
||||
from inse.models.funder import Funder
|
||||
from inse.models.funder_ids import FunderIds
|
||||
from inse.models.funders_list_response import FundersListResponse
|
||||
from inse.models.get_changefile200_response import GetChangefile200Response
|
||||
from inse.models.get_changefile200_response_meta import GetChangefile200ResponseMeta
|
||||
from inse.models.get_changefile200_response_results_inner import GetChangefile200ResponseResultsInner
|
||||
from inse.models.get_changefile200_response_results_inner_formats import GetChangefile200ResponseResultsInnerFormats
|
||||
from inse.models.get_changefile200_response_results_inner_formats_jsonl import GetChangefile200ResponseResultsInnerFormatsJsonl
|
||||
from inse.models.get_changefile200_response_results_inner_formats_parquet import GetChangefile200ResponseResultsInnerFormatsParquet
|
||||
from inse.models.group_by_result import GroupByResult
|
||||
from inse.models.institution import Institution
|
||||
from inse.models.institution_geo import InstitutionGeo
|
||||
from inse.models.institution_ids import InstitutionIds
|
||||
from inse.models.institution_type import InstitutionType
|
||||
from inse.models.institution_types_list_response import InstitutionTypesListResponse
|
||||
from inse.models.institutions_list_response import InstitutionsListResponse
|
||||
from inse.models.keyword import Keyword
|
||||
from inse.models.keywords_list_response import KeywordsListResponse
|
||||
from inse.models.language import Language
|
||||
from inse.models.languages_list_response import LanguagesListResponse
|
||||
from inse.models.license import License
|
||||
from inse.models.licenses_list_response import LicensesListResponse
|
||||
from inse.models.list_changefiles200_response import ListChangefiles200Response
|
||||
from inse.models.list_changefiles200_response_meta import ListChangefiles200ResponseMeta
|
||||
from inse.models.list_changefiles200_response_results_inner import ListChangefiles200ResponseResultsInner
|
||||
from inse.models.location import Location
|
||||
from inse.models.meta import Meta
|
||||
from inse.models.model_field import ModelField
|
||||
from inse.models.open_access import OpenAccess
|
||||
from inse.models.publisher import Publisher
|
||||
from inse.models.publisher_ids import PublisherIds
|
||||
from inse.models.publisher_parent_publisher import PublisherParentPublisher
|
||||
from inse.models.publishers_list_response import PublishersListResponse
|
||||
from inse.models.rate_limit_response import RateLimitResponse
|
||||
from inse.models.rate_limit_response_rate_limit import RateLimitResponseRateLimit
|
||||
from inse.models.rate_limit_response_rate_limit_endpoint_costs_usd import RateLimitResponseRateLimitEndpointCostsUsd
|
||||
from inse.models.sdg import Sdg
|
||||
from inse.models.sdg_ids import SdgIds
|
||||
from inse.models.sdgs_list_response import SdgsListResponse
|
||||
from inse.models.source import Source
|
||||
from inse.models.source_ids import SourceIds
|
||||
from inse.models.source_type import SourceType
|
||||
from inse.models.source_types_list_response import SourceTypesListResponse
|
||||
from inse.models.sources_list_response import SourcesListResponse
|
||||
from inse.models.subfield import Subfield
|
||||
from inse.models.subfield_domain import SubfieldDomain
|
||||
from inse.models.subfield_field import SubfieldField
|
||||
from inse.models.subfields_list_response import SubfieldsListResponse
|
||||
from inse.models.text_classification_response import TextClassificationResponse
|
||||
from inse.models.text_classification_response_meta import TextClassificationResponseMeta
|
||||
from inse.models.topic import Topic
|
||||
from inse.models.topic_domain import TopicDomain
|
||||
from inse.models.topic_field import TopicField
|
||||
from inse.models.topic_ids import TopicIds
|
||||
from inse.models.topic_subfield import TopicSubfield
|
||||
from inse.models.topics_list_response import TopicsListResponse
|
||||
from inse.models.work import Work
|
||||
from inse.models.work_biblio import WorkBiblio
|
||||
from inse.models.work_citation_normalized_percentile import WorkCitationNormalizedPercentile
|
||||
from inse.models.work_cited_by_percentile_year import WorkCitedByPercentileYear
|
||||
from inse.models.work_counts_by_year_inner import WorkCountsByYearInner
|
||||
from inse.models.work_has_content import WorkHasContent
|
||||
from inse.models.work_ids import WorkIds
|
||||
from inse.models.work_keyword import WorkKeyword
|
||||
from inse.models.work_mesh_inner import WorkMeshInner
|
||||
from inse.models.work_sustainable_development_goals_inner import WorkSustainableDevelopmentGoalsInner
|
||||
from inse.models.work_topic import WorkTopic
|
||||
from inse.models.work_topic_domain import WorkTopicDomain
|
||||
from inse.models.work_topic_field import WorkTopicField
|
||||
from inse.models.work_topic_subfield import WorkTopicSubfield
|
||||
from inse.models.work_type import WorkType
|
||||
from inse.models.work_types_list_response import WorkTypesListResponse
|
||||
from inse.models.works_list_response import WorksListResponse
|
||||
from inse.models.work_page import WorkPage
|
||||
|
||||
from inse.models.lsf_person import LsfPerson
|
||||
# empty package marker
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
from datetime import datetime, date
|
||||
from typing import Annotated, Optional
|
||||
|
||||
from pydantic import BaseModel, BeforeValidator, ConfigDict, Field
|
||||
|
||||
|
||||
def parse_german_date(value: Optional[str]) -> Optional[date]:
|
||||
if value is None or isinstance(value, date):
|
||||
return value
|
||||
|
||||
return datetime.strptime(value, "%d.%m.%Y").date()
|
||||
|
||||
|
||||
class BundProject(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
populate_by_name=True,
|
||||
extra="ignore",
|
||||
)
|
||||
|
||||
funding_code: Optional[str] = Field(
|
||||
default=None,
|
||||
validation_alias="Förderkennzeichen",
|
||||
description="The funding code of the project",
|
||||
examples=["19F2266G"],
|
||||
)
|
||||
|
||||
department: Optional[str] = Field(
|
||||
default=None,
|
||||
validation_alias="Ressort",
|
||||
description="The department of the project",
|
||||
examples=["BMDV"],
|
||||
)
|
||||
|
||||
department_fullname: Optional[str] = Field(
|
||||
default=None,
|
||||
validation_alias="Ressort_fullname",
|
||||
description="The full name of the department of the project",
|
||||
examples=["Bundesministerium für Digitales und Verkehr"],
|
||||
)
|
||||
|
||||
referat: Optional[str] = Field(
|
||||
default=None,
|
||||
validation_alias="Referat",
|
||||
description="The referat of the project",
|
||||
examples=["DP20"],
|
||||
)
|
||||
|
||||
project_sponsor: Optional[str] = Field(
|
||||
default=None,
|
||||
validation_alias="Projektträger",
|
||||
description="The project sponsor of the project",
|
||||
examples=["PT-TÜV"],
|
||||
)
|
||||
|
||||
project_sponsor_fullname: Optional[str] = Field(
|
||||
default=None,
|
||||
validation_alias="Projektträger_fullname",
|
||||
description="The full name of the project sponsor of the project",
|
||||
examples=["Projektträger TÜV Rheinland"],
|
||||
)
|
||||
|
||||
work_unit: Optional[str] = Field(
|
||||
default=None,
|
||||
validation_alias="Arb.-Einh.",
|
||||
description="The work unit of the project",
|
||||
examples=["mFUND"],
|
||||
)
|
||||
|
||||
recipient: Optional[str] = Field(
|
||||
default=None,
|
||||
validation_alias="Zuwendungsempfänger",
|
||||
description="The recipient of the project",
|
||||
examples=["Universität Duisburg-Essen"],
|
||||
)
|
||||
|
||||
municipal_code: Optional[str] = Field(
|
||||
default=None,
|
||||
validation_alias="Gemeindekennziffer",
|
||||
description="The municipal code of the project",
|
||||
examples=["05113000"],
|
||||
)
|
||||
|
||||
municipality: Optional[str] = Field(
|
||||
default=None,
|
||||
validation_alias="Stadt/Gemeinde",
|
||||
description="The municipality of the project",
|
||||
examples=["Essen"],
|
||||
)
|
||||
|
||||
place: Optional[str] = Field(
|
||||
default=None,
|
||||
validation_alias="Ort",
|
||||
description="The place of the project",
|
||||
examples=["Essen"],
|
||||
)
|
||||
|
||||
state: Optional[str] = Field(
|
||||
default=None,
|
||||
validation_alias="Bundesland",
|
||||
description="The state of the project",
|
||||
examples=["Nordrhein-Westfalen"],
|
||||
)
|
||||
|
||||
country: Optional[str] = Field(
|
||||
default=None,
|
||||
validation_alias="Staat",
|
||||
description="The country of the project",
|
||||
examples=["Deutschland"],
|
||||
)
|
||||
|
||||
implementing_agency: Optional[str] = Field(
|
||||
default=None,
|
||||
validation_alias="Ausführende Stelle",
|
||||
description="The implementing agency of the project",
|
||||
examples=[
|
||||
"Universität Duisburg-Essen - Fachbereich Allgemeine Informatik - Lehrstuhl Networked Embedded Systems (NES)"
|
||||
],
|
||||
)
|
||||
|
||||
topic: Optional[str] = Field(
|
||||
default=None,
|
||||
validation_alias="Thema",
|
||||
description="The topic of the project",
|
||||
examples=[
|
||||
"Verbundprojekt: Multimodaler Mobilitäts-Index - Moby_Dex -, Teilvorhaben: Universität Duisburg-Essen"
|
||||
],
|
||||
)
|
||||
|
||||
performance_plan_system: Optional[str] = Field(
|
||||
default=None,
|
||||
validation_alias="Leistungsplansystematik",
|
||||
description="The performance plan system of the project",
|
||||
examples=["GA6011"],
|
||||
)
|
||||
|
||||
performance_plan_system_text: Optional[str] = Field(
|
||||
default=None,
|
||||
validation_alias="Klartext Leistungsplansystematik",
|
||||
description="The performance plan system text of the project",
|
||||
examples=["Angewandte Forschung und Experimentelle Entwicklung"],
|
||||
)
|
||||
|
||||
funding_start: Annotated[
|
||||
Optional[date],
|
||||
Field(
|
||||
default=None,
|
||||
validation_alias="Förderbeginn",
|
||||
description="The funding start date of the project",
|
||||
examples=["01.09.2023"],
|
||||
),
|
||||
BeforeValidator(parse_german_date),
|
||||
]
|
||||
|
||||
funding_end: Annotated[
|
||||
Optional[date],
|
||||
Field(
|
||||
default=None,
|
||||
validation_alias="Förderende",
|
||||
description="The funding end date of the project",
|
||||
examples=["31.08.2026"],
|
||||
),
|
||||
BeforeValidator(parse_german_date),
|
||||
]
|
||||
|
||||
grant_amount: Optional[float] = Field(
|
||||
default=None,
|
||||
validation_alias="Fördersumme",
|
||||
description="The grant amount of the project",
|
||||
examples=[367651.00],
|
||||
)
|
||||
|
||||
funding_profile: Optional[str] = Field(
|
||||
default=None,
|
||||
validation_alias="Förderprofil",
|
||||
description="The funding profile of the project",
|
||||
examples=["Technologie- und Innovationsförderung"],
|
||||
)
|
||||
|
||||
joint_project: Optional[str] = Field(
|
||||
default=None,
|
||||
validation_alias="Verbundprojekt",
|
||||
description="Whether the project is a joint project",
|
||||
examples=["Moby_Dex"],
|
||||
)
|
||||
|
||||
funding_type: Optional[str] = Field(
|
||||
default=None,
|
||||
validation_alias="Förderart",
|
||||
description="The funding type of the project",
|
||||
examples=["PDIR"],
|
||||
)
|
||||
|
||||
publication_date: Optional[str] = Field(
|
||||
default=None,
|
||||
validation_alias="Publikationsdatum",
|
||||
description="The publication date of the project",
|
||||
examples=["2023"],
|
||||
)
|
||||
|
||||
unix_timestamp: Optional[int] = Field(
|
||||
default=None,
|
||||
validation_alias="Unix-Timestamp",
|
||||
description="The unix timestamp of the project",
|
||||
examples=[1737411518],
|
||||
)
|
||||
|
||||
date: Optional[str] = Field(
|
||||
default=None,
|
||||
validation_alias="datum",
|
||||
description="The date of the project",
|
||||
examples=["20.01.2025"],
|
||||
)
|
||||
|
||||
new: Optional[bool] = Field(
|
||||
default=None,
|
||||
validation_alias="neu",
|
||||
description="Whether the project is new",
|
||||
examples=[False],
|
||||
)
|
||||
|
||||
duration: Optional[str] = Field(
|
||||
default=None,
|
||||
validation_alias="Laufzeit",
|
||||
description="The duration of the project",
|
||||
examples=["von 01.09.2023 bis 31.08.2026"],
|
||||
)
|
||||
@@ -0,0 +1,94 @@
|
||||
from datetime import date
|
||||
from typing import Optional, Set
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class DfgProject(BaseModel):
|
||||
id: str = Field(description="The ID of the DFG project")
|
||||
link: str = Field(description="The link to the DFG project")
|
||||
title: str = Field(description="The title of the DFG project")
|
||||
description: str = Field(description="The description of the DFG project")
|
||||
|
||||
project_identifier: str = Field(
|
||||
description="The project identifier of the DFG project"
|
||||
)
|
||||
|
||||
funding_start_date: str = Field(
|
||||
description="The funding start date of the DFG project"
|
||||
)
|
||||
funding_end_date: str = Field(description="The funding end date of the DFG project")
|
||||
|
||||
associated_persons: list[str] = Field(
|
||||
description="The associated persons of the DFG project"
|
||||
)
|
||||
|
||||
institutions: list[str] = Field(
|
||||
description="The institutions associated with the DFG project"
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def from_elastic_hit(cls, hit: dict):
|
||||
source = hit["_source"]
|
||||
|
||||
associated_persons: Set[str] = set()
|
||||
institutions: Set[str] = set()
|
||||
|
||||
# persons
|
||||
|
||||
if "Antragsteller" in source:
|
||||
associated_persons.update(source["Antragsteller"].split(";"))
|
||||
|
||||
if "Antragstellerin" in source:
|
||||
associated_persons.add(source["Antragstellerin"])
|
||||
|
||||
if "Sprecher" in source:
|
||||
associated_persons.add(source["Sprecher"])
|
||||
|
||||
if "Sprecherin" in source:
|
||||
associated_persons.add(source["Sprecherin"])
|
||||
|
||||
if "Leiter" in source:
|
||||
associated_persons.add(source["Leiter"])
|
||||
|
||||
if "Leiterin" in source:
|
||||
associated_persons.add(source["Leiterin"])
|
||||
|
||||
if "beteiligte Wissenschaftlerinnen / beteiligte Wissenschaftler" in source:
|
||||
associated_persons.update(
|
||||
source[
|
||||
"beteiligte Wissenschaftlerinnen / beteiligte Wissenschaftler"
|
||||
].split(";")
|
||||
)
|
||||
|
||||
if "Beteiligte Personen" in source:
|
||||
associated_persons.update(source["Beteiligte Personen"].split(";"))
|
||||
|
||||
if "Teilprojektleiter" in source:
|
||||
associated_persons.update(source["Teilprojektleiter"].split(";"))
|
||||
|
||||
# institutions
|
||||
|
||||
if "Antragstellende Institution" in source:
|
||||
institutions.add(source["Antragstellende Institution"])
|
||||
|
||||
if "Mitantragstellende Institution" in source:
|
||||
institutions.add(source["Mitantragstellende Institution"])
|
||||
|
||||
if "Beteiligte Institution" in source:
|
||||
institutions.add(source["Beteiligte Institution"])
|
||||
|
||||
if "Beteiligte Hochschule" in source:
|
||||
institutions.add(source["Beteiligte Hochschule"])
|
||||
|
||||
return cls(
|
||||
id=hit["_id"],
|
||||
link=source["link"],
|
||||
title=source["title"],
|
||||
description=source["description"],
|
||||
project_identifier=source["Projektkennzeichen"],
|
||||
funding_start_date=source["funding_start"],
|
||||
funding_end_date=source["funding_end"],
|
||||
associated_persons=list(associated_persons),
|
||||
institutions=list(institutions),
|
||||
)
|
||||
@@ -0,0 +1,192 @@
|
||||
from typing import List, Optional
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
|
||||
class DisplayCodeSplittedNested(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
single_display_code: Optional[str] = Field(
|
||||
default=None,
|
||||
validation_alias="singleDisplayCode",
|
||||
description="A solitary segment or specific component broken out from the main display code.",
|
||||
)
|
||||
|
||||
|
||||
class CategoryNested(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
category: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The descriptive classification title or taxonomy name for the project.",
|
||||
)
|
||||
code: Optional[str] = Field(
|
||||
default=None, description="The system code representing the specific category."
|
||||
)
|
||||
display_code: Optional[str] = Field(
|
||||
default=None,
|
||||
validation_alias="displayCode",
|
||||
description="The alphanumeric code formatted for user interface display purposes.",
|
||||
)
|
||||
# REFINED: Mapped to List[str] because the real data provides an array of strings
|
||||
display_code_splitted: List[str] = Field(
|
||||
default_factory=list,
|
||||
validation_alias="displayCode_splitted",
|
||||
description="A tokenized hierarchy breakdown of the display code represented as an array of strings.",
|
||||
)
|
||||
display_code_splitted_nested: List[DisplayCodeSplittedNested] = Field(
|
||||
default_factory=list,
|
||||
validation_alias="displayCode_splitted_nested",
|
||||
description="Granular, nested breakdowns of the split parts of the display code.",
|
||||
)
|
||||
|
||||
|
||||
class KeywordNested(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
keyword: Optional[str] = Field(
|
||||
default=None,
|
||||
description="An individual standalone keyword or tag used for granular search index filtering.",
|
||||
)
|
||||
|
||||
|
||||
class OrganizationNested(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
ec_contribution: Optional[str] = Field(
|
||||
default=None,
|
||||
validation_alias="ecContribution",
|
||||
description="The gross European Commission financial contribution allocated to this specific participant organization.",
|
||||
)
|
||||
id: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The unique identifier or Participant Identification Code (PIC) of the organization.",
|
||||
)
|
||||
name: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The full legal name of the participating organization or institution.",
|
||||
)
|
||||
net_ec_contribution: Optional[str] = Field(
|
||||
default=None,
|
||||
validation_alias="netEcContribution",
|
||||
description="The net European Commission financial funding provided to the organization after adjustments.",
|
||||
)
|
||||
total_cost: Optional[str] = Field(
|
||||
default=None,
|
||||
validation_alias="totalCost",
|
||||
description="The overall individual budget or total cost declared by this organization for its share of work.",
|
||||
)
|
||||
organization_type: Optional[str] = Field(
|
||||
default=None,
|
||||
validation_alias="type",
|
||||
description="The legal entity type or role of the organization (e.g., coordinator, participant).",
|
||||
)
|
||||
|
||||
|
||||
class ProgrammeNested(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
code: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The structural code identifying the framework or specific funding sub-programme.",
|
||||
)
|
||||
id: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The unique identifier of the funding program within the registry.",
|
||||
)
|
||||
programme: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The official title or description of the EU funding program.",
|
||||
)
|
||||
|
||||
|
||||
class EuProject(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
acronym: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The official, short acronym chosen to identify the EU project.",
|
||||
)
|
||||
categories_nested: List[CategoryNested] = Field(
|
||||
default_factory=list,
|
||||
description="Structured lists of classification categories and taxonomy mappings assigned to the project.",
|
||||
)
|
||||
doc_number: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The internal administrative document control number or record tracking identifier.",
|
||||
)
|
||||
doi: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The Digital Object Identifier (DOI) linked to the project's official metadata or primary publication.",
|
||||
)
|
||||
ec_max_contribution: Optional[str] = Field(
|
||||
default=None,
|
||||
validation_alias="ecMaxContribution",
|
||||
description="The maximum authorized limit for the European Commission's financial grant contribution to the project.",
|
||||
)
|
||||
end_date: Optional[str] = Field(
|
||||
default=None,
|
||||
validation_alias="endDate",
|
||||
description="The calendar date marking the official structural conclusion of the project execution timeline.",
|
||||
)
|
||||
funding_end: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The exact calendar termination year for the project's financial eligibility period.",
|
||||
)
|
||||
funding_start: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The exact calendar activation year from which project expenses can be billed against the grant.",
|
||||
)
|
||||
id: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The unique global record ID for the project document (typically the Grant Agreement Number).",
|
||||
)
|
||||
keywords: Optional[str] = Field(
|
||||
default=None,
|
||||
description="A general text string or comma-separated list of keywords applied to the project record.",
|
||||
)
|
||||
keywords_nested: List[KeywordNested] = Field(
|
||||
default_factory=list,
|
||||
description="Strictly tokenized and isolated keywords nested for targeted search engine aggregations.",
|
||||
)
|
||||
link: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The web URL linking directly to the project's public profile page on CORDIS or an equivalent registry.",
|
||||
)
|
||||
objective: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The complete, detailed abstract outlining the goals, methodology, and expected impact of the project.",
|
||||
)
|
||||
organization_nested: List[OrganizationNested] = Field(
|
||||
default_factory=list,
|
||||
description="The full roster of academic, public, or private organizations participating in the project consortium.",
|
||||
)
|
||||
programme_nested: List[ProgrammeNested] = Field(
|
||||
default_factory=list,
|
||||
description="The nested historical line of EU funding frameworks and structural grants supporting this project.",
|
||||
)
|
||||
source: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The specific upstream system or database repository from which this document was fetched or synced.",
|
||||
)
|
||||
start_date: Optional[str] = Field(
|
||||
default=None,
|
||||
validation_alias="startDate",
|
||||
description="The official calendar date marking the active kickoff and formal initiation of the project.",
|
||||
)
|
||||
status: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The lifecycle phase of the project (e.g., 'CLOSED', 'ONGOING').",
|
||||
)
|
||||
teaser: Optional[str] = Field(
|
||||
default=None,
|
||||
description="A brief, high-level summary or editorial sentence written for general public consumption.",
|
||||
)
|
||||
title: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The comprehensive, full legal title describing the scope of the project.",
|
||||
)
|
||||
total_cost: Optional[str] = Field(
|
||||
default=None,
|
||||
validation_alias="totalCost",
|
||||
description="The combined sum total budget estimated for the implementation of the entire project.",
|
||||
)
|
||||
@@ -0,0 +1,132 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
Aktuell Index Backend Models
|
||||
|
||||
Pydantic models for the Elasticsearch \"aktuell\" index.
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by OpenAPI Generator (https://openapi-generator.tech)
|
||||
|
||||
Do not edit the class manually.
|
||||
""" # noqa: E501
|
||||
|
||||
|
||||
from __future__ import annotations
|
||||
import pprint
|
||||
import re # noqa: F401
|
||||
import json
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from inse.models.news_aktuell.link_item import LinkItem
|
||||
from inse.models.news_aktuell.tag_item import TagItem
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
|
||||
class Aktuell(BaseModel):
|
||||
"""
|
||||
Main document model for the aktuell index.
|
||||
""" # noqa: E501
|
||||
author: Optional[StrictStr] = None
|
||||
var_date: Optional[StrictStr] = Field(default=None, alias="date")
|
||||
date_full: Optional[StrictInt] = None
|
||||
date_year: Optional[StrictInt] = None
|
||||
full_content: Optional[StrictStr] = None
|
||||
further_content: Optional[StrictStr] = None
|
||||
intro_content: Optional[StrictStr] = None
|
||||
links_nested: Optional[List[LinkItem]] = None
|
||||
main_content: Optional[StrictStr] = None
|
||||
maintitle: Optional[StrictStr] = None
|
||||
redaktion: Optional[StrictStr] = None
|
||||
subtitle: Optional[StrictStr] = None
|
||||
tags: Optional[StrictStr] = None
|
||||
tags_nested: Optional[List[TagItem]] = None
|
||||
url: Optional[StrictStr] = None
|
||||
__properties: ClassVar[List[str]] = ["author", "date", "date_full", "date_year", "full_content", "further_content", "intro_content", "links_nested", "main_content", "maintitle", "redaktion", "subtitle", "tags", "tags_nested", "url"]
|
||||
|
||||
model_config = ConfigDict(
|
||||
validate_by_name=True,
|
||||
validate_by_alias=True,
|
||||
validate_assignment=True,
|
||||
protected_namespaces=(),
|
||||
)
|
||||
|
||||
|
||||
def to_str(self) -> str:
|
||||
"""Returns the string representation of the model using alias"""
|
||||
return pprint.pformat(self.model_dump(by_alias=True))
|
||||
|
||||
def to_json(self) -> str:
|
||||
"""Returns the JSON representation of the model using alias"""
|
||||
return json.dumps(to_jsonable_python(self.to_dict()))
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, json_str: str) -> Optional[Self]:
|
||||
"""Create an instance of Aktuell from a JSON string"""
|
||||
return cls.from_dict(json.loads(json_str))
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Return the dictionary representation of the model using alias.
|
||||
|
||||
This has the following differences from calling pydantic's
|
||||
`self.model_dump(by_alias=True)`:
|
||||
|
||||
* `None` is only added to the output dict for nullable fields that
|
||||
were set at model initialization. Other fields with value `None`
|
||||
are ignored.
|
||||
"""
|
||||
excluded_fields: Set[str] = set([
|
||||
])
|
||||
|
||||
_dict = self.model_dump(
|
||||
by_alias=True,
|
||||
exclude=excluded_fields,
|
||||
exclude_none=True,
|
||||
)
|
||||
# override the default output from pydantic by calling `to_dict()` of each item in links_nested (list)
|
||||
_items = []
|
||||
if self.links_nested:
|
||||
for _item_links_nested in self.links_nested:
|
||||
if _item_links_nested:
|
||||
_items.append(_item_links_nested.to_dict())
|
||||
_dict['links_nested'] = _items
|
||||
# override the default output from pydantic by calling `to_dict()` of each item in tags_nested (list)
|
||||
_items = []
|
||||
if self.tags_nested:
|
||||
for _item_tags_nested in self.tags_nested:
|
||||
if _item_tags_nested:
|
||||
_items.append(_item_tags_nested.to_dict())
|
||||
_dict['tags_nested'] = _items
|
||||
return _dict
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
|
||||
"""Create an instance of Aktuell from a dict"""
|
||||
if obj is None:
|
||||
return None
|
||||
|
||||
if not isinstance(obj, dict):
|
||||
return cls.model_validate(obj)
|
||||
|
||||
_obj = cls.model_validate({
|
||||
"author": obj.get("author"),
|
||||
"date": obj.get("date"),
|
||||
"date_full": obj.get("date_full"),
|
||||
"date_year": obj.get("date_year"),
|
||||
"full_content": obj.get("full_content"),
|
||||
"further_content": obj.get("further_content"),
|
||||
"intro_content": obj.get("intro_content"),
|
||||
"links_nested": [LinkItem.from_dict(_item) for _item in obj["links_nested"]] if obj.get("links_nested") is not None else None,
|
||||
"main_content": obj.get("main_content"),
|
||||
"maintitle": obj.get("maintitle"),
|
||||
"redaktion": obj.get("redaktion"),
|
||||
"subtitle": obj.get("subtitle"),
|
||||
"tags": obj.get("tags"),
|
||||
"tags_nested": [TagItem.from_dict(_item) for _item in obj["tags_nested"]] if obj.get("tags_nested") is not None else None,
|
||||
"url": obj.get("url")
|
||||
})
|
||||
return _obj
|
||||
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
Aktuell Index Backend Models
|
||||
|
||||
Pydantic models for the Elasticsearch \"aktuell\" index.
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by OpenAPI Generator (https://openapi-generator.tech)
|
||||
|
||||
Do not edit the class manually.
|
||||
""" # noqa: E501
|
||||
|
||||
|
||||
from __future__ import annotations
|
||||
import pprint
|
||||
import re # noqa: F401
|
||||
import json
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, StrictStr
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
|
||||
class LinkItem(BaseModel):
|
||||
"""
|
||||
Nested link object within the Aktuell document.
|
||||
""" # noqa: E501
|
||||
text: Optional[StrictStr] = None
|
||||
url: Optional[StrictStr] = None
|
||||
__properties: ClassVar[List[str]] = ["text", "url"]
|
||||
|
||||
model_config = ConfigDict(
|
||||
validate_by_name=True,
|
||||
validate_by_alias=True,
|
||||
validate_assignment=True,
|
||||
protected_namespaces=(),
|
||||
)
|
||||
|
||||
|
||||
def to_str(self) -> str:
|
||||
"""Returns the string representation of the model using alias"""
|
||||
return pprint.pformat(self.model_dump(by_alias=True))
|
||||
|
||||
def to_json(self) -> str:
|
||||
"""Returns the JSON representation of the model using alias"""
|
||||
return json.dumps(to_jsonable_python(self.to_dict()))
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, json_str: str) -> Optional[Self]:
|
||||
"""Create an instance of LinkItem from a JSON string"""
|
||||
return cls.from_dict(json.loads(json_str))
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Return the dictionary representation of the model using alias.
|
||||
|
||||
This has the following differences from calling pydantic's
|
||||
`self.model_dump(by_alias=True)`:
|
||||
|
||||
* `None` is only added to the output dict for nullable fields that
|
||||
were set at model initialization. Other fields with value `None`
|
||||
are ignored.
|
||||
"""
|
||||
excluded_fields: Set[str] = set([
|
||||
])
|
||||
|
||||
_dict = self.model_dump(
|
||||
by_alias=True,
|
||||
exclude=excluded_fields,
|
||||
exclude_none=True,
|
||||
)
|
||||
return _dict
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
|
||||
"""Create an instance of LinkItem from a dict"""
|
||||
if obj is None:
|
||||
return None
|
||||
|
||||
if not isinstance(obj, dict):
|
||||
return cls.model_validate(obj)
|
||||
|
||||
_obj = cls.model_validate({
|
||||
"text": obj.get("text"),
|
||||
"url": obj.get("url")
|
||||
})
|
||||
return _obj
|
||||
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
Aktuell Index Backend Models
|
||||
|
||||
Pydantic models for the Elasticsearch \"aktuell\" index.
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by OpenAPI Generator (https://openapi-generator.tech)
|
||||
|
||||
Do not edit the class manually.
|
||||
""" # noqa: E501
|
||||
|
||||
|
||||
from __future__ import annotations
|
||||
import pprint
|
||||
import re # noqa: F401
|
||||
import json
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, StrictStr
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
|
||||
class TagItem(BaseModel):
|
||||
"""
|
||||
Nested tag object within the Aktuell document.
|
||||
""" # noqa: E501
|
||||
tag: Optional[StrictStr] = None
|
||||
__properties: ClassVar[List[str]] = ["tag"]
|
||||
|
||||
model_config = ConfigDict(
|
||||
validate_by_name=True,
|
||||
validate_by_alias=True,
|
||||
validate_assignment=True,
|
||||
protected_namespaces=(),
|
||||
)
|
||||
|
||||
|
||||
def to_str(self) -> str:
|
||||
"""Returns the string representation of the model using alias"""
|
||||
return pprint.pformat(self.model_dump(by_alias=True))
|
||||
|
||||
def to_json(self) -> str:
|
||||
"""Returns the JSON representation of the model using alias"""
|
||||
return json.dumps(to_jsonable_python(self.to_dict()))
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, json_str: str) -> Optional[Self]:
|
||||
"""Create an instance of TagItem from a JSON string"""
|
||||
return cls.from_dict(json.loads(json_str))
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Return the dictionary representation of the model using alias.
|
||||
|
||||
This has the following differences from calling pydantic's
|
||||
`self.model_dump(by_alias=True)`:
|
||||
|
||||
* `None` is only added to the output dict for nullable fields that
|
||||
were set at model initialization. Other fields with value `None`
|
||||
are ignored.
|
||||
"""
|
||||
excluded_fields: Set[str] = set([
|
||||
])
|
||||
|
||||
_dict = self.model_dump(
|
||||
by_alias=True,
|
||||
exclude=excluded_fields,
|
||||
exclude_none=True,
|
||||
)
|
||||
return _dict
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
|
||||
"""Create an instance of TagItem from a dict"""
|
||||
if obj is None:
|
||||
return None
|
||||
|
||||
if not isinstance(obj, dict):
|
||||
return cls.model_validate(obj)
|
||||
|
||||
_obj = cls.model_validate({
|
||||
"tag": obj.get("tag")
|
||||
})
|
||||
return _obj
|
||||
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
# coding: utf-8
|
||||
|
||||
# flake8: noqa
|
||||
"""
|
||||
OpenAlex API
|
||||
|
||||
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Contact: support@openalex.org
|
||||
Generated by OpenAPI Generator (https://openapi-generator.tech)
|
||||
|
||||
Do not edit the class manually.
|
||||
""" # noqa: E501
|
||||
|
||||
# import models into model package
|
||||
from inse.models.openalex.author import Author
|
||||
from inse.models.openalex.author_affiliations_inner import AuthorAffiliationsInner
|
||||
from inse.models.openalex.author_counts_by_year_inner import AuthorCountsByYearInner
|
||||
from inse.models.openalex.author_ids import AuthorIds
|
||||
from inse.models.openalex.author_parsed_longest_name import AuthorParsedLongestName
|
||||
from inse.models.openalex.author_summary_stats import AuthorSummaryStats
|
||||
from inse.models.openalex.author_topics_inner import AuthorTopicsInner
|
||||
from inse.models.openalex.authors_list_response import AuthorsListResponse
|
||||
from inse.models.openalex.authorship import Authorship
|
||||
from inse.models.openalex.autocomplete_response import AutocompleteResponse
|
||||
from inse.models.openalex.autocomplete_response_meta import AutocompleteResponseMeta
|
||||
from inse.models.openalex.autocomplete_response_results_inner import AutocompleteResponseResultsInner
|
||||
from inse.models.openalex.award import Award
|
||||
from inse.models.openalex.award_full import AwardFull
|
||||
from inse.models.openalex.award_full_funder import AwardFullFunder
|
||||
from inse.models.openalex.awards_list_response import AwardsListResponse
|
||||
from inse.models.openalex.concept import Concept
|
||||
from inse.models.openalex.concept_ids import ConceptIds
|
||||
from inse.models.openalex.concepts_list_response import ConceptsListResponse
|
||||
from inse.models.openalex.continent import Continent
|
||||
from inse.models.openalex.continent_ids import ContinentIds
|
||||
from inse.models.openalex.continents_list_response import ContinentsListResponse
|
||||
from inse.models.openalex.countries_list_response import CountriesListResponse
|
||||
from inse.models.openalex.country import Country
|
||||
from inse.models.openalex.country_continent import CountryContinent
|
||||
from inse.models.openalex.country_ids import CountryIds
|
||||
from inse.models.openalex.dehydrated_author import DehydratedAuthor
|
||||
from inse.models.openalex.dehydrated_funder import DehydratedFunder
|
||||
from inse.models.openalex.dehydrated_institution import DehydratedInstitution
|
||||
from inse.models.openalex.dehydrated_source import DehydratedSource
|
||||
from inse.models.openalex.domain import Domain
|
||||
from inse.models.openalex.domain_fields_inner import DomainFieldsInner
|
||||
from inse.models.openalex.domain_ids import DomainIds
|
||||
from inse.models.openalex.domains_list_response import DomainsListResponse
|
||||
from inse.models.openalex.error import Error
|
||||
from inse.models.openalex.fields_list_response import FieldsListResponse
|
||||
from inse.models.openalex.funder import Funder
|
||||
from inse.models.openalex.funder_ids import FunderIds
|
||||
from inse.models.openalex.funders_list_response import FundersListResponse
|
||||
from inse.models.openalex.get_changefile200_response import GetChangefile200Response
|
||||
from inse.models.openalex.get_changefile200_response_meta import GetChangefile200ResponseMeta
|
||||
from inse.models.openalex.get_changefile200_response_results_inner import GetChangefile200ResponseResultsInner
|
||||
from inse.models.openalex.get_changefile200_response_results_inner_formats import GetChangefile200ResponseResultsInnerFormats
|
||||
from inse.models.openalex.get_changefile200_response_results_inner_formats_jsonl import GetChangefile200ResponseResultsInnerFormatsJsonl
|
||||
from inse.models.openalex.get_changefile200_response_results_inner_formats_parquet import GetChangefile200ResponseResultsInnerFormatsParquet
|
||||
from inse.models.openalex.group_by_result import GroupByResult
|
||||
from inse.models.openalex.institution import Institution
|
||||
from inse.models.openalex.institution_geo import InstitutionGeo
|
||||
from inse.models.openalex.institution_ids import InstitutionIds
|
||||
from inse.models.openalex.institution_type import InstitutionType
|
||||
from inse.models.openalex.institution_types_list_response import InstitutionTypesListResponse
|
||||
from inse.models.openalex.institutions_list_response import InstitutionsListResponse
|
||||
from inse.models.openalex.keyword import Keyword
|
||||
from inse.models.openalex.keywords_list_response import KeywordsListResponse
|
||||
from inse.models.openalex.language import Language
|
||||
from inse.models.openalex.languages_list_response import LanguagesListResponse
|
||||
from inse.models.openalex.license import License
|
||||
from inse.models.openalex.licenses_list_response import LicensesListResponse
|
||||
from inse.models.openalex.list_changefiles200_response import ListChangefiles200Response
|
||||
from inse.models.openalex.list_changefiles200_response_meta import ListChangefiles200ResponseMeta
|
||||
from inse.models.openalex.list_changefiles200_response_results_inner import ListChangefiles200ResponseResultsInner
|
||||
from inse.models.openalex.location import Location
|
||||
from inse.models.openalex.meta import Meta
|
||||
from inse.models.openalex.model_field import ModelField
|
||||
from inse.models.openalex.open_access import OpenAccess
|
||||
from inse.models.openalex.publisher import Publisher
|
||||
from inse.models.openalex.publisher_ids import PublisherIds
|
||||
from inse.models.openalex.publisher_parent_publisher import PublisherParentPublisher
|
||||
from inse.models.openalex.publishers_list_response import PublishersListResponse
|
||||
from inse.models.openalex.rate_limit_response import RateLimitResponse
|
||||
from inse.models.openalex.rate_limit_response_rate_limit import RateLimitResponseRateLimit
|
||||
from inse.models.openalex.rate_limit_response_rate_limit_endpoint_costs_usd import RateLimitResponseRateLimitEndpointCostsUsd
|
||||
from inse.models.openalex.sdg import Sdg
|
||||
from inse.models.openalex.sdg_ids import SdgIds
|
||||
from inse.models.openalex.sdgs_list_response import SdgsListResponse
|
||||
from inse.models.openalex.source import Source
|
||||
from inse.models.openalex.source_ids import SourceIds
|
||||
from inse.models.openalex.source_type import SourceType
|
||||
from inse.models.openalex.source_types_list_response import SourceTypesListResponse
|
||||
from inse.models.openalex.sources_list_response import SourcesListResponse
|
||||
from inse.models.openalex.subfield import Subfield
|
||||
from inse.models.openalex.subfield_domain import SubfieldDomain
|
||||
from inse.models.openalex.subfield_field import SubfieldField
|
||||
from inse.models.openalex.subfields_list_response import SubfieldsListResponse
|
||||
from inse.models.openalex.text_classification_response import TextClassificationResponse
|
||||
from inse.models.openalex.text_classification_response_meta import TextClassificationResponseMeta
|
||||
from inse.models.openalex.topic import Topic
|
||||
from inse.models.openalex.topic_domain import TopicDomain
|
||||
from inse.models.openalex.topic_field import TopicField
|
||||
from inse.models.openalex.topic_ids import TopicIds
|
||||
from inse.models.openalex.topic_subfield import TopicSubfield
|
||||
from inse.models.openalex.topics_list_response import TopicsListResponse
|
||||
from inse.models.openalex.work import Work
|
||||
from inse.models.openalex.work_biblio import WorkBiblio
|
||||
from inse.models.openalex.work_citation_normalized_percentile import WorkCitationNormalizedPercentile
|
||||
from inse.models.openalex.work_cited_by_percentile_year import WorkCitedByPercentileYear
|
||||
from inse.models.openalex.work_counts_by_year_inner import WorkCountsByYearInner
|
||||
from inse.models.openalex.work_has_content import WorkHasContent
|
||||
from inse.models.openalex.work_ids import WorkIds
|
||||
from inse.models.openalex.work_keyword import WorkKeyword
|
||||
from inse.models.openalex.work_mesh_inner import WorkMeshInner
|
||||
from inse.models.openalex.work_sustainable_development_goals_inner import WorkSustainableDevelopmentGoalsInner
|
||||
from inse.models.openalex.work_topic import WorkTopic
|
||||
from inse.models.openalex.work_topic_domain import WorkTopicDomain
|
||||
from inse.models.openalex.work_topic_field import WorkTopicField
|
||||
from inse.models.openalex.work_topic_subfield import WorkTopicSubfield
|
||||
from inse.models.openalex.work_type import WorkType
|
||||
from inse.models.openalex.work_types_list_response import WorkTypesListResponse
|
||||
from inse.models.openalex.works_list_response import WorksListResponse
|
||||
from inse.models.openalex.work_page import WorkPage
|
||||
|
||||
from inse.models.openalex.lsf_person import LsfPerson
|
||||
+7
-7
@@ -21,13 +21,13 @@ import json
|
||||
from datetime import date, datetime
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from inse.models.author_affiliations_inner import AuthorAffiliationsInner
|
||||
from inse.models.author_counts_by_year_inner import AuthorCountsByYearInner
|
||||
from inse.models.author_ids import AuthorIds
|
||||
from inse.models.author_parsed_longest_name import AuthorParsedLongestName
|
||||
from inse.models.author_summary_stats import AuthorSummaryStats
|
||||
from inse.models.work_topic import WorkTopic
|
||||
from inse.models.dehydrated_institution import DehydratedInstitution
|
||||
from inse.models.openalex.author_affiliations_inner import AuthorAffiliationsInner
|
||||
from inse.models.openalex.author_counts_by_year_inner import AuthorCountsByYearInner
|
||||
from inse.models.openalex.author_ids import AuthorIds
|
||||
from inse.models.openalex.author_parsed_longest_name import AuthorParsedLongestName
|
||||
from inse.models.openalex.author_summary_stats import AuthorSummaryStats
|
||||
from inse.models.openalex.work_topic import WorkTopic
|
||||
from inse.models.openalex.dehydrated_institution import DehydratedInstitution
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
+1
-1
@@ -19,7 +19,7 @@ import json
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictInt
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from inse.models.dehydrated_institution import DehydratedInstitution
|
||||
from inse.models.openalex.dehydrated_institution import DehydratedInstitution
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
+3
-3
@@ -20,9 +20,9 @@ import json
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from inse.models.author import Author
|
||||
from inse.models.group_by_result import GroupByResult
|
||||
from inse.models.meta import Meta
|
||||
from inse.models.openalex.author import Author
|
||||
from inse.models.openalex.group_by_result import GroupByResult
|
||||
from inse.models.openalex.meta import Meta
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
+2
-2
@@ -20,8 +20,8 @@ import json
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr, field_validator
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from inse.models.dehydrated_author import DehydratedAuthor
|
||||
from inse.models.dehydrated_institution import DehydratedInstitution
|
||||
from inse.models.openalex.dehydrated_author import DehydratedAuthor
|
||||
from inse.models.openalex.dehydrated_institution import DehydratedInstitution
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
+2
-2
@@ -20,8 +20,8 @@ import json
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from inse.models.autocomplete_response_meta import AutocompleteResponseMeta
|
||||
from inse.models.autocomplete_response_results_inner import AutocompleteResponseResultsInner
|
||||
from inse.models.openalex.autocomplete_response_meta import AutocompleteResponseMeta
|
||||
from inse.models.openalex.autocomplete_response_results_inner import AutocompleteResponseResultsInner
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
+1
-1
@@ -21,7 +21,7 @@ import json
|
||||
from datetime import date, datetime
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictFloat, StrictInt, StrictStr
|
||||
from typing import Any, ClassVar, Dict, List, Optional, Union
|
||||
from inse.models.award_full_funder import AwardFullFunder
|
||||
from inse.models.openalex.award_full_funder import AwardFullFunder
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
+2
-2
@@ -20,8 +20,8 @@ import json
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from inse.models.award_full import AwardFull
|
||||
from inse.models.meta import Meta
|
||||
from inse.models.openalex.award_full import AwardFull
|
||||
from inse.models.openalex.meta import Meta
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
+1
-1
@@ -21,7 +21,7 @@ import json
|
||||
from datetime import date, datetime
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from inse.models.concept_ids import ConceptIds
|
||||
from inse.models.openalex.concept_ids import ConceptIds
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
+2
-2
@@ -20,8 +20,8 @@ import json
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from inse.models.concept import Concept
|
||||
from inse.models.meta import Meta
|
||||
from inse.models.openalex.concept import Concept
|
||||
from inse.models.openalex.meta import Meta
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
+2
-2
@@ -21,8 +21,8 @@ import json
|
||||
from datetime import date, datetime
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictStr
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from inse.models.continent_ids import ContinentIds
|
||||
from inse.models.domain_fields_inner import DomainFieldsInner
|
||||
from inse.models.openalex.continent_ids import ContinentIds
|
||||
from inse.models.openalex.domain_fields_inner import DomainFieldsInner
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
+2
-2
@@ -20,8 +20,8 @@ import json
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from inse.models.continent import Continent
|
||||
from inse.models.meta import Meta
|
||||
from inse.models.openalex.continent import Continent
|
||||
from inse.models.openalex.meta import Meta
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
+2
-2
@@ -20,8 +20,8 @@ import json
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from inse.models.country import Country
|
||||
from inse.models.meta import Meta
|
||||
from inse.models.openalex.country import Country
|
||||
from inse.models.openalex.meta import Meta
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
+2
-2
@@ -21,8 +21,8 @@ import json
|
||||
from datetime import date, datetime
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from inse.models.country_continent import CountryContinent
|
||||
from inse.models.country_ids import CountryIds
|
||||
from inse.models.openalex.country_continent import CountryContinent
|
||||
from inse.models.openalex.country_ids import CountryIds
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
+2
-2
@@ -21,8 +21,8 @@ import json
|
||||
from datetime import date, datetime
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from inse.models.domain_fields_inner import DomainFieldsInner
|
||||
from inse.models.domain_ids import DomainIds
|
||||
from inse.models.openalex.domain_fields_inner import DomainFieldsInner
|
||||
from inse.models.openalex.domain_ids import DomainIds
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
+2
-2
@@ -20,8 +20,8 @@ import json
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from inse.models.domain import Domain
|
||||
from inse.models.meta import Meta
|
||||
from inse.models.openalex.domain import Domain
|
||||
from inse.models.openalex.meta import Meta
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
+2
-2
@@ -20,8 +20,8 @@ import json
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from inse.models.meta import Meta
|
||||
from inse.models.model_field import ModelField
|
||||
from inse.models.openalex.meta import Meta
|
||||
from inse.models.openalex.model_field import ModelField
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
+2
-2
@@ -21,8 +21,8 @@ import json
|
||||
from datetime import date, datetime
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from inse.models.author_counts_by_year_inner import AuthorCountsByYearInner
|
||||
from inse.models.funder_ids import FunderIds
|
||||
from inse.models.openalex.author_counts_by_year_inner import AuthorCountsByYearInner
|
||||
from inse.models.openalex.funder_ids import FunderIds
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
+3
-3
@@ -20,9 +20,9 @@ import json
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from inse.models.funder import Funder
|
||||
from inse.models.group_by_result import GroupByResult
|
||||
from inse.models.meta import Meta
|
||||
from inse.models.openalex.funder import Funder
|
||||
from inse.models.openalex.group_by_result import GroupByResult
|
||||
from inse.models.openalex.meta import Meta
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
+2
-2
@@ -20,8 +20,8 @@ import json
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from inse.models.get_changefile200_response_meta import GetChangefile200ResponseMeta
|
||||
from inse.models.get_changefile200_response_results_inner import GetChangefile200ResponseResultsInner
|
||||
from inse.models.openalex.get_changefile200_response_meta import GetChangefile200ResponseMeta
|
||||
from inse.models.openalex.get_changefile200_response_results_inner import GetChangefile200ResponseResultsInner
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
+1
-1
@@ -20,7 +20,7 @@ import json
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from inse.models.get_changefile200_response_results_inner_formats import GetChangefile200ResponseResultsInnerFormats
|
||||
from inse.models.openalex.get_changefile200_response_results_inner_formats import GetChangefile200ResponseResultsInnerFormats
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
+2
-2
@@ -20,8 +20,8 @@ import json
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from inse.models.get_changefile200_response_results_inner_formats_jsonl import GetChangefile200ResponseResultsInnerFormatsJsonl
|
||||
from inse.models.get_changefile200_response_results_inner_formats_parquet import GetChangefile200ResponseResultsInnerFormatsParquet
|
||||
from inse.models.openalex.get_changefile200_response_results_inner_formats_jsonl import GetChangefile200ResponseResultsInnerFormatsJsonl
|
||||
from inse.models.openalex.get_changefile200_response_results_inner_formats_parquet import GetChangefile200ResponseResultsInnerFormatsParquet
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
+4
-4
@@ -21,10 +21,10 @@ import json
|
||||
from datetime import date, datetime
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr, field_validator
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from inse.models.author_counts_by_year_inner import AuthorCountsByYearInner
|
||||
from inse.models.author_summary_stats import AuthorSummaryStats
|
||||
from inse.models.institution_geo import InstitutionGeo
|
||||
from inse.models.institution_ids import InstitutionIds
|
||||
from inse.models.openalex.author_counts_by_year_inner import AuthorCountsByYearInner
|
||||
from inse.models.openalex.author_summary_stats import AuthorSummaryStats
|
||||
from inse.models.openalex.institution_geo import InstitutionGeo
|
||||
from inse.models.openalex.institution_ids import InstitutionIds
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
+2
-2
@@ -20,8 +20,8 @@ import json
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from inse.models.institution_type import InstitutionType
|
||||
from inse.models.meta import Meta
|
||||
from inse.models.openalex.institution_type import InstitutionType
|
||||
from inse.models.openalex.meta import Meta
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
+3
-3
@@ -20,9 +20,9 @@ import json
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from inse.models.group_by_result import GroupByResult
|
||||
from inse.models.institution import Institution
|
||||
from inse.models.meta import Meta
|
||||
from inse.models.openalex.group_by_result import GroupByResult
|
||||
from inse.models.openalex.institution import Institution
|
||||
from inse.models.openalex.meta import Meta
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
+3
-3
@@ -20,9 +20,9 @@ import json
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from inse.models.group_by_result import GroupByResult
|
||||
from inse.models.keyword import Keyword
|
||||
from inse.models.meta import Meta
|
||||
from inse.models.openalex.group_by_result import GroupByResult
|
||||
from inse.models.openalex.keyword import Keyword
|
||||
from inse.models.openalex.meta import Meta
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
+2
-2
@@ -20,8 +20,8 @@ import json
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from inse.models.language import Language
|
||||
from inse.models.meta import Meta
|
||||
from inse.models.openalex.language import Language
|
||||
from inse.models.openalex.meta import Meta
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
+2
-2
@@ -20,8 +20,8 @@ import json
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from inse.models.license import License
|
||||
from inse.models.meta import Meta
|
||||
from inse.models.openalex.license import License
|
||||
from inse.models.openalex.meta import Meta
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user