fix: resolve merge conflict with dev in person-funding.component.ts
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
LocationBasedServices/smartguide/pipeline/head This commit looks good

This commit is contained in:
2026-07-28 15:35:09 +02:00
790 changed files with 215781 additions and 26841 deletions
+15
View File
@@ -0,0 +1,15 @@
*
!background-jobs
!service
service/*
!service/scripts
# Data-only folders that do not belong in the job image.
service/scripts/multipliers
**/__pycache__
**/*.pyc
**/.venv
**/.env
**/.env.*
**/out
+5
View File
@@ -0,0 +1,5 @@
.env
.env.*
__pycache__/
*.pyc
.venv/
+7
View File
@@ -0,0 +1,7 @@
# Copy this file to `.env` and fill in the real values.
# `.env` is gitignored and is NOT baked into the image.
INSE_ELASTIC_URL=https://inse.nes.uni-due.de/elastic
INSE_ELASTIC_API_KEY=your-elastic-api-key-here
INSE_LLM_BASE_URL=https://project.nes.uni-due.de/llm2/v1/
INSE_LLM_API_KEY=your-llm-api-key-here
INSE_LLM_MODEL=gemma4-e4b
+5
View File
@@ -0,0 +1,5 @@
# Local secrets – never commit
.env
__pycache__/
*.pyc
+95
View File
@@ -0,0 +1,95 @@
# Background Jobs
Background Jobs sind Docker-Container, die regelmäßig oder manuell Elasticsearch-Daten verarbeiten. Sie werden vom Backend über den Docker-Socket gestartet.
**Wichtig:** Jobs sind in der **Datenbank**, nicht im Image. Das Image enthält nur die ausführbaren Skripte.
## Jobs anlegen
**Frontend** (`/jobs`):
- "Neuer Job" → Name + Command + optionales Image + Zeitplan
**API**:
```bash
curl -X POST -H "Authorization: Bearer $TOKEN" \
-d '{"name": "Sync", "command": "python sync.py --sync-delta", "schedule": "0 3 * * *"}' \
http://localhost:8000/api/background-jobs/tasks
```
Command-Beispiele:
```
python service/scripts/demo/demo.py 20
python sync.py --sync-delta
python service/scripts/news/ude/run_pipeline.py --skip-upload --max-items 5
python -m service.scripts.news.topic_mapper.map_news_topics --output-index docker-job_test --max-docs 50
python -m service.scripts.projects.topic_mapper.map_project_topics --dry-run
sh -c "cd service/scripts/projects/bund && python gpc.data.py --skip-upload"
```
**Neue Jobs = kein Image-Rebuild.** Die Skripte sind bereits im Image; der Command wird direkt an Docker übergeben.
## Image & Dockerfile
Das [Dockerfile](../service/scripts/jobs-image/Dockerfile) kopiert den kompletten `service/scripts/`-Baum (Pfade im Container = Pfade im Repo) plus `background-jobs/app/` (sync.py) und hat keinen ENTRYPOINT. Neue Skripte unter `service/scripts` landen automatisch im nächsten Build — ohne Dockerfile-Änderung. Der Backend startet Container direkt:
```python
docker.run(image="...", command="python sync.py --sync-delta")
```
**Skripte hinzugefügt oder geändert?** → Image neu bauen + pushen:
```bash
docker build -f service/scripts/jobs-image/Dockerfile -t docker.nes.uni-due.de/inse/background-jobs:latest .
docker push docker.nes.uni-due.de/inse/background-jobs:latest
```
Lokal testen ohne Pull:
```bash
export BACKGROUND_JOBS_PULL_BEFORE_RUN=false
```
## Scheduling
Job mit `schedule: "0 3 * * *"` und `enabled: true` läuft automatisch täglich um 3:00 UTC. Manuell starten: "Jetzt ausführen" Button oder API.
## Logs
Während Laufzeit: Live vom Container. Nach Beendigung: Letzte 200 Zeilen in der DB. Frontend: "Logs anzeigen" Button.
## Docker-Socket (Deployment)
```yaml
# docker-compose
backend:
volumes:
- /var/run/docker.sock:/var/run/docker.sock
```
Ohne Socket-Mount funktioniert nichts.
## Env-Variablen
Standard-Image erhält automatisch:
- `INSE_ELASTIC_URL`, `INSE_ELASTIC_API_KEY`
- `INSE_LLM_*`, `ELASTICSEARCH_INSE_*`, `SENTENCE_TRANSFORMERS_MODEL_NAME`
Plus `env` aus der Job-Definition.
**Eigene Images** bekommen nur die `env`-Variablen (Sicherheit).
## API
- `GET /api/background-jobs/tasks` — Jobs auflisten
- `POST /api/background-jobs/tasks` — Job anlegen
- `DELETE /api/background-jobs/tasks/{id}` — Job löschen
- `POST /api/background-jobs/tasks/{id}/run` — Run starten
- `PATCH /api/background-jobs/tasks/{id}` — Schedule ändern
- `GET /api/background-jobs/runs/{id}/logs` — Logs abrufen
- `POST /api/background-jobs/runs/{id}/stop` — Run stoppen
Alle Endpoints erfordern Superadmin-Auth.
+151
View File
@@ -0,0 +1,151 @@
import os
import requests
from requests.adapters import HTTPAdapter
from urllib.parse import quote
from dotenv import load_dotenv
load_dotenv()
INSE_URL = os.getenv("INSE_ELASTIC_URL", "https://inse.nes.uni-due.de/elastic")
INSE_API_KEY = os.getenv("INSE_ELASTIC_API_KEY")
if not INSE_API_KEY:
raise RuntimeError(
"INSE_ELASTIC_API_KEY is not set. Copy .env.example to .env and fill it in, "
"or pass it as an environment variable."
)
ES_HEADERS = {
"Authorization": f"ApiKey {INSE_API_KEY}",
"Content-Type": "application/json",
}
_session = requests.Session()
_session.headers.update(ES_HEADERS)
_adapter = HTTPAdapter(pool_connections=32, pool_maxsize=32)
_session.mount("https://", _adapter)
_session.mount("http://", _adapter)
def _send_es_request(method: str, url: str, payload: dict = None) -> dict:
try:
response = _session.request(
method=method,
url=url,
json=payload,
)
response.raise_for_status()
return response.json()
except requests.RequestException as error:
print(f"Send Request failed: ({method} {url}): {error}")
raise
def add_entry(index: str, entry: dict):
endpoint = f"{INSE_URL}/{index}/_doc"
document_body = {
"news_id": entry["news_id"],
"relevant": int(entry["relevant"]),
"authors": entry["authors"],
"keywords": entry.get("keywords", []),
}
response_data = _send_es_request("POST", endpoint, payload=document_body)
created_id = response_data["_id"]
entry["_id"] = created_id
return created_id
def index_entry(index: str, document_id: str, entry: dict):
encoded_document_id = quote(document_id, safe="")
endpoint = f"{INSE_URL}/{index}/_doc/{encoded_document_id}"
document_body = {
"news_id": entry["news_id"],
"relevant": int(entry["relevant"]),
"authors": entry["authors"],
"keywords": entry.get("keywords", []),
}
return _send_es_request("PUT", endpoint, payload=document_body)
def update_entry(index: str, document_id: str, partial_doc: dict):
encoded_document_id = quote(document_id, safe="")
endpoint = f"{INSE_URL}/{index}/_update/{encoded_document_id}"
return _send_es_request("POST", endpoint, payload={"doc": partial_doc})
def get_entry(index: str, document_id: str) -> dict:
encoded_document_id = quote(document_id, safe="")
endpoint = f"{INSE_URL}/{index}/_doc/{encoded_document_id}"
return _send_es_request("GET", endpoint)
def delete_entry(index: str, document_id: str):
encoded_document_id = quote(document_id, safe="")
endpoint = f"{INSE_URL}/{index}/_doc/{encoded_document_id}"
return _send_es_request("DELETE", endpoint)
def get_all_entries(index: str, fields: list = None) -> list:
if not fields:
source_fields = True
else:
source_fields = fields
endpoint = f"{INSE_URL}/{index}/_search"
page_size = 1000
results = []
last_sort_value = None
while True:
payload = {
"query": {"match_all": {}},
"size": page_size,
"sort": [{"_doc": "asc"}],
"_source": source_fields,
}
if last_sort_value is not None:
payload["search_after"] = last_sort_value
response_data = _send_es_request("POST", endpoint, payload=payload)
results_list = response_data["hits"]["hits"]
if not results_list:
break
results.extend(results_list)
last_sort_value = results_list[-1]["sort"]
return results
def delete_all_entries(index: str):
endpoint = f"{INSE_URL}/{index}/_delete_by_query"
payload = {
"query": {"match_all": {}}
}
return _send_es_request("POST", endpoint, payload=payload)
def remove_field_all(index: str, field: str):
endpoint = f"{INSE_URL}/{index}/_update_by_query"
payload = {
"query": {"exists": {"field": field}},
"script": {
"source": f"ctx._source.remove('{field}')",
"lang": "painless",
},
}
return _send_es_request("POST", endpoint, payload=payload)
+95
View File
@@ -0,0 +1,95 @@
import os
import requests
from openai import OpenAI, APIConnectionError
from dotenv import load_dotenv
load_dotenv()
LLM_BASE_URL = os.getenv("INSE_LLM_BASE_URL", "https://project.nes.uni-due.de/llm2/v1/")
LLM_API_KEY = os.getenv("INSE_LLM_API_KEY")
if not LLM_API_KEY:
raise RuntimeError(
"INSE_LLM_API_KEY is not set. Copy .env.example to .env and fill it in, "
"or pass it as an environment variable."
)
LLM_MODEL = os.getenv("INSE_LLM_MODEL", "gemma4-e4b")
SYSTEM_PROMPT_RELEVANT = ("""
Du bewertest Nachrichtenartikel aus dem Campus-Aktuell-Bereich der Universität Duisburg-Essen.
Entscheide, ob der Artikel inhaltlich über eine konkrete Person berichtet, also über deren Werdegang, Forschung, Leistung, Auszeichnung oder Tätigkeit.
Falls du dir unsicher bist, ob eine Person im Mittelpunkt steht, dann entscheide dich bitte für die positivere Option (also 1), damit die Namensextraktion auf keinen Fall bei Artikeln mit Personenbezug versäumt wird.
Antworte mit 1, wenn eine konkrete Person im Mittelpunkt steht.
Antworte mit 0, wenn es sich um allgemeine Mitteilungen handelt, die keine einzelne Person in den Mittelpunkt stellen, zum Beispiel Veranstaltungs- und Terminhinweise, Spendenaufrufe, organisatorische Ankündigungen, allgemeine Universitätsinformationen oder Pressemitteilungen ohne Personenbezug.
Die bloße Nennung von Namen (etwa als Autor oder Ansprechpartner) reicht für eine 1 nicht aus; die Person muss inhaltlich Thema des Artikels sein.
Antworte ausschließlich mit einer einzigen Ziffer: 0 oder 1.
""")
SYSTEM_PROMPT_NAMES = ("""
Aus dem nachfolgenden Campus-Aktuell-Artikel der Universität Duisburg-Essen: Nenne die Namen aller konkreten Personen, um die es im Artikel inhaltlich geht.
Es können mehrere Personen sein. Bitte achte darauf dass du nur die Namen der Personen nennst, die tatsächlich im Mittelpunkt des Artikels stehen.
Insbesondere am Ende von Artikeln werden oft Personen genannt, die nur als Ansprechpartner oder Organisator und sollen deshalb nicht genannt werden.
Antworte ausschließlich mit gültigem JSON in exakt diesem Format: {\"person\": [\"Vorname Nachname\", \"Vorname Nachname\"]}
Gib keine Erklärungen und kein Markdown aus, nur das JSON.
""")
SYSTEM_PROMPT_KEYWORDS = ("""
Extrahiere aus dem nachfolgenden Campus-Aktuell-Artikel der Universität Duisburg-Essen die wichtigsten Schlagwörter (Keywords).
Wähle ausschließlich Begriffe oder Phrasen, die tatsächlich im Text vorkommen. Erfinde keine Begriffe, verallgemeinere nicht und nenne keine Oberbegriffe, die nicht im Text stehen.
Übersetze keine Begriffe – verwende ausschließlich Wörter und Phrasen in der Sprache des Artikels.
Gib jedes Schlagwort in seiner Grundform an: Bei deutschen Begriffen Substantive im Nominativ Singular; bei englischen Begriffen Substantive im Singular. Verwende den Plural nur, wenn der Begriff üblicherweise im Plural gebraucht wird.
Vermeide Redundanz: Wenn zwei mögliche Schlagwörter dieselbe Wortbasis teilen (z.B. „Forschung" und „Forschungsprojekt"), nenne nur den spezifischeren Begriff.
Nenne maximal sechs prägnante Begriffe oder kurze Phrasen. Konzentriere dich auf inhaltlich zentrale Begriffe, nicht auf Personennamen oder Datumsangaben.
Antworte ausschließlich mit gültigem JSON in exakt diesem Format: {\"keywords\": [\"Schlagwort\", \"Schlagwort\"]}
Gib keine Erklärungen und kein Markdown aus, nur das JSON.
""")
_client = OpenAI(
base_url=LLM_BASE_URL,
api_key=LLM_API_KEY,
timeout=30,
)
def call(system_prompt, user_prompt, model=LLM_MODEL, temperature=1.0, top_p=0.95):
try:
response = _client.chat.completions.create(
model=model,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt},
],
temperature=temperature,
top_p=top_p,
extra_body={"top_k": 64},
)
except APIConnectionError:
return None
return response.choices[0].message.content or None
def is_news_relevant(text: str) -> bool:
result = call(SYSTEM_PROMPT_RELEVANT, text)
if result is None:
return False
return result.strip() == "1"
def extract_names(text: str) -> list[str]:
result = call(SYSTEM_PROMPT_NAMES, text)
if result is None:
return []
try:
import json
data = json.loads(result)
return data.get("person", [])
except json.JSONDecodeError:
return []
def extract_keywords(text: str) -> list[str]:
result = call(SYSTEM_PROMPT_KEYWORDS, text)
if result is None:
return []
try:
import json
data = json.loads(result)
return data.get("keywords", [])
except json.JSONDecodeError:
return []
+246
View File
@@ -0,0 +1,246 @@
import elastic.client as es_client
import llm.client as llm_client
import json
import argparse
import time
import logging
import threading
from concurrent.futures import ThreadPoolExecutor, as_completed
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger(__name__)
POSTPROC_INDEX = "aktuell_postproc"
def print_pretty_json(data):
logger.info(json.dumps(data, indent=2))
def sync_single_news(news_id, max_retries=3):
attempt = 0
while attempt < max_retries:
try:
news_text = es_client.get_entry("aktuell", news_id)["_source"]["full_content"]
is_news_relevant = llm_client.is_news_relevant(news_text)
authors = llm_client.extract_names(news_text)
keywords = llm_client.extract_keywords(news_text)
new_entry = {
"news_id": news_id,
"relevant": is_news_relevant,
"authors": authors,
"keywords": keywords,
}
es_client.add_entry("aktuell_postproc", new_entry)
return True
except Exception as error:
attempt += 1
logger.warning(f"Warning syncing news_id {news_id} (Attempt {attempt}/{max_retries})")
if attempt < max_retries:
time.sleep(1)
else:
logger.error(f"Error: {news_id} - {error}")
return False
def update_keywords_single(postproc_entry, target_index=POSTPROC_INDEX, max_retries=3):
doc_id = postproc_entry["_id"]
source = postproc_entry["_source"]
news_id = source["news_id"]
attempt = 0
while attempt < max_retries:
try:
news_text = es_client.get_entry("aktuell", news_id)["_source"]["full_content"]
keywords = llm_client.extract_keywords(news_text)
if not keywords:
# Empty article or unparseable LLM answer: writing an empty list
# would look like a success and block a later retry.
logger.info(f"Skipped {news_id}: no keywords extracted.")
return False
if target_index == POSTPROC_INDEX:
es_client.update_entry(POSTPROC_INDEX, doc_id, {"keywords": keywords})
else:
# Key the target doc on news_id so re-runs update it in place
# instead of piling up a new document each time.
es_client.index_entry(
target_index,
news_id,
{
"news_id": news_id,
"relevant": source.get("relevant", 0),
"authors": source.get("authors", []),
"keywords": keywords,
},
)
return True
except Exception as error:
attempt += 1
logger.warning(f"Warning updating keywords for news_id {news_id} (Attempt {attempt}/{max_retries})")
if attempt < max_retries:
time.sleep(1)
else:
logger.error(f"Error: {news_id} - {error}")
return False
def main():
parser = argparse.ArgumentParser(description="Synchronize news articles from 'aktuell' index to 'aktuell_postproc' index with relevance and author extraction using LLM.")
parser.add_argument(
"--delete-all",
action="store_true",
help="Delete all entries from index 'aktuell_postproc'.",
)
parser.add_argument(
"--sync-delta",
action="store_true",
help="Sync only missing entries from 'aktuell' to 'aktuell_postproc'.",
)
parser.add_argument(
"--update-keywords",
action="store_true",
help="Add 'keywords' to existing 'aktuell_postproc' entries that don't have them yet (keeps relevant/authors).",
)
parser.add_argument(
"--reset-keywords",
action="store_true",
help="Remove the 'keywords' field from all 'aktuell_postproc' entries (keeps relevant/authors). Run before re-extracting with a new prompt.",
)
parser.add_argument(
"--stats",
action="store_true",
help="Print statistics about the entries in 'aktuell_postproc' and 'aktuell'.",
)
parser.add_argument(
"--threads",
type=int,
default=4,
help="Number of threads for --sync-delta (Default: 4).",
)
parser.add_argument(
"--limit",
type=int,
default=None,
help="Process at most this many entries (used by --update-keywords, e.g. for a smoke test).",
)
parser.add_argument(
"--target-index",
default=POSTPROC_INDEX,
help=(
f"Index that --update-keywords writes to (default: {POSTPROC_INDEX}). Any other "
"index gets new documents instead of in-place updates, and every entry is "
"re-extracted rather than only those missing keywords."
),
)
args = parser.parse_args()
if args.delete_all:
es_client.delete_all_entries("aktuell_postproc")
if args.reset_keywords:
result = es_client.remove_field_all("aktuell_postproc", "keywords")
logger.info(f"Removed 'keywords' from {result.get('updated', 0)} entries.")
if args.sync_delta:
start_time = time.time()
aktuell_ids_raw = es_client.get_all_entries("aktuell", fields=["_id"])
postproc_ids_raw = es_client.get_all_entries("aktuell_postproc", fields=["news_id"])
source_ids = set(entry["_id"] for entry in aktuell_ids_raw)
target_ids = set(entry["_source"]["news_id"] for entry in postproc_ids_raw)
missing_ids = source_ids - target_ids
logger.info(f"Number of missing IDs: {len(missing_ids)}")
missing_ids = list(missing_ids)
total = len(missing_ids)
processed = 0
succeeded = 0
progress_lock = threading.Lock()
with ThreadPoolExecutor(max_workers=args.threads) as executor:
futures = [executor.submit(sync_single_news, news_id) for news_id in missing_ids]
for future in as_completed(futures):
was_successful = future.result()
with progress_lock:
processed += 1
if was_successful:
succeeded += 1
logger.info(f"Sync: {processed} / {total}")
end_time = time.time()
logger.info(f"Sync DONE: {succeeded} entries synced.")
logger.info(f"Time taken: {end_time - start_time} seconds.")
if args.update_keywords:
start_time = time.time()
postproc_entries = es_client.get_all_entries(
POSTPROC_INDEX, fields=["news_id", "keywords", "relevant", "authors"]
)
if args.target_index == POSTPROC_INDEX:
pending = [entry for entry in postproc_entries if not entry["_source"].get("keywords")]
logger.info(f"Number of entries without keywords: {len(pending)}")
else:
# Writing elsewhere never marks the postproc entries, so the "missing
# keywords" filter would select the same entries on every run. Pick
# entries that already have keywords instead: those are known to come
# from articles with actual content, unlike the empty archive stubs.
pending = [entry for entry in postproc_entries if entry["_source"].get("keywords")]
logger.info(f"Re-extracting keywords into '{args.target_index}': {len(pending)} candidates.")
if args.limit is not None:
pending = pending[:args.limit]
total = len(pending)
logger.info(f"Processing {total} entries.")
processed = 0
succeeded = 0
progress_lock = threading.Lock()
with ThreadPoolExecutor(max_workers=args.threads) as executor:
futures = [
executor.submit(update_keywords_single, entry, args.target_index)
for entry in pending
]
for future in as_completed(futures):
was_successful = future.result()
with progress_lock:
processed += 1
if was_successful:
succeeded += 1
logger.info(f"Update keywords: {processed} / {total}")
end_time = time.time()
logger.info(f"Update keywords DONE: {succeeded} entries updated.")
logger.info(f"Time taken: {end_time - start_time} seconds.")
if args.stats:
aktuell_entries = es_client.get_all_entries("aktuell", fields=["_id"])
logger.info(f"Total entries in 'aktuell': {len(aktuell_entries)}")
postproc_entries = es_client.get_all_entries("aktuell_postproc", fields=["_id", "news_id", "relevant", "authors", "keywords"])
total_entries = len(postproc_entries)
relevant_count = sum(1 for entry in postproc_entries if entry["_source"]["relevant"] == 1)
irrelevant_count = total_entries - relevant_count
news_with_extracted_names = sum(1 for entry in postproc_entries if entry["_source"]["authors"])
news_without_extracted_names = total_entries - news_with_extracted_names
news_with_keywords = sum(1 for entry in postproc_entries if entry["_source"].get("keywords"))
news_without_keywords = total_entries - news_with_keywords
logger.info(f"Total entries in 'aktuell_postproc': {total_entries}")
logger.info(f"Relevant entries: {relevant_count}")
logger.info(f"Irrelevant entries: {irrelevant_count}")
logger.info(f"Entries with extracted names: {news_with_extracted_names}")
logger.info(f"Entries without extracted names: {news_without_extracted_names}")
logger.info(f"Entries with keywords: {news_with_keywords}")
logger.info(f"Entries without keywords: {news_without_keywords}")
if __name__ == "__main__":
main()
@@ -0,0 +1,543 @@
{
"author": {
"id": "https://openalex.org/A5034365278",
"display_name": "Dirk Schadendorf",
"card_works_count": 2376,
"cited_by_count": 221896
},
"webapp_publication_list": {
"endpoint": "/api/v2/works/author/A5034365278?page=0&size=50",
"raw_hits_total_value": 2406,
"raw_hits_total_relation": "eq",
"raw_documents_scanned": 2406,
"unique_openalex_work_ids": 2370,
"duplicate_raw_documents": 36,
"work_ids_with_multiple_source_documents": 36
},
"classification_pipeline": {
"minimum_publication_year": 1950,
"eligible_unique_work_ids": 2369,
"pre_threshold_unique_work_ids": 0,
"missing_year_unique_work_ids": 1,
"classified_by_target_id": 2369,
"eligible_but_missing_in_target": 0,
"classified_target_documents_containing_author": 2369,
"classified_by_id_but_author_missing_from_target_document": 0
},
"institution": {
"id": "https://openalex.org/I62318514",
"pipeline_selected_source_works_matching_institution": 422
},
"important_differences": [
"The author card reads openalex-authors.works_count directly.",
"The publication list counts raw hits from openalex-works* and does not deduplicate by work ID.",
"The classification pipeline deduplicates by normalized OpenAlex work ID.",
"The classification pipeline excludes works with publication_year below 1950 or missing.",
"A work can exist in the classification index but be absent from a per-author target-index count if the stored authors array does not contain that author."
],
"examples": {
"eligible_but_missing_in_target": [],
"publication_year_before_threshold": [],
"publication_year_missing": [
{
"work_id": "W4211208194",
"full_work_id": "https://openalex.org/W4211208194",
"title": "",
"publication_year": null,
"type": "article",
"doi": null,
"updated_date": "2025-11-06T04:12:42.849Z",
"source_index": "openalex-works-3",
"variant_count": 1,
"variant_indices": ["openalex-works-3"],
"classified_by_id": false,
"classification_contains_author": false,
"institution_match": true,
"reason": "publication_year_missing"
}
],
"multiple_source_documents_same_id": [
{
"work_id": "W4409451759",
"full_work_id": "https://openalex.org/W4409451759",
"title": "Clinical validation of droplet digital PCR assays in detecting BRAFV600-mutant circulating tumour DNA as a prognostic biomarker in patients with resected stage III melanoma receiving adjuvant therapy (COMBI-AD): a biomarker analysis from a double-blind, randomised phase 3 trial",
"publication_year": 2025,
"type": "article",
"doi": "https://doi.org/10.1016/s1470-2045(25)00139-1",
"updated_date": "2026-01-13T01:12:25.745Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-4", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W4409145101",
"full_work_id": "https://openalex.org/W4409145101",
"title": "Acral lentiginous melanoma shows a poorer response to immune checkpoint inhibition in the non-resectable or metastatic setting – A EUMelaReg real world outcome study",
"publication_year": 2025,
"type": "article",
"doi": "https://doi.org/10.1016/j.ejcskn.2025.100527",
"updated_date": "2026-03-13T14:20:09.374Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-4", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W4405380398",
"full_work_id": "https://openalex.org/W4405380398",
"title": "A comparison of real-world data on adjuvant treatment in patients with stage III BRAF V600 mutated melanoma – Results of systematic literature research",
"publication_year": 2024,
"type": "review",
"doi": "https://doi.org/10.1016/j.ejca.2024.115160",
"updated_date": "2026-03-13T14:20:09.374Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-4", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W4402565731",
"full_work_id": "https://openalex.org/W4402565731",
"title": "LBA43 10-y survival outcomes from the phase III CheckMate 067 trial of nivolumab plus ipilimumab in advanced melanoma",
"publication_year": 2024,
"type": "article",
"doi": "https://doi.org/10.1016/j.annonc.2024.08.2284",
"updated_date": "2026-03-13T14:20:09.374Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-4", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W4402560903",
"full_work_id": "https://openalex.org/W4402560903",
"title": "1078MO Pembrolizumab (pembro) vs placebo as adjuvant therapy for high-risk stage II melanoma: Long-term follow-up, rechallenge, and crossover in KEYNOTE-716",
"publication_year": 2024,
"type": "article",
"doi": "https://doi.org/10.1016/j.annonc.2024.08.1146",
"updated_date": "2026-03-13T14:20:09.374Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-4", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W4391886851",
"full_work_id": "https://openalex.org/W4391886851",
"title": "Biomarker and pharmacodynamic activity of the transforming growth factor‐beta (<scp>TGFβ)</scp> inhibitor <scp>SAR439459</scp> as monotherapy and in combination with cemiplimab in a phase I clinical study in patients with advanced solid tumors",
"publication_year": 2024,
"type": "article",
"doi": "https://doi.org/10.1111/cts.13736",
"updated_date": "2026-03-13T14:20:09.374Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-4", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W4391430347",
"full_work_id": "https://openalex.org/W4391430347",
"title": "Prognostic and predictive value of non-steroidal anti-inflammatory drugs in the EORTC 1325/KEYNOTE-054 phase III trial of pembrolizumab versus placebo in resected high-risk stage III melanoma",
"publication_year": 2024,
"type": "article",
"doi": "https://doi.org/10.1016/j.ejca.2024.113585",
"updated_date": "2026-01-13T01:12:25.745Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-4", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W4362505674",
"full_work_id": "https://openalex.org/W4362505674",
"title": "The Latest Option: Nivolumab and Relatlimab in Advanced Melanoma",
"publication_year": 2023,
"type": "review",
"doi": "https://doi.org/10.1007/s11912-023-01406-4",
"updated_date": "2026-01-13T01:12:25.745Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-3", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": true,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W4353055387",
"full_work_id": "https://openalex.org/W4353055387",
"title": "Health-related quality of life with nivolumab plus relatlimab versus nivolumab monotherapy in patients with previously untreated unresectable or metastatic melanoma: RELATIVITY-047 trial",
"publication_year": 2023,
"type": "article",
"doi": "https://doi.org/10.1016/j.ejca.2023.03.014",
"updated_date": "2026-03-13T14:20:09.374Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-4", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W4282559953",
"full_work_id": "https://openalex.org/W4282559953",
"title": "Innate immune receptor signaling induces transient melanoma dedifferentiation while preserving immunogenicity",
"publication_year": 2022,
"type": "article",
"doi": "https://doi.org/10.1136/jitc-2021-003863",
"updated_date": "2025-11-06T03:46:38.306Z",
"source_index": "openalex-works",
"variant_count": 2,
"variant_indices": ["openalex-works", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": true,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W3157996908",
"full_work_id": "https://openalex.org/W3157996908",
"title": "Computed tomography-guided biopsy of radiologically unclear lesions in advanced skin cancer: A retrospective analysis of 47 cases",
"publication_year": 2021,
"type": "article",
"doi": "https://doi.org/10.1016/j.ejca.2021.03.026",
"updated_date": "2026-01-13T01:12:25.745Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-3", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W3108194869",
"full_work_id": "https://openalex.org/W3108194869",
"title": "Surveillance of patients with conjunctival melanoma in German-speaking countries: A multinational survey of the German dermatologic cooperative oncology group",
"publication_year": 2020,
"type": "letter",
"doi": "https://doi.org/10.1016/j.ejca.2020.10.021",
"updated_date": "2026-01-13T01:12:25.745Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-3", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W2967473922",
"full_work_id": "https://openalex.org/W2967473922",
"title": "Deep neural networks are superior to dermatologists in melanoma image classification",
"publication_year": 2019,
"type": "article",
"doi": "https://doi.org/10.1016/j.ejca.2019.05.023",
"updated_date": "2026-01-13T01:12:25.745Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-3", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W2950219014",
"full_work_id": "https://openalex.org/W2950219014",
"title": "The X-Linked DDX3X RNA Helicase Dictates Translation Reprogramming and Metastasis in Melanoma",
"publication_year": 2019,
"type": "article",
"doi": "https://doi.org/10.1016/j.celrep.2019.05.069",
"updated_date": "2026-01-13T01:12:25.745Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-4", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W2790093035",
"full_work_id": "https://openalex.org/W2790093035",
"title": "Clinical outcome of concomitant vs interrupted BRAF inhibitor therapy during radiotherapy in melanoma patients",
"publication_year": 2018,
"type": "article",
"doi": "https://doi.org/10.1038/bjc.2017.489",
"updated_date": "2026-01-13T01:12:25.745Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-4", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W2773801101",
"full_work_id": "https://openalex.org/W2773801101",
"title": "Eighth American Joint Committee on Cancer (AJCC) melanoma classification: Let us reconsider stage III",
"publication_year": 2017,
"type": "letter",
"doi": "https://doi.org/10.1016/j.ejca.2017.11.023",
"updated_date": "2026-01-13T01:12:25.745Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-3", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W2767826944",
"full_work_id": "https://openalex.org/W2767826944",
"title": "A phase 2 study of ontuxizumab, a monoclonal antibody targeting endosialin, in metastatic melanoma",
"publication_year": 2017,
"type": "article",
"doi": "https://doi.org/10.1007/s10637-017-0530-4",
"updated_date": "2026-01-13T01:12:25.745Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-3", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W2901161788",
"full_work_id": "https://openalex.org/W2901161788",
"title": "7503-114079-1-Sp",
"publication_year": 2016,
"type": "article",
"doi": null,
"updated_date": "2025-11-06T04:12:42.849Z",
"source_index": "openalex-works-2",
"variant_count": 2,
"variant_indices": ["openalex-works-2", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W2308247172",
"full_work_id": "https://openalex.org/W2308247172",
"title": "Integrating first-line treatment options into clinical practice",
"publication_year": 2015,
"type": "review",
"doi": "https://doi.org/10.1097/cmr.0000000000000200",
"updated_date": "2026-01-13T01:12:25.745Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-3", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W2053545055",
"full_work_id": "https://openalex.org/W2053545055",
"title": "Expression of stress ligands of the immunoreceptor NKG2D in melanoma: Regulation and clinical significance",
"publication_year": 2014,
"type": "review",
"doi": "https://doi.org/10.1016/j.ejcb.2014.01.009",
"updated_date": "2026-01-13T01:12:25.745Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-4", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W2112537584",
"full_work_id": "https://openalex.org/W2112537584",
"title": "Adjuvant pegylated interferon α-2b therapy for melanoma",
"publication_year": 2010,
"type": "article",
"doi": "https://doi.org/10.3892/ol_00000042",
"updated_date": "2026-01-13T01:12:25.745Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-4", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W1967863327",
"full_work_id": "https://openalex.org/W1967863327",
"title": "Screening of Human Tumor Antigens for CD4+ T Cell Epitopes by Combination of HLA-Transgenic Mice, Recombinant Adenovirus and Antigen Peptide Libraries",
"publication_year": 2010,
"type": "article",
"doi": "https://doi.org/10.1371/journal.pone.0014137",
"updated_date": "2026-01-13T01:12:25.745Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-3", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W2124806374",
"full_work_id": "https://openalex.org/W2124806374",
"title": "Multiple Melanomas After Treatment for Hodgkin Lymphoma in a Non-Dutch p16-Leiden Mutation Carrier With 2 MC1R High-Risk Variants",
"publication_year": 2007,
"type": "article",
"doi": "https://doi.org/10.1001/archderm.143.4.495",
"updated_date": "2026-01-13T01:12:25.745Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-4", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W2149012823",
"full_work_id": "https://openalex.org/W2149012823",
"title": "P-glycoprotein expression in primary and metastatic malignant melanoma",
"publication_year": 2006,
"type": "article",
"doi": "https://doi.org/10.1111/j.1365-2133.1995.tb08710.x",
"updated_date": "2026-01-13T01:12:25.745Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-4", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W2047303314",
"full_work_id": "https://openalex.org/W2047303314",
"title": "Expression of GAGE family proteins in malignant melanoma",
"publication_year": 2006,
"type": "article",
"doi": "https://doi.org/10.1016/j.canlet.2006.11.022",
"updated_date": "2026-01-13T01:12:25.745Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-3", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W1963965528",
"full_work_id": "https://openalex.org/W1963965528",
"title": "Photoreceptor proteins as cancer‐retina antigens",
"publication_year": 2006,
"type": "article",
"doi": "https://doi.org/10.1002/ijc.22458",
"updated_date": "2026-01-13T01:12:25.745Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-4", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W2404943841",
"full_work_id": "https://openalex.org/W2404943841",
"title": "[Acute juvenile pityriasis rubra pilaris in a 2-year-old child].",
"publication_year": 2004,
"type": "article",
"doi": null,
"updated_date": "2025-11-06T04:12:42.849Z",
"source_index": "openalex-works-3",
"variant_count": 2,
"variant_indices": ["openalex-works-3", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W2037452525",
"full_work_id": "https://openalex.org/W2037452525",
"title": "mRNA expression of tumor‐associated antigens in melanoma tissues and cell lines",
"publication_year": 2002,
"type": "article",
"doi": "https://doi.org/10.1034/j.1600-0625.2002.110402.x",
"updated_date": "2026-01-13T01:12:25.745Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-4", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W1983494843",
"full_work_id": "https://openalex.org/W1983494843",
"title": "Study of Therapy Resistance in Cancer Cells with Functional Proteome Analysis",
"publication_year": 2002,
"type": "review",
"doi": "https://doi.org/10.1515/cclm.2002.037",
"updated_date": "2026-01-13T01:12:25.745Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-3", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W2598959332",
"full_work_id": "https://openalex.org/W2598959332",
"title": "‘PEG meets Liposome’ – zwei Technologien führen zu einer Substanz mit neuem Profil",
"publication_year": 2001,
"type": "article",
"doi": "https://doi.org/10.1159/000050295",
"updated_date": "2025-11-06T03:46:38.306Z",
"source_index": "openalex-works",
"variant_count": 2,
"variant_indices": ["openalex-works", "openalex-works-2"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
}
],
"classified_but_author_missing": []
}
}
@@ -2,6 +2,7 @@ from __future__ import annotations
import argparse
import json
import sys
import time
from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
from datetime import datetime, timezone
@@ -12,6 +13,15 @@ import requests
from openai import OpenAI
ROOT = Path(__file__).resolve().parent
SERVICE_SOURCE_ROOT = ROOT.parents[1] / "service" / "src" / "main"
if str(SERVICE_SOURCE_ROOT) not in sys.path:
sys.path.insert(0, str(SERVICE_SOURCE_ROOT))
from inse.authors.institution_membership_query import ( # noqa: E402
build_institution_membership_query,
current_affiliation_year_cutoff,
)
PROMPT_FILE = ROOT / "prompt_frascati_hard_ranges_v2.txt"
REPORTS_DIR = ROOT / "run_reports"
@@ -27,11 +37,13 @@ LLM_MODEL = "gemma4-e4b"
PROMPT_VERSION = "frascati_hard_ranges_v2"
UDE_ID = "https://openalex.org/I62318514"
UDE_ROR = "https://ror.org/04mz5ra38"
UDE_NAME = "University of Duisburg-Essen"
AFFILIATION_YEAR_GTE = 2025
AFFILIATION_YEAR_GTE = current_affiliation_year_cutoff()
WORK_YEAR_GTE = 1950
SELECTION_AUTHOR_COHORT = "author-cohort"
SELECTION_INSTITUTION_WORKS = "institution-works"
SELECTION_MODES = (SELECTION_AUTHOR_COHORT, SELECTION_INSTITUTION_WORKS)
AUTHOR_PAGE_SIZE = 1000
AUTHOR_BATCH_SIZE = 1000
WORK_PAGE_SIZE = 2000
@@ -201,6 +213,7 @@ TARGET_TOP_LEVEL_FIELDS = {
"work_id",
"title",
"publication_year",
"publication_type",
"doi",
"authors",
"institutions",
@@ -209,6 +222,7 @@ TARGET_TOP_LEVEL_FIELDS = {
"validation",
"classification_meta",
}
TARGET_OPTIONAL_TOP_LEVEL_FIELDS = {"publication_type"}
TARGET_CLASSIFICATION_FIELDS = {
"primary_category",
"applied_orientation_score",
@@ -398,6 +412,7 @@ def build_work_metadata(
"work_id": full_work_id,
"title": title,
"publication_year": publication_year,
"publication_type": nullable_text(work.get("type")),
"doi": nullable_text(work.get("doi")),
"authors": target_authors(work),
"institutions": target_institutions(work),
@@ -409,12 +424,13 @@ def exact_fields(
value: Any,
expected: set[str],
path: str,
optional: set[str] | None = None,
) -> list[str]:
if not isinstance(value, dict):
return [f"{path}_must_be_object"]
actual = set(value)
errors: list[str] = []
missing = expected - actual
missing = expected - (optional or set()) - actual
unknown = actual - expected
if missing:
errors.append(f"{path}_missing_fields:{','.join(sorted(missing))}")
@@ -456,7 +472,12 @@ def validate_target_document(
short_work_id: str,
document: Any,
) -> list[str]:
errors = exact_fields(document, TARGET_TOP_LEVEL_FIELDS, "document")
errors = exact_fields(
document,
TARGET_TOP_LEVEL_FIELDS,
"document",
optional=TARGET_OPTIONAL_TOP_LEVEL_FIELDS,
)
if not isinstance(document, dict):
return errors
@@ -466,6 +487,12 @@ def validate_target_document(
errors.extend(validate_nullable_string(document.get("title"), "title"))
errors.extend(validate_nullable_string(document.get("doi"), "doi"))
errors.extend(
validate_nullable_string(
document.get("publication_type"),
"publication_type",
)
)
year = document.get("publication_year")
if year is not None and (isinstance(year, bool) or not isinstance(year, int)):
@@ -854,69 +881,20 @@ def validate(result: dict[str, Any]) -> list[str]:
return errors
def ude_affiliation_filter() -> dict[str, Any]:
return {
"nested": {
"path": "affiliations",
"query": {
"bool": {
"filter": [
{
"bool": {
"should": [
{"term": {"affiliations.institution.id": UDE_ID}},
{"term": {"affiliations.institution.ror": UDE_ROR}},
{
"match_phrase": {
"affiliations.institution.display_name": UDE_NAME
}
},
],
"minimum_should_match": 1,
}
},
{
"range": {
"affiliations.years": {"gte": AFFILIATION_YEAR_GTE}
}
},
]
}
},
}
}
def author_query(group: str, after: list[Any] | None) -> dict[str, Any]:
last_known = {
"nested": {
"path": "last_known_institutions",
"query": {
"match_phrase": {"last_known_institutions.display_name": UDE_NAME}
},
}
}
last_known_exists = {
"nested": {
"path": "last_known_institutions",
"query": {"exists": {"field": "last_known_institutions.display_name"}},
}
}
query = (
{"bool": {"filter": [last_known, ude_affiliation_filter()]}}
if group == "known"
else {
"bool": {
"filter": [ude_affiliation_filter()],
"must_not": [last_known_exists],
}
}
)
def author_query(
after: list[Any] | None,
institution_id: str = UDE_ID,
affiliation_year_gte: int = AFFILIATION_YEAR_GTE,
) -> dict[str, Any]:
body: dict[str, Any] = {
"size": AUTHOR_PAGE_SIZE,
"track_total_hits": True,
"_source": ["id"],
"query": query,
"query": build_institution_membership_query(
institution_id=institution_id,
year_mode="from",
year=affiliation_year_gte,
),
"sort": [{"id": "asc"}],
}
if after is not None:
@@ -924,7 +902,22 @@ def author_query(group: str, after: list[Any] | None) -> dict[str, Any]:
return body
def work_query(author_ids: list[str], after: list[Any] | None) -> dict[str, Any]:
def work_query(
author_ids: list[str],
after: list[Any] | None,
work_year_gte: int | None = WORK_YEAR_GTE,
) -> dict[str, Any]:
filters: list[dict[str, Any]] = [
{
"nested": {
"path": "authorships",
"query": {"terms": {"authorships.author.id": author_ids}},
}
}
]
if work_year_gte is not None:
filters.insert(0, {"range": {"publication_year": {"gte": work_year_gte}}})
body: dict[str, Any] = {
"size": WORK_PAGE_SIZE,
"track_total_hits": False,
@@ -964,15 +957,7 @@ def work_query(author_ids: list[str], after: list[Any] | None) -> dict[str, Any]
],
"query": {
"bool": {
"filter": [
{"range": {"publication_year": {"gte": WORK_YEAR_GTE}}},
{
"nested": {
"path": "authorships",
"query": {"terms": {"authorships.author.id": author_ids}},
}
},
]
"filter": filters
}
},
"sort": [{"id": "asc"}],
@@ -982,6 +967,36 @@ def work_query(author_ids: list[str], after: list[Any] | None) -> dict[str, Any]
return body
def institution_work_query(
institution_id: str,
after: list[Any] | None,
) -> dict[str, Any]:
"""Select all works attributed to an institution, like Publikationsliste."""
body = work_query([], after)
body["query"] = {
"bool": {
"must": [
{
"nested": {
"path": "authorships",
"query": {
"nested": {
"path": "authorships.institutions",
"query": {
"terms": {
"authorships.institutions.id": [institution_id]
}
},
}
},
}
}
]
}
}
return body
def choose_work_hit(
current: dict[str, Any] | None,
candidate: dict[str, Any],
@@ -1016,6 +1031,7 @@ EXPECTED_MAPPING_TYPES = {
"work_id": "keyword",
"title": "text",
"publication_year": "integer",
"publication_type": "keyword",
"doi": "keyword",
"authors": "nested",
"authors.id": "keyword",
@@ -1510,32 +1526,42 @@ def classify(
raise StopPipeline(f"LLM unavailable for {work_id}: {error}")
def collect_authors(es: ES) -> list[str]:
def collect_authors(
es: ES,
institution_id: str = UDE_ID,
affiliation_year_gte: int = AFFILIATION_YEAR_GTE,
) -> list[str]:
ids: set[str] = set()
for group in ("known", "empty"):
after = None
total = None
read = 0
while True:
result = es.search(AUTHORS_INDEX, author_query(group, after))
hits = result.get("hits", {}).get("hits", [])
if total is None:
value = result.get("hits", {}).get("total", 0)
total = int(value.get("value", 0) if isinstance(value, dict) else value)
print(f"Authors {group}: expected {total}")
if not hits:
break
for hit in hits:
author_id = (hit.get("_source") or {}).get("id")
if isinstance(author_id, str):
ids.add(author_id)
read += len(hits)
after = hits[-1].get("sort")
if not isinstance(after, list):
raise StopPipeline("Missing author search_after")
print(f"Authors {group}: {read}/{total}")
after = None
total = None
read = 0
while True:
result = es.search(
AUTHORS_INDEX,
author_query(
after,
institution_id,
affiliation_year_gte,
),
)
hits = result.get("hits", {}).get("hits", [])
if total is None:
value = result.get("hits", {}).get("total", 0)
total = int(value.get("value", 0) if isinstance(value, dict) else value)
print(f"Authors: expected {total}")
if not hits:
break
for hit in hits:
author_id = (hit.get("_source") or {}).get("id")
if isinstance(author_id, str):
ids.add(author_id)
read += len(hits)
after = hits[-1].get("sort")
if not isinstance(after, list):
raise StopPipeline("Missing author search_after")
print(f"Authors: {read}/{total}")
result = sorted(ids)
print(f"Final UDE author count: {len(result)}")
print(f"Final institution author count: {len(result)}")
return result
@@ -1726,6 +1752,10 @@ def run(
limit: int | None,
workers: int,
report: dict[str, Any],
selection_mode: str = SELECTION_AUTHOR_COHORT,
institution_id: str = UDE_ID,
affiliation_year_gte: int = AFFILIATION_YEAR_GTE,
work_year_gte: int | None = WORK_YEAR_GTE,
preflight_only: bool = False,
) -> None:
if not ES_API_KEY.strip():
@@ -1749,17 +1779,32 @@ def run(
api_key=LLM_API_KEY,
timeout=REQUEST_TIMEOUT,
)
authors = collect_authors(es)
count = 0
warm = False
batches = (len(authors) + AUTHOR_BATCH_SIZE - 1) // AUTHOR_BATCH_SIZE
for start in range(0, len(authors), AUTHOR_BATCH_SIZE):
if selection_mode == SELECTION_INSTITUTION_WORKS:
work_batches: list[tuple[str, list[str] | None]] = [
(f"Institution works: {institution_id}", None)
]
else:
authors = collect_authors(
es,
institution_id,
affiliation_year_gte,
)
batch_count = (len(authors) + AUTHOR_BATCH_SIZE - 1) // AUTHOR_BATCH_SIZE
work_batches = [
(
f"Author batch {start // AUTHOR_BATCH_SIZE + 1}/{batch_count}",
authors[start : start + AUTHOR_BATCH_SIZE],
)
for start in range(0, len(authors), AUTHOR_BATCH_SIZE)
]
for batch_label, author_ids in work_batches:
if limit is not None and count >= limit:
break
batch = authors[start : start + AUTHOR_BATCH_SIZE]
print(f"\nAuthor batch {start // AUTHOR_BATCH_SIZE + 1}/{batches}")
print(f"\n{batch_label}")
after = None
page = 0
@@ -1767,7 +1812,12 @@ def run(
if limit is not None and count >= limit:
break
result = es.search(WORKS_INDEX, work_query(batch, after))
query = (
institution_work_query(institution_id, after)
if author_ids is None
else work_query(author_ids, after, work_year_gte)
)
result = es.search(WORKS_INDEX, query)
hits = result.get("hits", {}).get("hits", [])
if not hits:
break
@@ -1843,15 +1893,58 @@ def main() -> None:
parser.add_argument("--limit", type=int)
parser.add_argument("--workers", type=int, default=MAX_WORKERS)
parser.add_argument("--preflight-only", action="store_true")
parser.add_argument(
"--selection-mode",
choices=SELECTION_MODES,
default=SELECTION_AUTHOR_COHORT,
help=(
"author-cohort selects works by current affiliated authors; "
"institution-works selects every work attributed to --institution-id"
),
)
parser.add_argument("--institution-id", default=UDE_ID)
parser.add_argument(
"--affiliation-year-gte", type=int, default=AFFILIATION_YEAR_GTE
)
parser.add_argument("--work-year-gte", type=int, default=WORK_YEAR_GTE)
parser.add_argument(
"--all-work-years",
action="store_true",
help=(
"disable the publication-year filter in author-cohort mode, "
"including works without publication_year"
),
)
args = parser.parse_args()
if args.limit is not None and args.limit < 1:
raise SystemExit("--limit must be at least 1")
if args.workers < 1:
raise SystemExit("--workers must be at least 1")
if args.affiliation_year_gte < 0:
raise SystemExit("--affiliation-year-gte must not be negative")
if args.work_year_gte < 0:
raise SystemExit("--work-year-gte must not be negative")
work_year_gte = None if args.all_work_years else args.work_year_gte
institution_id = args.institution_id.strip()
if not institution_id:
raise SystemExit("--institution-id must not be empty")
if not institution_id.startswith("https://openalex.org/"):
institution_id = f"https://openalex.org/{bare_id(institution_id)}"
report = new_run_report(args.limit, args.workers)
report["parameters"]["preflight_only"] = args.preflight_only
report["parameters"].update(
{
"selection_mode": args.selection_mode,
"institution_id": institution_id,
"affiliation_year_gte": args.affiliation_year_gte,
"work_year_gte": work_year_gte,
"all_work_years": args.all_work_years,
}
)
exit_code = 0
try:
@@ -1859,6 +1952,10 @@ def main() -> None:
args.limit,
args.workers,
report,
selection_mode=args.selection_mode,
institution_id=institution_id,
affiliation_year_gte=args.affiliation_year_gte,
work_year_gte=work_year_gte,
preflight_only=args.preflight_only,
)
report["status"] = "completed"
@@ -0,0 +1,755 @@
#!/usr/bin/env python3
"""Compare the three publication-counting approaches for one OpenAlex author.
The script compares:
1. The author card value from openalex-authors.works_count.
2. The publication-list backend query used by /person/{id}/publications.
3. The classification-pipeline set based on unique OpenAlex work IDs since 1950.
4. Existing documents in work-classifications.
It also writes concrete discrepancy examples to JSON and CSV files.
No credentials are hardcoded. The script reads:
- ELASTICSEARCH_URL
- ELASTICSEARCH_API_KEY
from service/src/main/inse/.env or from the process environment.
python compare_author_publication_counts.py ^ --project-root . ^ --author-id A5034365278 ^ --institution-id I62318514
"""
from __future__ import annotations
import argparse
import csv
import json
import os
import sys
from collections import defaultdict
from pathlib import Path
from typing import Any, Iterable
import requests
DEFAULT_AUTHOR_ID = "A5034365278"
DEFAULT_WORK_YEAR_GTE = 1950
SOURCE_INDEX = "openalex-works*"
AUTHOR_INDEX = "openalex-authors"
TARGET_INDEX = "work-classifications"
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Compare author publication counts across the webapp and classification index."
)
parser.add_argument(
"--author-id",
default=DEFAULT_AUTHOR_ID,
help="OpenAlex author ID, for example A5034365278.",
)
parser.add_argument(
"--project-root",
type=Path,
default=Path.cwd(),
help="Project root containing service/src/main/inse/.env.",
)
parser.add_argument(
"--env-file",
type=Path,
default=None,
help="Explicit .env file. Defaults to service/src/main/inse/.env.",
)
parser.add_argument(
"--institution-id",
default=None,
help=(
"Optional OpenAlex institution ID used to inspect institution-specific works, "
"for example I62318514."
),
)
parser.add_argument(
"--work-year-gte",
type=int,
default=DEFAULT_WORK_YEAR_GTE,
help="Minimum publication year used by the classification pipeline.",
)
parser.add_argument(
"--output-dir",
type=Path,
default=Path("author_publication_comparison"),
help="Directory for JSON and CSV output.",
)
parser.add_argument(
"--example-limit",
type=int,
default=30,
help="Maximum number of examples per discrepancy group.",
)
return parser.parse_args()
def read_env_file(path: Path) -> dict[str, str]:
values: dict[str, str] = {}
if not path.exists():
return values
for raw_line in path.read_text(encoding="utf-8").splitlines():
line = raw_line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, value = line.split("=", 1)
values[key.strip()] = value.strip().strip('"').strip("'")
return values
def load_credentials(args: argparse.Namespace) -> tuple[str, str]:
env_file = args.env_file
if env_file is None:
env_file = args.project_root / "service" / "src" / "main" / "inse" / ".env"
file_values = read_env_file(env_file)
base_url = (
os.getenv("ELASTICSEARCH_URL") or file_values.get("ELASTICSEARCH_URL") or ""
).rstrip("/")
api_key = (
os.getenv("ELASTICSEARCH_API_KEY")
or file_values.get("ELASTICSEARCH_API_KEY")
or ""
).strip()
if not base_url:
raise RuntimeError(
f"ELASTICSEARCH_URL is missing. Set it in the environment or in {env_file}."
)
if not api_key:
raise RuntimeError(
"ELASTICSEARCH_API_KEY is missing. Set it in the environment or in "
f"{env_file}."
)
return base_url, api_key
def full_openalex_id(value: str, prefix: str) -> str:
clean = value.strip().rstrip("/").rsplit("/", 1)[-1]
if not clean.startswith(prefix):
raise ValueError(f"Unexpected OpenAlex ID: {value}")
return f"https://openalex.org/{clean}"
def short_openalex_id(value: Any) -> str | None:
if not isinstance(value, str) or not value.strip():
return None
return value.strip().rstrip("/").rsplit("/", 1)[-1]
class ElasticsearchClient:
def __init__(self, base_url: str, api_key: str) -> None:
self.base_url = base_url.rstrip("/")
self.session = requests.Session()
self.session.headers.update(
{
"Authorization": f"ApiKey {api_key}",
"Content-Type": "application/json",
"Accept": "application/json",
}
)
def request(
self,
method: str,
path: str,
*,
body: dict[str, Any] | None = None,
params: dict[str, Any] | None = None,
timeout: float = 120.0,
) -> dict[str, Any]:
response = self.session.request(
method,
f"{self.base_url}/{path.lstrip('/')}",
json=body,
params=params,
timeout=timeout,
)
if not response.ok:
raise RuntimeError(
f"Elasticsearch {response.status_code} for {path}: "
f"{response.text[:1000]}"
)
if not response.content:
return {}
return response.json()
def get_author(self, short_author_id: str) -> dict[str, Any]:
result = self.request(
"GET",
f"{AUTHOR_INDEX}/_doc/{short_author_id}",
params={"_source": "id,display_name,works_count,cited_by_count"},
)
source = result.get("_source")
if not isinstance(source, dict):
raise RuntimeError(f"Author not found: {short_author_id}")
return source
def search_publication_page(
self,
full_author_id: str,
*,
page: int = 0,
size: int = 50,
) -> dict[str, Any]:
query = author_query(full_author_id)
body = {
"query": query,
"_source": [
"id",
"title",
"type",
"publication_year",
"language",
"cited_by_count",
"authorships.author",
"authorships.institutions.id",
"topics",
],
"from": page * size,
"size": size,
"sort": [{"publication_year": "desc"}],
}
return self.request("POST", f"{SOURCE_INDEX}/_search", body=body)
def scroll_author_works(
self,
full_author_id: str,
*,
page_size: int = 1000,
) -> list[dict[str, Any]]:
body = {
"size": page_size,
"track_total_hits": True,
"query": author_query(full_author_id),
"_source": [
"id",
"doi",
"title",
"display_name",
"publication_year",
"updated_date",
"type",
"authorships.author.id",
"authorships.author.display_name",
"authorships.institutions.id",
"authorships.institutions.display_name",
],
"sort": ["_doc"],
}
result = self.request(
"POST",
f"{SOURCE_INDEX}/_search",
body=body,
params={"scroll": "2m"},
)
scroll_id = result.get("_scroll_id")
hits: list[dict[str, Any]] = []
try:
while True:
page_hits = result.get("hits", {}).get("hits", [])
if not page_hits:
break
hits.extend(hit for hit in page_hits if isinstance(hit, dict))
if not scroll_id:
break
result = self.request(
"POST",
"_search/scroll",
body={"scroll": "2m", "scroll_id": scroll_id},
)
scroll_id = result.get("_scroll_id", scroll_id)
finally:
if scroll_id:
try:
self.request(
"DELETE",
"_search/scroll",
body={"scroll_id": [scroll_id]},
)
except Exception:
pass
return hits
def mget_classifications(
self,
short_work_ids: list[str],
*,
chunk_size: int = 500,
) -> dict[str, dict[str, Any]]:
result: dict[str, dict[str, Any]] = {}
for start in range(0, len(short_work_ids), chunk_size):
chunk = short_work_ids[start : start + chunk_size]
response = self.request(
"POST",
f"{TARGET_INDEX}/_mget",
body={"ids": chunk},
params={
"_source_includes": ",".join(
[
"work_id",
"title",
"publication_year",
"authors.id",
"classification.primary_category",
"classification_meta.prompt_version",
]
)
},
)
for document in response.get("docs", []):
if isinstance(document, dict):
result[str(document.get("_id"))] = document
return result
def count_classifications_by_author(self, full_author_id: str) -> int:
response = self.request(
"POST",
f"{TARGET_INDEX}/_count",
body={
"query": {
"nested": {
"path": "authors",
"query": {"term": {"authors.id": full_author_id}},
}
}
},
)
return int(response.get("count", 0))
def author_query(full_author_id: str) -> dict[str, Any]:
return {
"nested": {
"path": "authorships",
"query": {"term": {"authorships.author.id": full_author_id}},
}
}
def choose_pipeline_hit(
current: dict[str, Any] | None,
candidate: dict[str, Any],
) -> dict[str, Any]:
"""Reproduce classify_ude_works_to_index.py source-version selection."""
if current is None:
return candidate
current_index = current.get("_index")
candidate_index = candidate.get("_index")
if candidate_index == "openalex-works" and current_index != "openalex-works":
return candidate
if current_index == "openalex-works" and candidate_index != "openalex-works":
return current
current_source = current.get("_source")
candidate_source = candidate.get("_source")
current_updated = (
current_source.get("updated_date") if isinstance(current_source, dict) else None
)
candidate_updated = (
candidate_source.get("updated_date")
if isinstance(candidate_source, dict)
else None
)
if isinstance(candidate_updated, str):
if not isinstance(current_updated, str) or candidate_updated > current_updated:
return candidate
return current
def work_record(hit: dict[str, Any]) -> dict[str, Any]:
source = hit.get("_source")
if not isinstance(source, dict):
source = {}
work_id = short_openalex_id(source.get("id") or hit.get("_id"))
return {
"work_id": work_id,
"full_work_id": (f"https://openalex.org/{work_id}" if work_id else None),
"title": source.get("title") or source.get("display_name"),
"publication_year": source.get("publication_year"),
"type": source.get("type"),
"doi": source.get("doi"),
"updated_date": source.get("updated_date"),
"source_index": hit.get("_index"),
}
def author_ids_in_source(source: dict[str, Any]) -> set[str]:
result: set[str] = set()
for authorship in source.get("authorships") or []:
if not isinstance(authorship, dict):
continue
author = authorship.get("author")
if not isinstance(author, dict):
continue
author_id = author.get("id")
if isinstance(author_id, str):
result.add(author_id)
return result
def institution_ids_in_source(source: dict[str, Any]) -> set[str]:
result: set[str] = set()
for authorship in source.get("authorships") or []:
if not isinstance(authorship, dict):
continue
for institution in authorship.get("institutions") or []:
if not isinstance(institution, dict):
continue
institution_id = institution.get("id")
if isinstance(institution_id, str):
result.add(institution_id)
return result
def classification_author_ids(document: dict[str, Any]) -> set[str]:
source = document.get("_source")
if not isinstance(source, dict):
return set()
result: set[str] = set()
for author in source.get("authors") or []:
if isinstance(author, dict) and isinstance(author.get("id"), str):
result.add(author["id"])
return result
def sort_work_records(records: Iterable[dict[str, Any]]) -> list[dict[str, Any]]:
return sorted(
records,
key=lambda item: (
item.get("publication_year") is not None,
item.get("publication_year") or -1,
item.get("work_id") or "",
),
reverse=True,
)
def write_csv(path: Path, rows: list[dict[str, Any]]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
fieldnames = [
"work_id",
"full_work_id",
"title",
"publication_year",
"type",
"doi",
"updated_date",
"source_index",
"variant_count",
"variant_indices",
"classified_by_id",
"classification_contains_author",
"institution_match",
"reason",
]
with path.open("w", encoding="utf-8-sig", newline="") as handle:
writer = csv.DictWriter(handle, fieldnames=fieldnames, extrasaction="ignore")
writer.writeheader()
writer.writerows(rows)
def main() -> int:
args = parse_args()
base_url, api_key = load_credentials(args)
client = ElasticsearchClient(base_url, api_key)
short_author_id = short_openalex_id(args.author_id)
if short_author_id is None:
raise RuntimeError("Author ID is empty.")
full_author_id = full_openalex_id(short_author_id, "A")
full_institution_id: str | None = None
if args.institution_id:
short_institution_id = short_openalex_id(args.institution_id)
if short_institution_id is None:
raise RuntimeError("Institution ID is empty.")
full_institution_id = full_openalex_id(short_institution_id, "I")
output_dir = args.output_dir
output_dir.mkdir(parents=True, exist_ok=True)
print(f"Loading author {short_author_id}...")
author = client.get_author(short_author_id)
print("Reproducing the publication-list query...")
publication_page = client.search_publication_page(
full_author_id,
page=0,
size=50,
)
page_total = publication_page.get("hits", {}).get("total", {})
page_total_value = (
int(page_total.get("value", 0))
if isinstance(page_total, dict)
else int(page_total or 0)
)
page_total_relation = (
page_total.get("relation") if isinstance(page_total, dict) else None
)
print("Scanning all matching source documents...")
raw_hits = client.scroll_author_works(full_author_id)
variants_by_work_id: dict[str, list[dict[str, Any]]] = defaultdict(list)
pipeline_hit_by_work_id: dict[str, dict[str, Any]] = {}
for hit in raw_hits:
source = hit.get("_source")
if not isinstance(source, dict):
continue
work_id = short_openalex_id(source.get("id") or hit.get("_id"))
if not work_id:
continue
variants_by_work_id[work_id].append(hit)
pipeline_hit_by_work_id[work_id] = choose_pipeline_hit(
pipeline_hit_by_work_id.get(work_id),
hit,
)
unique_work_ids = sorted(pipeline_hit_by_work_id)
eligible_work_ids: list[str] = []
pre_threshold_work_ids: list[str] = []
missing_year_work_ids: list[str] = []
for work_id, hit in pipeline_hit_by_work_id.items():
source = hit.get("_source")
if not isinstance(source, dict):
continue
year = source.get("publication_year")
if isinstance(year, bool) or not isinstance(year, int):
missing_year_work_ids.append(work_id)
elif year < args.work_year_gte:
pre_threshold_work_ids.append(work_id)
else:
eligible_work_ids.append(work_id)
print("Loading matching classification documents...")
classification_docs = client.mget_classifications(eligible_work_ids)
classified_author_count = client.count_classifications_by_author(full_author_id)
classified_by_id: list[str] = []
unclassified_eligible: list[str] = []
classified_but_author_missing: list[str] = []
for work_id in eligible_work_ids:
document = classification_docs.get(work_id)
if document and document.get("found"):
classified_by_id.append(work_id)
if full_author_id not in classification_author_ids(document):
classified_but_author_missing.append(work_id)
else:
unclassified_eligible.append(work_id)
duplicate_work_ids = [
work_id
for work_id, variants in variants_by_work_id.items()
if len(variants) > 1
]
institution_matching_work_ids: list[str] = []
if full_institution_id:
for work_id, hit in pipeline_hit_by_work_id.items():
source = hit.get("_source")
if not isinstance(source, dict):
continue
if full_institution_id in institution_ids_in_source(source):
institution_matching_work_ids.append(work_id)
def enrich(work_id: str, reason: str) -> dict[str, Any]:
hit = pipeline_hit_by_work_id[work_id]
record = work_record(hit)
variants = variants_by_work_id.get(work_id, [])
classification = classification_docs.get(work_id)
source = hit.get("_source")
institution_match = None
if full_institution_id and isinstance(source, dict):
institution_match = full_institution_id in institution_ids_in_source(source)
record.update(
{
"variant_count": len(variants),
"variant_indices": sorted(
{
str(variant.get("_index"))
for variant in variants
if variant.get("_index")
}
),
"classified_by_id": bool(
classification and classification.get("found")
),
"classification_contains_author": bool(
classification
and classification.get("found")
and full_author_id in classification_author_ids(classification)
),
"institution_match": institution_match,
"reason": reason,
}
)
return record
unclassified_examples = sort_work_records(
enrich(work_id, "eligible_since_threshold_but_missing_in_target")
for work_id in unclassified_eligible
)
pre_threshold_examples = sort_work_records(
enrich(work_id, f"publication_year_before_{args.work_year_gte}")
for work_id in pre_threshold_work_ids
)
missing_year_examples = sort_work_records(
enrich(work_id, "publication_year_missing") for work_id in missing_year_work_ids
)
duplicate_examples = sort_work_records(
enrich(work_id, "multiple_source_documents_same_openalex_id")
for work_id in duplicate_work_ids
)
author_missing_examples = sort_work_records(
enrich(work_id, "classified_target_document_does_not_contain_author")
for work_id in classified_but_author_missing
)
summary = {
"author": {
"id": full_author_id,
"display_name": author.get("display_name"),
"card_works_count": author.get("works_count"),
"cited_by_count": author.get("cited_by_count"),
},
"webapp_publication_list": {
"endpoint": f"/api/v2/works/author/{short_author_id}?page=0&size=50",
"raw_hits_total_value": page_total_value,
"raw_hits_total_relation": page_total_relation,
"raw_documents_scanned": len(raw_hits),
"unique_openalex_work_ids": len(unique_work_ids),
"duplicate_raw_documents": len(raw_hits) - len(unique_work_ids),
"work_ids_with_multiple_source_documents": len(duplicate_work_ids),
},
"classification_pipeline": {
"minimum_publication_year": args.work_year_gte,
"eligible_unique_work_ids": len(eligible_work_ids),
"pre_threshold_unique_work_ids": len(pre_threshold_work_ids),
"missing_year_unique_work_ids": len(missing_year_work_ids),
"classified_by_target_id": len(classified_by_id),
"eligible_but_missing_in_target": len(unclassified_eligible),
"classified_target_documents_containing_author": classified_author_count,
"classified_by_id_but_author_missing_from_target_document": len(
classified_but_author_missing
),
},
"institution": {
"id": full_institution_id,
"pipeline_selected_source_works_matching_institution": (
len(institution_matching_work_ids) if full_institution_id else None
),
},
"important_differences": [
"The author card reads openalex-authors.works_count directly.",
"The publication list counts raw hits from openalex-works* and does not deduplicate by work ID.",
"The classification pipeline deduplicates by normalized OpenAlex work ID.",
f"The classification pipeline excludes works with publication_year below {args.work_year_gte} or missing.",
"A work can exist in the classification index but be absent from a per-author target-index count if the stored authors array does not contain that author.",
],
"examples": {
"eligible_but_missing_in_target": unclassified_examples[
: args.example_limit
],
"publication_year_before_threshold": pre_threshold_examples[
: args.example_limit
],
"publication_year_missing": missing_year_examples[: args.example_limit],
"multiple_source_documents_same_id": duplicate_examples[
: args.example_limit
],
"classified_but_author_missing": author_missing_examples[
: args.example_limit
],
},
}
json_path = output_dir / f"{short_author_id}_publication_count_comparison.json"
json_path.write_text(
json.dumps(summary, ensure_ascii=False, indent=2),
encoding="utf-8",
)
write_csv(
output_dir / f"{short_author_id}_eligible_but_unclassified.csv",
unclassified_examples,
)
write_csv(
output_dir / f"{short_author_id}_source_duplicates.csv",
duplicate_examples,
)
write_csv(
output_dir / f"{short_author_id}_excluded_by_year.csv",
pre_threshold_examples + missing_year_examples,
)
write_csv(
output_dir / f"{short_author_id}_classified_but_author_missing.csv",
author_missing_examples,
)
print()
print("Comparison")
print("----------")
print(f"Author card works_count: {author.get('works_count')}")
print(
f"Publication page raw total: {page_total_value} ({page_total_relation})"
)
print(f"Publication page unique OpenAlex IDs: {len(unique_work_ids)}")
print(f"Pipeline-eligible unique IDs: {len(eligible_work_ids)}")
print(f"Classified by target document ID: {len(classified_by_id)}")
print(f"Eligible but missing in target: {len(unclassified_eligible)}")
print(f"Target documents containing this author: {classified_author_count}")
print(
f"Raw duplicate documents: {len(raw_hits) - len(unique_work_ids)}"
)
print(
f"Works before {args.work_year_gte}: {len(pre_threshold_work_ids)}"
)
print(f"Works with missing publication year: {len(missing_year_work_ids)}")
print()
print(f"Report: {json_path.resolve()}")
print(f"CSV files: {output_dir.resolve()}")
return 0
if __name__ == "__main__":
try:
raise SystemExit(main())
except KeyboardInterrupt:
print("\nInterrupted.", file=sys.stderr)
raise SystemExit(130)
except Exception as exc:
print(f"Error: {exc}", file=sys.stderr)
raise SystemExit(1)
@@ -0,0 +1,181 @@
{
"summary": {
"created_at": "2026-07-19T23:22:32.712141Z",
"index": "work-classifications",
"read_only": true,
"expected_count": null,
"documents": 183661,
"initial_count": 183661,
"final_count": 183661,
"count_consistent": true,
"expected_count_matches": true,
"index_integrity_valid": true
},
"mapping": {
"valid": true,
"error_count": 0,
"errors": []
},
"documents": {
"schema_valid": 183661,
"schema_invalid": 0,
"field_order_valid": 183661,
"field_order_invalid": 0,
"unique_work_ids": 183661,
"duplicate_work_id_count": 0,
"duplicate_work_ids": {},
"schema_error_counts": {},
"field_order_error_counts": {}
},
"classification": {
"categories": {
"basic_research": {
"count": 83310,
"percentage": 45.36
},
"applied_research": {
"count": 73026,
"percentage": 39.76
},
"non_research": {
"count": 14584,
"percentage": 7.94
},
"experimental_development": {
"count": 12741,
"percentage": 6.94
}
},
"quadrants": {
"pure_applied": {
"count": 85767,
"percentage": 46.7
},
"use_inspired_basic": {
"count": 54366,
"percentage": 29.6
},
"pure_basic": {
"count": 28944,
"percentage": 15.76
},
"not_applicable": {
"count": 14584,
"percentage": 7.94
}
},
"confidence": {
"high": {
"count": 113822,
"percentage": 61.97
},
"medium": {
"count": 68830,
"percentage": 37.48
},
"low": {
"count": 1009,
"percentage": 0.55
}
},
"insufficient_context": {
"false": {
"count": 173892,
"percentage": 94.68
},
"true": {
"count": 9769,
"percentage": 5.32
}
},
"signals_used": {
"topics": 181324,
"title": 179981,
"work_type": 175947,
"venue": 141807,
"abstract": 110404,
"funders": 38567,
"language": 6695,
"year": 85
},
"applied_orientation_score": {
"overall": {
"count": 169077,
"min": 0.0,
"max": 92.0,
"mean": 47.18,
"median": 50.0
},
"by_category": {
"applied_research": {
"count": 73026,
"min": 31.0,
"max": 70.0,
"mean": 62.08,
"median": 60.0
},
"basic_research": {
"count": 83310,
"min": 0.0,
"max": 45.0,
"mean": 28.74,
"median": 35.0
},
"experimental_development": {
"count": 12741,
"min": 75.0,
"max": 92.0,
"mean": 82.34,
"median": 80.0
},
"non_research": {
"count": 0,
"min": null,
"max": null,
"mean": null,
"median": null
}
}
},
"current_rule_consistency": {
"consistent": 183661,
"inconsistent": 0,
"consistent_percentage": 100.0,
"error_counts": {}
},
"stored_validation": {
"states": {
"valid": 183661
},
"valid_state_consistent_with_error_list": 183661,
"valid_state_inconsistent_with_error_list": 0,
"error_occurrences": 0,
"error_counts": {}
}
},
"metadata": {
"missing_title": 120,
"missing_doi": 18865,
"missing_publication_year": 0,
"empty_authors": 0,
"empty_institutions": 47038,
"empty_topics": 2233,
"publication_year": {
"min": 1950,
"max": 2026
},
"classified_at": {
"min": "2026-07-10T18:42:03Z",
"max": "2026-07-19T06:14:05Z"
}
},
"provenance": {
"models": {
"gemma4-e4b": 183661
},
"prompt_versions": {
"frascati_hard_ranges_v2": 141643,
"frascati_v1": 42018
}
}
}
@@ -0,0 +1,44 @@
{
"run_id": "20260718_080350_493424",
"started_at": "2026-07-18T08:03:50Z",
"finished_at": "2026-07-18T11:25:02Z",
"duration_seconds": 12070.563,
"status": "completed",
"error": null,
"parameters": {
"limit": 15000,
"workers": 25,
"model": "gemma4-e4b",
"prompt_version": "frascati_hard_ranges_v2",
"target_index": "work-classifications",
"bulk_batch_size": 200,
"state_storage": "memory_only",
"preflight_only": false
},
"classification": {
"llm_completed": 15000,
"valid": 15000,
"invalid": 0,
"categories": {
"experimental_development": 1037,
"basic_research": 6608,
"applied_research": 6062,
"non_research": 1293
},
"validation_errors": {}
},
"indexing": {
"newly_indexed": 15000,
"bulk_requests": 82,
"bulk_documents_submitted": 15350,
"bulk_failures": 0
},
"token_usage": {
"prompt_tokens": 56119646,
"cached_prompt_tokens": 51428736,
"uncached_prompt_tokens": 4690910,
"completion_tokens": 13741519,
"real_total_usage": 18432429
},
"throughput_indexed_per_hour": 4473.69
}
@@ -0,0 +1,50 @@
{
"run_id": "20260722_021910_049378",
"started_at": "2026-07-22T02:19:10Z",
"finished_at": "2026-07-22T09:26:37Z",
"duration_seconds": 25645.781,
"status": "completed",
"error": null,
"parameters": {
"limit": null,
"workers": 25,
"model": "gemma4-e4b",
"prompt_version": "frascati_hard_ranges_v2",
"target_index": "work-classifications",
"bulk_batch_size": 200,
"state_storage": "memory_only",
"preflight_only": false,
"selection_mode": "institution-works",
"institution_id": "https://openalex.org/I62318514",
"institution_ror": "https://ror.org/04mz5ra38",
"institution_name": "University of Duisburg-Essen",
"affiliation_year_gte": 2025,
"work_year_gte": 1950
},
"classification": {
"llm_completed": 32189,
"valid": 32189,
"invalid": 0,
"categories": {
"applied_research": 10001,
"basic_research": 17089,
"experimental_development": 1813,
"non_research": 3286
},
"validation_errors": {}
},
"indexing": {
"newly_indexed": 32189,
"bulk_requests": 183,
"bulk_documents_submitted": 32589,
"bulk_failures": 0
},
"token_usage": {
"prompt_tokens": 119788565,
"cached_prompt_tokens": 110500800,
"uncached_prompt_tokens": 9287765,
"completion_tokens": 29352270,
"real_total_usage": 38640035
},
"throughput_indexed_per_hour": 4518.5
}
@@ -0,0 +1,51 @@
{
"run_id": "20260723_154918_847690",
"started_at": "2026-07-23T15:49:18Z",
"finished_at": "2026-07-23T19:49:04Z",
"duration_seconds": 14385.39,
"status": "completed",
"error": null,
"parameters": {
"limit": null,
"workers": 25,
"model": "gemma4-e4b",
"prompt_version": "frascati_hard_ranges_v2",
"target_index": "work-classifications",
"bulk_batch_size": 200,
"state_storage": "memory_only",
"preflight_only": false,
"selection_mode": "author-cohort",
"institution_id": "https://openalex.org/I62318514",
"institution_ror": "https://ror.org/04mz5ra38",
"institution_name": "University of Duisburg-Essen",
"affiliation_year_gte": 2024,
"work_year_gte": 1950,
"all_work_years": false
},
"classification": {
"llm_completed": 16272,
"valid": 16272,
"invalid": 0,
"categories": {
"basic_research": 8658,
"applied_research": 4889,
"non_research": 1190,
"experimental_development": 1535
},
"validation_errors": {}
},
"indexing": {
"newly_indexed": 16272,
"bulk_requests": 148,
"bulk_documents_submitted": 16472,
"bulk_failures": 0
},
"token_usage": {
"prompt_tokens": 60051102,
"cached_prompt_tokens": 55752000,
"uncached_prompt_tokens": 4299102,
"completion_tokens": 14983831,
"real_total_usage": 19282933
},
"throughput_indexed_per_hour": 4072.13
}
@@ -0,0 +1,341 @@
from typing import Any, Iterator
from elasticsearch import Elasticsearch
from collections import defaultdict
import json
from pathlib import Path
from elasticsearch import NotFoundError
# elasticseach library required. Here used elasticsearch==8.0.0
# estimated execution time: 3-5 Minutes
def remove_year(patent_number: str) -> str:
"""Remove a leading 4-digit year from the front of a patent number, if present.
Only strips the first 4 characters when they are all digits (i.e. actually
look like a year). Otherwise the ID is returned unchanged.
"""
prefix = patent_number[:4]
if len(patent_number) > 4 and prefix.isdigit():
return patent_number[4:]
return patent_number
class PatentCounter:
def __init__(
self,
source_es: Elasticsearch,
target_es: Elasticsearch,
source_index: str,
results_file: str = "patent_matches.json",
):
self.source_es = source_es
self.target_es = target_es
self.source_index = source_index
self.results_file = Path(results_file)
self.match_stats = defaultdict(int)
def _build_variations_uspto(self, patent_id: str) -> dict[str, str]:
raw_id = patent_id.upper().removeprefix("US")
no_year = remove_year(raw_id)
return {
"publication_number": raw_id,
"publication_number_no_year": no_year,
"application_number": raw_id,
"application_number_no_year": no_year,
}
def _build_variations_epo(self, patent_id: str) -> dict[str, str]:
raw_id = patent_id.upper().removeprefix("EP")
no_year = remove_year(raw_id)
return {
"doc_number": raw_id,
"doc_number_no_year": no_year,
"application_number": raw_id,
"application_number_no_year": no_year,
}
def _uspto_query_by_id(
self,
patent_id: str,
size: int = 100,
) -> dict[str, Any]:
variations = self._build_variations_uspto(patent_id)
body = {
"size": size,
"track_total_hits": True,
"_source": [
"publication_number",
"application_number",
"title",
],
"query": {
"bool": {
"should": [
{"term": {"publication_number": variations["publication_number"]}},
{"term": {"publication_number": variations["publication_number_no_year"]}},
{"term": {"application_number": variations["application_number"]}},
{"term": {"application_number": variations["application_number_no_year"]}},
],
"minimum_should_match": 1,
}
},
}
#print(f"USPTO query for {patent_id}: {json.dumps(body)}") # Debugging line
return body
def _epo_query_by_id(
self,
patent_id: str,
size: int = 100,
) -> dict[str, Any]:
variations = self._build_variations_epo(patent_id)
body = {
"size": size,
"track_total_hits": True,
"_source": [
"doc_number",
"application_number",
"title_en",
"title_fr",
"title_de",
],
"query": {
"bool": {
"should": [
{"term": {"doc_number": variations["doc_number"]}},
{"term": {"application_number": variations["application_number"]}},
{"term": {"doc_number": variations["doc_number_no_year"]}},
{"term": {"application_number": variations["application_number_no_year"]}},
{"wildcard": {
"application_number": {
"value": f"{variations['application_number']}*"
}
}
},
],
"minimum_should_match": 1,
}
},
}
#print(f"EP query for {patent_id}: {json.dumps(body)}") # Debugging line
return body
def _scroll_all(self, query: dict) -> Iterator[dict]:
"""Run a scroll query to completion, yielding each hit's _source,
and always clearing the scroll context when done."""
resp = self.source_es.search(
index=self.source_index,
body=query,
scroll="5m",
size=10000,
)
scroll_id = resp.get("_scroll_id")
try:
while True:
hits = resp["hits"]["hits"]
if not hits:
break
for hit in hits:
yield hit["_source"]
try:
resp = self.source_es.scroll(scroll_id=scroll_id, scroll="5m")
scroll_id = resp.get("_scroll_id")
except NotFoundError:
break
finally:
if scroll_id:
try:
self.source_es.clear_scroll(scroll_id=scroll_id)
except Exception:
pass # best-effort cleanup, don't fail the run over this
def get_source_docs(self) -> Iterator[dict]:
"""
Yield source docs (with applicationIdentifier, applicationPrefix, title) in order:
1. All EP patents (applicationPrefix: "EP")
2. Then all USPTO patents (applicationPrefix: "US")
"""
query_ep = {
"_source": ["applicationIdentifier", "applicationPrefix", "title"],
"query": {"term": {"applicationPrefix": "EP"}},
}
query_us = {
"_source": ["applicationIdentifier", "applicationPrefix", "title"],
"query": {"term": {"applicationPrefix": "US"}},
}
for source in self._scroll_all(query_ep):
if source.get("applicationIdentifier"):
yield source
for source in self._scroll_all(query_us):
if source.get("applicationIdentifier"):
yield source
def find_matches(self, patent_id: str, source_prefix: str, source_title: str) -> dict:
"""Match a single source patent against the target indexes.
source_prefix/source_title are passed in from get_source_docs() rather
than being re-fetched here, avoiding a redundant query per record and
the IndexError that occurred when a fetch found no hits.
"""
variations_uspto = self._build_variations_uspto(patent_id)
variations_epo = self._build_variations_epo(patent_id)
raw_id_epo = patent_id.upper().removeprefix("EP")
matches = []
matched_indexes = set()
# EP PATENTS -> Only match in EPO index
if source_prefix == "EP":
epo_resp = self.target_es.search(
index="epo_index_1.0",
body=self._epo_query_by_id(patent_id),
)
epo_hits = epo_resp["hits"]["hits"]
for hit in epo_hits:
source = hit["_source"]
matched_field = None
if source.get("doc_number") == raw_id_epo:
matched_field = "doc_number"
elif source.get("doc_number") == variations_epo["doc_number_no_year"]:
matched_field = "doc_number_no_year"
matched_field_app = None
if source.get("application_number") == raw_id_epo:
matched_field_app = "application_number"
elif source.get("application_number") == variations_epo["application_number_no_year"]:
matched_field_app = "application_number_no_year"
elif source.get("application_number", "").startswith(variations_epo["application_number"]):
matched_field_app = "application_number_wildcard"
matched_fields = [f for f in (matched_field, matched_field_app) if f]
for field in matched_fields:
self.match_stats[f"epo:{field}"] += 1
all_ids = {
"doc_number": source.get("doc_number"),
"application_number": source.get("application_number"),
}
matches.append({
"index": "epo_index_1.0",
"field": field,
"doc_id": hit["_id"],
"title_en": source.get("title_en"),
"title_fr": source.get("title_fr"),
"title_de": source.get("title_de"),
"all_ids": all_ids,
})
if epo_hits:
matched_indexes.add("epo_index_1.0")
# US PATENTS -> Only match in USPTO index
elif source_prefix == "US":
uspto_resp = self.target_es.search(
index="uspto_patents_3.0",
body=self._uspto_query_by_id(patent_id),
)
uspto_hits = uspto_resp["hits"]["hits"]
for hit in uspto_hits:
source = hit["_source"]
pub = source.get("publication_number")
app = source.get("application_number")
matched_field_pub = None
if pub == variations_uspto["publication_number"]:
matched_field_pub = "publication_number"
elif pub == variations_uspto["publication_number_no_year"]:
matched_field_pub = "publication_number_no_year"
matched_field_app = None
if app == variations_uspto["application_number"]:
matched_field_app = "application_number"
elif app == variations_uspto["application_number_no_year"]:
matched_field_app = "application_number_no_year"
matched_fields = [f for f in (matched_field_pub, matched_field_app) if f]
for field in matched_fields:
self.match_stats[f"uspto:{field}"] += 1
matches.append({
"index": "uspto_patents_3.0",
"field": field,
"doc_id": hit["_id"],
"title": source.get("title"),
})
if uspto_hits:
matched_indexes.add("uspto_patents_3.0")
return {
"source_id": patent_id,
"source_prefix": source_prefix,
"source_title": source_title,
"found": len(matches) > 0,
"matches": matches,
"not_found_in": [
idx for idx in ("epo_index_1.0", "uspto_patents_3.0")
if idx not in matched_indexes
],
}
def count_matches(self):
total = 0
matched = 0
all_results = []
for source_doc in self.get_source_docs():
patent_id = source_doc["applicationIdentifier"]
source_prefix = source_doc.get("applicationPrefix", "")
source_title = source_doc.get("title", "")
total += 1
result = self.find_matches(patent_id, source_prefix, source_title)
if result["found"]:
matched += 1
all_results.append(result)
if total % 1000 == 0:
print(f"Processed={total:,}, Matched={matched:,}")
with open(self.results_file, "w") as f:
json.dump(all_results, f, indent=2)
# Final save
with open(self.results_file, "w") as f:
json.dump(all_results, f, indent=2)
return total, matched
if __name__ == "__main__":
source_es = Elasticsearch('https://inse.nes.uni-due.de:443/elastic', basic_auth=('elastic', 'RLldUaJgbGeoqd3KCX3p'), request_timeout=60, max_retries=5, retry_on_timeout=True)
counter = PatentCounter(
source_es=source_es,
target_es=source_es,
source_index="cordis_eu_fp7_project_iprs",
results_file="patent_matches.json",
)
total, matched = counter.count_matches()
print(f"Total IDs: {total:,}")
print(f"Matched source IDs: {matched:,}")
print(f"Not found: {total - matched:,}")
print("\nMatch statistics:")
for key, count in sorted(counter.match_stats.items()):
print(f"{key}: {count:,}")
@@ -0,0 +1,78 @@
Here’s a shorter, more concise version:
# Patent Matching Pipeline — CORDIS FP7 IPR Records ↔ EPO / USPTO
## Purpose
This pipeline validates FP7 patent records from CORDIS against external patent databases:
- **EPO index (`epo_index_1.0`)** for `EP` patents
- **USPTO index (`uspto_patents_3.0`)** for `US` patents
The objective is to measure match coverage and determine which ID-matching strategies are reliable for downstream patent linking.
## Dataset
Source: `cordis_eu_fp7_project_iprs`
Patents tested: 5196(total) - 2270(others) -> 2926 (EP and US patents)
| Prefix | Count |
| --------- | --------: |
| EP | 1,952 |
| US | 974 |
| **Total** | **2,926** |
## Matching Strategies
### EPO
- `doc_number`: exact, no-year
- `application_number`: exact, no-year, wildcard (`{id}*`)
### USPTO
- `application_number`: exact, no-year
- `publication_number`: exact, no-year
Matching priority: **exact → no-year → wildcard** (first match wins).
## Results
| Metric | Count |
| ----------- | ----: |
| Total IDs | 2,926 |
| Matched IDs | 1,713 |
| Not Found | 1,213 |
### Match Counts by Field
| Field | Hits |
| ---------------------------------- | ----: |
| `epo:application_number_wildcard` | 1,864 |
| `epo:doc_number` | 7 |
| `uspto:application_number_no_year` | 564 |
| `uspto:application_number` | 6 |
No matches were found for:
- `epo:application_number` (exact/no-year)
- `epo:doc_number_no_year`
- `uspto:publication_number` (exact/no-year)
## Findings
### EPO
| Strategy | Assessment |
| ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| `doc_number` | ❌ Unreliable; often matches unrelated patents |
| `application_number` exact/no-year | ⚠️ No matches |
| `application_number` wildcard (APPROVED) | ⚠️ Best coverage (1,864 hits) but over-matches related filings; requires secondary validation (e.g., title similarity) |
### USPTO
| Strategy | Assessment |
| --------------------------------------- | --------------------------------------- |
| `application_number` exact | ❌ Unreliable; numbering formats differ |
| `application_number_no_year` (APPROVED) | ✅ Reliable (564 matches) |
| `publication_number` | No useful matches |
File diff suppressed because it is too large Load Diff
@@ -0,0 +1 @@
Perhaps not the final version. I did not find the files inside my local git branch. I most likely did not save them, however i made backups sometimes, so i hope these versions are the final ones.
@@ -0,0 +1,428 @@
#!/usr/bin/env python3
import os
import sys
import json
import time
import asyncio
from pathlib import Path
import httpx
import numpy as np
# Load service environment config
current_dir = Path(__file__).parent.resolve()
project_root = current_dir.parent.parent.resolve()
env_path = project_root / "service" / "src" / "main" / "inse" / ".env"
from dotenv import load_dotenv
load_dotenv(dotenv_path=env_path)
sys.path.append(str(project_root / "service" / "src" / "main"))
from inse.config import settings
from inse.util import get_model
ELASTIC_URL = settings.elasticsearch_url
if ELASTIC_URL and not ELASTIC_URL.endswith("/"):
ELASTIC_URL += "/"
API_KEY = settings.elasticsearch_api_key
headers = {
"Authorization": f"ApiKey {API_KEY}",
"Content-Type": "application/json"
}
FIELDS = [
"Social Sciences", "Medicine", "Engineering", "Computer Science",
"Arts and Humanities", "Biochemistry, Genetics and Molecular Biology",
"Agricultural and Biological Sciences", "Environmental Science",
"Business, Management and Accounting", "Psychology", "Materials Science",
"Economics, Econometrics and Finance", "Health Professions",
"Physics and Astronomy", "Chemistry", "Mathematics", "Neuroscience",
"Decision Sciences", "Earth and Planetary Sciences", "Immunology and Microbiology",
"Energy", "Pharmacology, Toxicology and Pharmaceutics", "Nursing",
"Chemical Engineering", "Dentistry", "Veterinary"
]
QUERIES_FILE = current_dir / "evaluation_queries.json"
def load_queries():
if QUERIES_FILE.exists():
print(f"Loading cached queries from {QUERIES_FILE}...")
with open(QUERIES_FILE, "r", encoding="utf-8") as f:
return json.load(f)
else:
raise FileNotFoundError(f"Evaluation queries file not found at {QUERIES_FILE}")
def make_es_payload(query_vector, query_str, config_type, limit=10):
if config_type == "display_name":
clause = {
"knn": {
"field": "display_name_vector",
"query_vector": query_vector,
"k": limit,
"num_candidates": 100,
"similarity": 0.62
}
}
query_body = {"query": clause}
elif config_type == "description":
clause = {
"knn": {
"field": "description_vector",
"query_vector": query_vector,
"k": limit,
"num_candidates": 100,
"similarity": 0.62
}
}
query_body = {"query": clause}
elif config_type == "keywords":
clause = {
"nested": {
"path": "keyword_vectors",
"query": {
"knn": {
"field": "keyword_vectors.vector",
"query_vector": query_vector,
"k": limit,
"num_candidates": 100,
"similarity": 0.62
}
},
"score_mode": "max"
}
}
query_body = {"query": clause}
elif config_type == "display_name_and_keywords":
query_body = {
"query": {
"bool": {
"should": [
{
"knn": {
"field": "display_name_vector",
"query_vector": query_vector,
"k": limit,
"num_candidates": 100,
"similarity": 0.62
}
},
{
"nested": {
"path": "keyword_vectors",
"query": {
"knn": {
"field": "keyword_vectors.vector",
"query_vector": query_vector,
"k": limit,
"num_candidates": 100,
"similarity": 0.62
}
},
"score_mode": "max"
}
}
]
}
}
}
elif config_type == "display_name_and_description":
query_body = {
"query": {
"bool": {
"should": [
{
"knn": {
"field": "display_name_vector",
"query_vector": query_vector,
"k": limit,
"num_candidates": 100,
"similarity": 0.62
}
},
{
"knn": {
"field": "description_vector",
"query_vector": query_vector,
"k": limit,
"num_candidates": 100,
"similarity": 0.62
}
}
]
}
}
}
elif config_type == "combined":
query_body = {
"query": {
"bool": {
"should": [
{
"knn": {
"field": "display_name_vector",
"query_vector": query_vector,
"k": limit,
"num_candidates": 100,
"similarity": 0.62
}
},
{
"knn": {
"field": "description_vector",
"query_vector": query_vector,
"k": limit,
"num_candidates": 100,
"similarity": 0.62
}
},
{
"nested": {
"path": "keyword_vectors",
"query": {
"knn": {
"field": "keyword_vectors.vector",
"query_vector": query_vector,
"k": limit,
"num_candidates": 100,
"similarity": 0.62
}
},
"score_mode": "max"
}
}
]
}
}
}
elif config_type == "lexical_only":
query_body = {
"query": {
"multi_match": {
"query": query_str,
"fields": ["display_name^3", "keywords^2", "description^1"]
}
}
}
elif config_type == "hybrid":
query_body = {
"query": {
"bool": {
"should": [
{
"multi_match": {
"query": query_str,
"fields": ["display_name^3", "keywords^2", "description^1"]
}
},
{
"knn": {
"field": "display_name_vector",
"query_vector": query_vector,
"k": limit,
"num_candidates": 100,
"similarity": 0.62
}
},
{
"knn": {
"field": "description_vector",
"query_vector": query_vector,
"k": limit,
"num_candidates": 100,
"similarity": 0.62
}
},
{
"nested": {
"path": "keyword_vectors",
"query": {
"knn": {
"field": "keyword_vectors.vector",
"query_vector": query_vector,
"k": limit,
"num_candidates": 100,
"similarity": 0.62
}
},
"score_mode": "max"
}
}
]
}
}
}
else:
raise ValueError(f"Unknown config_type: {config_type}")
query_body["_source"] = {
"excludes": ["display_name_vector", "description_vector", "keyword_vectors", "description"]
}
query_body["size"] = limit
return query_body
async def evaluate():
queries_by_field = load_queries()
# 1. Warm up model and connection
print("\nWarming up model and Elasticsearch connection...")
model = get_model()
model.encode("warmup search term")
# Run a dummy check on ES
dummy_vector = [0.1] * 768
dummy_payload = make_es_payload(dummy_vector, "warmup search term", "display_name")
try:
with httpx.Client(timeout=10.0) as client:
client.post(f"{ELASTIC_URL}topicvectors/_search", json=dummy_payload, headers=headers)
print("Warmup complete.")
except Exception as exc:
print(f"Warmup query failed: {exc}")
results = []
print("\nRunning comprehensive latency evaluation on 520 queries...")
query_count = 0
config_list = [
"display_name", "description", "keywords",
"display_name_and_keywords", "display_name_and_description",
"combined", "lexical_only", "hybrid"
]
with httpx.Client(timeout=30.0) as client:
for field, queries in queries_by_field.items():
for q in queries:
query_count += 1
if query_count % 50 == 0:
print(f"Processed {query_count} / 520 queries...")
# Measure encoding latency
t0 = time.perf_counter()
query_vector = model.encode(q).tolist()
t1 = time.perf_counter()
encode_time = (t1 - t0) * 1000.0 # ms
latencies = {}
# Benchmark each configuration
for config in config_list:
payload = make_es_payload(query_vector, q, config)
t0 = time.perf_counter()
try:
resp = client.post(f"{ELASTIC_URL}topicvectors/_search", json=payload, headers=headers)
resp.raise_for_status()
except Exception as exc:
# Log error but don't crash
pass
t1 = time.perf_counter()
latencies[config] = (t1 - t0) * 1000.0 # ms
results.append({
"query": q,
"field": field,
"encode_latency_ms": encode_time,
"display_name_latency_ms": latencies.get("display_name", 0.0),
"description_latency_ms": latencies.get("description", 0.0),
"keywords_latency_ms": latencies.get("keywords", 0.0),
"display_name_and_keywords_latency_ms": latencies.get("display_name_and_keywords", 0.0),
"display_name_and_description_latency_ms": latencies.get("display_name_and_description", 0.0),
"combined_latency_ms": latencies.get("combined", 0.0),
"lexical_only_latency_ms": latencies.get("lexical_only", 0.0),
"hybrid_latency_ms": latencies.get("hybrid", 0.0)
})
# Calculate global stats
encode_l = [r["encode_latency_ms"] for r in results]
display_name_l = [r["display_name_latency_ms"] for r in results]
description_l = [r["description_latency_ms"] for r in results]
keywords_l = [r["keywords_latency_ms"] for r in results]
display_name_and_keywords_l = [r["display_name_and_keywords_latency_ms"] for r in results]
display_name_and_description_l = [r["display_name_and_description_latency_ms"] for r in results]
combined_l = [r["combined_latency_ms"] for r in results]
lexical_only_l = [r["lexical_only_latency_ms"] for r in results]
hybrid_l = [r["hybrid_latency_ms"] for r in results]
summary = {
"total_queries": len(results),
"encode": {
"mean": np.mean(encode_l), "median": np.median(encode_l),
"p90": np.percentile(encode_l, 90), "p95": np.percentile(encode_l, 95)
},
"display_name": {
"mean": np.mean(display_name_l), "median": np.median(display_name_l),
"p90": np.percentile(display_name_l, 90), "p95": np.percentile(display_name_l, 95)
},
"description": {
"mean": np.mean(description_l), "median": np.median(description_l),
"p90": np.percentile(description_l, 90), "p95": np.percentile(description_l, 95)
},
"keywords": {
"mean": np.mean(keywords_l), "median": np.median(keywords_l),
"p90": np.percentile(keywords_l, 90), "p95": np.percentile(keywords_l, 95)
},
"display_name_and_keywords": {
"mean": np.mean(display_name_and_keywords_l), "median": np.median(display_name_and_keywords_l),
"p90": np.percentile(display_name_and_keywords_l, 90), "p95": np.percentile(display_name_and_keywords_l, 95)
},
"display_name_and_description": {
"mean": np.mean(display_name_and_description_l), "median": np.median(display_name_and_description_l),
"p90": np.percentile(display_name_and_description_l, 90), "p95": np.percentile(display_name_and_description_l, 95)
},
"combined": {
"mean": np.mean(combined_l), "median": np.median(combined_l),
"p90": np.percentile(combined_l, 90), "p95": np.percentile(combined_l, 95)
},
"lexical_only": {
"mean": np.mean(lexical_only_l), "median": np.median(lexical_only_l),
"p90": np.percentile(lexical_only_l, 90), "p95": np.percentile(lexical_only_l, 95)
},
"hybrid": {
"mean": np.mean(hybrid_l), "median": np.median(hybrid_l),
"p90": np.percentile(hybrid_l, 90), "p95": np.percentile(hybrid_l, 95)
}
}
# Save full report to json
report_json_path = current_dir / "evaluation_report.json"
with open(report_json_path, "w", encoding="utf-8") as f:
json.dump({"summary": summary, "results": results}, f, indent=2, ensure_ascii=False)
print(f"\nSaved detailed JSON report to {report_json_path}")
# Generate and save markdown report
md_report_path = current_dir / "evaluation_report.md"
md_content = f"""# Vector Search Configuration Latency Report
Generated on: {time.strftime('%Y-%m-%d %H:%M:%S')}
This report documents the latency breakdown for different Elasticsearch query configurations across 520 queries, measuring flat vector searches, nested searches, multi-field combinations, pure lexical searches, and full hybrid queries.
## Latency Summary Table (ms)
| Query Configuration | Mean | Median | p90 | p95 |
| :--- | :---: | :---: | :---: | :---: |
| **Embedding Encode** | {summary["encode"]["mean"]:.2f} | {summary["encode"]["median"]:.2f} | {summary["encode"]["p90"]:.2f} | {summary["encode"]["p95"]:.2f} |
| **Pure Lexical Search (`multi_match`)** | {summary["lexical_only"]["mean"]:.2f} | {summary["lexical_only"]["median"]:.2f} | {summary["lexical_only"]["p90"]:.2f} | {summary["lexical_only"]["p95"]:.2f} |
| **Description Only (`description_vector`)** | {summary["description"]["mean"]:.2f} | {summary["description"]["median"]:.2f} | {summary["description"]["p90"]:.2f} | {summary["description"]["p95"]:.2f} |
| **Display Name Only (`display_name_vector`)** | {summary["display_name"]["mean"]:.2f} | {summary["display_name"]["median"]:.2f} | {summary["display_name"]["p90"]:.2f} | {summary["display_name"]["p95"]:.2f} |
| **Keywords Only (`keyword_vectors` - Nested)** | {summary["keywords"]["mean"]:.2f} | {summary["keywords"]["median"]:.2f} | {summary["keywords"]["p90"]:.2f} | {summary["keywords"]["p95"]:.2f} |
| **Display Name & Description** | {summary["display_name_and_description"]["mean"]:.2f} | {summary["display_name_and_description"]["median"]:.2f} | {summary["display_name_and_description"]["p90"]:.2f} | {summary["display_name_and_description"]["p95"]:.2f} |
| **Display Name & Keywords (Nested)** | {summary["display_name_and_keywords"]["mean"]:.2f} | {summary["display_name_and_keywords"]["median"]:.2f} | {summary["display_name_and_keywords"]["p90"]:.2f} | {summary["display_name_and_keywords"]["p95"]:.2f} |
| **Combined (All 3 vector fields)** | {summary["combined"]["mean"]:.2f} | {summary["combined"]["median"]:.2f} | {summary["combined"]["p90"]:.2f} | {summary["combined"]["p95"]:.2f} |
| **Hybrid Search (Lexical + All 3 vector fields)** | {summary["hybrid"]["mean"]:.2f} | {summary["hybrid"]["median"]:.2f} | {summary["hybrid"]["p90"]:.2f} | {summary["hybrid"]["p95"]:.2f} |
---
## 💡 Latency Bottleneck & Configuration Analysis
1. **Lexical Baseline**: **Pure Lexical Search** has extremely low latency (mean: **{summary["lexical_only"]["mean"]:.2f} ms**), representing standard BM25 keyword matching speed.
2. **Impact of Nested Fields**:
- Compares **Keywords Only (Nested)** (mean: **{summary["keywords"]["mean"]:.2f} ms**) with **Description Only (Flat)** (mean: **{summary["description"]["mean"]:.2f} ms**).
- Combining Display Name with the flat Description (**Display Name & Description**: **{summary["display_name_and_description"]["mean"]:.2f} ms**) is faster than combining Display Name with nested Keywords (**Display Name & Keywords**: **{summary["display_name_and_keywords"]["mean"]:.2f} ms**), demonstrating that nested vector joins add a steady latency premium.
3. **Compound Parallel Execution**:
- Adding lexical queries to the 3 combined vector queries (**Hybrid Search**: **{summary["hybrid"]["mean"]:.2f} ms**) introduces virtually no latency overhead compared to **Combined** vector-only search (mean: **{summary["combined"]["mean"]:.2f} ms**), proving that standard lexical match is executed concurrently with HNSW vector retrieval.
"""
with open(md_report_path, "w", encoding="utf-8") as f:
f.write(md_content)
print(f"Saved Markdown report summary to {md_report_path}")
if __name__ == "__main__":
asyncio.run(evaluate())
@@ -0,0 +1,392 @@
#!/usr/bin/env python3
"""
Professional evaluation pipeline to benchmark different Sentence Transformer models
on the OpenAlex topics dataset. Measures Information Retrieval (IR) metrics,
Taxonomy Clustering metrics, and operational performance metrics.
"""
import os
import sys
import json
import time
import argparse
import random
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
# Import evaluation libraries
from sentence_transformers import SentenceTransformer
from sentence_transformers.evaluation import InformationRetrievalEvaluator
from sklearn.cluster import KMeans
from sklearn import metrics
DEFAULT_MODELS = [
"paraphrase-multilingual-mpnet-base-v2",
"BAAI/bge-m3",
"google/embeddinggemma-300m",
"intfloat/multilingual-e5-small",
"intfloat/multilingual-e5-base",
"intfloat/multilingual-e5-large",
"sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2",
#english
"sentence-transformers/all-MiniLM-L6-v2",
"intfloat/e5-large-v2",
"BAAI/bge-large-en-v1.5"
]
def fetch_all_topics():
topics = []
size = 1000
offset = 0
headers = {
"Authorization": f"ApiKey {API_KEY}",
"Content-Type": "application/json"
}
with httpx.Client(timeout=60.0) as client:
while True:
payload = {
"query": {"match_all": {}},
"from": offset,
"size": size
}
resp = client.post(
f"{ELASTIC_URL.rstrip('/')}/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...")
if len(hits) < size:
break
print(f"Total topics loaded: {len(topics)}")
return topics
def prepare_data(topics, sample_size=None):
"""
Formulate the IR dataset and clustering taxonomy ground truth labels.
"""
corpus = {}
queries = {}
relevant_docs = {}
# Clustering labels
topic_ids = []
names_for_clustering = []
descriptions_for_clustering = []
labels_subfield = []
labels_field = []
labels_domain = []
# Build complete corpus dictionary of documents
for t in topics:
source = t["_source"]
doc_id = source["id"]
display_name = source.get("display_name") or ""
description = source.get("description") or ""
doc_text = f"{display_name} {description}".strip()
corpus[doc_id] = doc_text
# Taxonomy labels
topic_ids.append(doc_id)
names_for_clustering.append(display_name.strip())
descriptions_for_clustering.append(description.strip())
labels_subfield.append(source.get("subfield", {}).get("id") or "unknown_subfield")
labels_field.append(source.get("field", {}).get("id") or "unknown_field")
labels_domain.append(source.get("domain", {}).get("id") or "unknown_domain")
sampled_topics = topics
if sample_size and sample_size < len(topics):
print(f"Sampling {sample_size} topics for query/keyword generation...")
sampled_topics = random.sample(topics, sample_size)
query_count = 0
for t in sampled_topics:
source = t["_source"]
doc_id = source["id"]
keywords = source.get("keywords") or []
for keyword in keywords:
if not keyword.strip():
continue
query_id = f"q_{query_count}"
queries[query_id] = keyword
# Ground truth relevant documents: topic name
rel_docs = {doc_id}
relevant_docs[query_id] = rel_docs
query_count += 1
print(f"Dataset Formulated: {len(corpus)} corpus documents, {len(queries)} queries.")
return {
"corpus": corpus,
"queries": queries,
"relevant_docs": relevant_docs,
"clustering": {
"ids": topic_ids,
"names": names_for_clustering,
"descriptions": descriptions_for_clustering,
"subfield": labels_subfield,
"field": labels_field,
"domain": labels_domain
}
}
def evaluate_model(model_name, data, output_dir):
"""
Load a model, measure operational speed, and calculate IR + clustering quality.
"""
model_safe_name = model_name.replace("/", "_").replace("-", "_")
report_file = output_dir / f"model_report_{model_safe_name}.json"
print(f"\n==================================================")
print(f"Evaluating Model: '{model_name}'")
print(f"==================================================")
start_load = time.time()
try:
model = SentenceTransformer(model_name)
except Exception as exc:
print(f"ERROR: Failed to load model '{model_name}': {exc}")
return None
load_time = time.time() - start_load
print(f"Model loaded in {load_time:.2f} seconds.")
num_params = sum(p.numel() for p in model.parameters())
param_count_m = num_params / 1_000_000
vector_dim = model.get_sentence_embedding_dimension()
print(f"Parameters: {param_count_m:.1f}M, Vector Dimension: {vector_dim}")
# --- FIXED: Perform a warm-up to initialize computation graphs ---
print("Warming up model...")
_ = model.encode(["warmup sentence"])
# 2. Measure Query Latency
sample_queries = list(data["queries"].values())[:100]
if not sample_queries:
sample_queries = ["artificial intelligence", "machine learning"]
start_lat = time.time()
for q in sample_queries:
_ = model.encode(q)
latency_ms = ((time.time() - start_lat) / len(sample_queries)) * 1000
print(f"Average Query Latency: {latency_ms:.2f} ms")
# 3. Measure Ingestion Throughput
sample_docs = list(data["corpus"].values())[:200]
start_batch = time.time()
_ = model.encode(sample_docs, batch_size=32)
batch_time = time.time() - start_batch
throughput_docs_sec = len(sample_docs) / batch_time
print(f"Ingestion Throughput: {throughput_docs_sec:.2f} docs/sec")
# 4. Information Retrieval Evaluation
print("Running Information Retrieval evaluation (NDCG, MRR, Recall)...")
# --- FIXED: Use precision_recall_at_k for true recall metrics ---
evaluator = InformationRetrievalEvaluator(
data["queries"],
data["corpus"],
data["relevant_docs"], # The evaluator natively accepts sets, no need to cast to lists
name=model_safe_name,
mrr_at_k=[10],
ndcg_at_k=[10],
precision_recall_at_k=[10] # This ensures true Recall is calculated across multiple sibling matches
)
ir_results = evaluator(model)
# Extract keys safely
ndcg_key = f"{model_safe_name}_cosine_ndcg@10"
mrr_key = f"{model_safe_name}_cosine_mrr@10"
recall_key = f"{model_safe_name}_cosine_recall@10" # Changed from accuracy to recall
ndcg_score = ir_results.get(ndcg_key, 0.0)
mrr_score = ir_results.get(mrr_key, 0.0)
recall_score = ir_results.get(recall_key, 0.0)
print(f"NDCG@10: {ndcg_score:.4f}, MRR@10: {mrr_score:.4f}, Recall@10: {recall_score:.4f}")
# 5. Clustering evaluation against ground-truth taxonomy
print("Running Taxonomy Clustering evaluation (NMI)...")
unique_subfields = list(set(data["clustering"]["subfield"]))
n_clusters = len(unique_subfields)
# Topic Names Clustering
print("Clustering Topic Names...")
clustering_names = data["clustering"]["names"]
name_embeddings = model.encode(clustering_names, show_progress_bar=False, batch_size=64)
nmi_name = 0.0
ari_name = 0.0
if n_clusters > 1 and len(name_embeddings) > n_clusters:
kmeans_name = KMeans(n_clusters=n_clusters, random_state=42, n_init='auto')
assignments_name = kmeans_name.fit_predict(name_embeddings)
nmi_name = metrics.normalized_mutual_info_score(data["clustering"]["subfield"], assignments_name)
ari_name = metrics.adjusted_rand_score(data["clustering"]["subfield"], assignments_name)
print(f"Names - Subfield Clustering NMI: {nmi_name:.4f}, ARI: {ari_name:.4f}")
# Topic Descriptions Clustering
print("Clustering Topic Descriptions...")
clustering_descs = data["clustering"]["descriptions"]
desc_embeddings = model.encode(clustering_descs, show_progress_bar=False, batch_size=64)
nmi_desc = 0.0
ari_desc = 0.0
if n_clusters > 1 and len(desc_embeddings) > n_clusters:
kmeans_desc = KMeans(n_clusters=n_clusters, random_state=42, n_init='auto')
assignments_desc = kmeans_desc.fit_predict(desc_embeddings)
nmi_desc = metrics.normalized_mutual_info_score(data["clustering"]["subfield"], assignments_desc)
ari_desc = metrics.adjusted_rand_score(data["clustering"]["subfield"], assignments_desc)
print(f"Descriptions - Subfield Clustering NMI: {nmi_desc:.4f}, ARI: {ari_desc:.4f}")
report = {
"model_name": model_name,
"parameters_m": param_count_m,
"vector_dim": vector_dim,
"latency_ms": latency_ms,
"throughput_docs_sec": throughput_docs_sec,
"ndcg_at_10": ndcg_score,
"mrr_at_10": mrr_score,
"recall_at_10": recall_score,
"name_nmi": nmi_name,
"name_ari": ari_name,
"desc_nmi": nmi_desc,
"desc_ari": ari_desc
}
with open(report_file, "w", encoding="utf-8") as f:
json.dump(report, f, indent=2, ensure_ascii=False)
print(f"Saved model report to {report_file}")
return report
def generate_consolidated_report(output_dir, reports):
if not reports:
print("No reports to consolidate.")
return
report_file = output_dir / "model_evaluation_report.md"
print(f"\nCompiling consolidated report into {report_file}...")
sorted_reports = sorted(reports, key=lambda x: x["ndcg_at_10"], reverse=True)
lines = [
"# Sentence Transformer Model Evaluation Report",
"",
"This report aggregates performance metrics and accuracy benchmarks for different Sentence Transformer models evaluated against the OpenAlex topic keywords dataset.",
"",
"## Overall Leaderboard",
"",
"| Rank | Model Name | Vector Dim | Params (M) | Query Latency (ms) | Throughput (docs/s) | NDCG@10 | MRR@10 | Recall@10 | Name NMI | Desc NMI |",
"| :--- | :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |"
]
for idx, r in enumerate(sorted_reports):
name_nmi = r.get("name_nmi", 0.0)
desc_nmi = r.get("desc_nmi", 0.0)
lines.append(
f"| {idx+1} | `{r['model_name']}` | {r['vector_dim']} | {r['parameters_m']:.1f}M | {r['latency_ms']:.2f}ms | {r['throughput_docs_sec']:.1f} | **{r['ndcg_at_10']:.4f}** | {r['mrr_at_10']:.4f} | {r['recall_at_10']:.4f} | {name_nmi:.4f} | {desc_nmi:.4f} |"
)
lines.extend([
"",
"### Metric Definitions:",
"* **NDCG@10**: Normalized Discounted Cumulative Gain. Measures how well the query maps to the target topic at the top 10 positions.",
"* **MRR@10**: Mean Reciprocal Rank. Looks at the average of `1 / rank` for the first correctly matched topic.",
"* **Recall@10**: Percentage of times the target document (excluding sibling topics) was successfully retrieved in the top 10.",
"* **Name NMI**: Normalized Mutual Information of K-Means clusters of topic display names against ground truth OpenAlex subfields.",
"* **Desc NMI**: Normalized Mutual Information of K-Means clusters of topic descriptions against ground truth OpenAlex subfields.",
"* **Query Latency**: Time to encode a single search keyword.",
"* **Throughput**: Ingestion batch encoding speed."
])
with open(report_file, "w", encoding="utf-8") as f:
f.write("\n".join(lines))
print(f"Report compiled successfully at {report_file}")
def main():
parser = argparse.ArgumentParser(description="Evaluate Sentence Transformer models on OpenAlex topics.")
parser.add_argument("--model", type=str, help="Specific model to evaluate (skips others).")
parser.add_argument("--sample-size", type=int, help="Sample size of topics to evaluate keywords for (faster run).")
parser.add_argument("--all", action="store_true", help="Evaluate all topics/keywords (default if sample-size omitted).")
parser.add_argument("--output-dir", type=str, help="Custom directory to save reports.")
parser.add_argument("--force-refresh", action="store_true", help="Force reload topics from Elasticsearch instead of cache.")
args = parser.parse_args()
if Path("/data").is_dir():
data_dir = Path("/data")
else:
project_root = Path(__file__).parent.parent.parent.parent.parent.resolve()
data_dir = project_root / "service" / "src" / "data"
data_dir.mkdir(parents=True, exist_ok=True)
output_dir = Path(args.output_dir) if args.output_dir else data_dir
output_dir.mkdir(parents=True, exist_ok=True)
cache_file = data_dir / "raw_topics_cache.json"
if cache_file.exists() and not args.force_refresh:
print(f"Loading topics from local cache: {cache_file}")
with open(cache_file, "r", encoding="utf-8") as f:
topics = json.load(f)
else:
topics = fetch_all_topics()
with open(cache_file, "w", encoding="utf-8") as f:
json.dump(topics, f, indent=2, ensure_ascii=False)
print(f"Cached {len(topics)} topics to {cache_file}")
if not topics:
print("Error: No topics dataset available. Make sure Elasticsearch is running or cache exists.")
sys.exit(1)
data = prepare_data(topics, sample_size=args.sample_size)
models_to_evaluate = DEFAULT_MODELS
if args.model:
models_to_evaluate = [args.model]
print(f"Models scheduled for evaluation: {models_to_evaluate}")
reports = []
for m in models_to_evaluate:
model_safe_name = m.replace("/", "_").replace("-", "_")
report_file = output_dir / f"model_report_{model_safe_name}.json"
if report_file.exists() and not args.model:
print(f"Loading cached evaluation report for '{m}' from {report_file}")
with open(report_file, "r", encoding="utf-8") as f:
reports.append(json.load(f))
else:
rep = evaluate_model(m, data, output_dir)
if rep:
reports.append(rep)
generate_consolidated_report(output_dir, reports)
if __name__ == "__main__":
main()
@@ -0,0 +1,159 @@
# Performance Summary
520 Keywords as query against hybrid & semantic search
- Search fields:
- display name (Keyword & single vector)
- description (Keyword & single vector)
- keywords (Keyword & nested vectors)
- 26 Fields: 20 examples each
| # | OpenAlex Field Name | Complete Test Queries |
|---|---------------------|-----------------------------------------|
| 01 | **Social Sciences** | `sociology, gender inequality in workplace, urbanization trends, political polarization, human rights law, social mobility, qualitative research methods, demographic shifts, cultural anthropology, criminal justice reform, public policy analysis, indigenous languages, voter behavior, globalization effects, community development, media studies, social movements, migration patterns, welfare systems, family dynamics` |
| 02 | **Medicine** | `cardiology, diabetes management, oncology treatment options, clinical trials, pediatric care, chronic pain relief, cardiovascular disease prevention, surgical procedures, infectious disease outbreak, medical imaging techniques, hypertension guidelines, patient outcomes, immunotherapy for cancer, epidemiology study, stroke rehabilitation, genetic disorders, telemedicine adoption, internal medicine, diagnostic accuracy, palliative care` |
| 03 | **Engineering** | `civil engineering, structural integrity, aerospace propulsion, mechanical design, robotics automation, geotechnical analysis, bridge construction, renewable energy grid, fluid mechanics, electrical circuits, thermodynamics applications, manufacturing optimization, control systems engineering, materials fatigue, hvac design, biomedical devices, transportation infrastructure, signal processing, solid mechanics, industrial engineering` |
| 04 | **Computer Science** | `machine learning, natural language processing, cybersecurity protocols, cloud computing architecture, neural networks, database optimization, software engineering practices, computer vision algorithms, blockchain technology, artificial intelligence ethics, human computer interaction, operating systems, distributed ledgers, compiler design, data mining techniques, cryptographic keys, quantum computing algorithms, web development frameworks, reinforcement learning, graph databases` |
| 05 | **Arts and Humanities** | `art history, literary criticism, philosophy of mind, renaissance architecture, linguistics morphology, creative writing, musical composition, theater history, postmodern literature, ethics and morality, historical archives, film analysis, religious studies, classical archaeology, metaphysics, cultural heritage preservation, comparative literature, linguistic semantics, medieval art, epistemology` |
| 06 | **Biochemistry, Genetics and Molecular Biology** | `dna replication, crispr gene editing, protein folding, rna sequencing, enzyme kinetics, cellular signaling pathways, metabolic pathways, genomic sequencing, molecular cloning, apoptosis mechanism, mitochondrial DNA, epigenetic modifications, proteomics analysis, gene expression regulation, chromatin remodeling, amino acid synthesis, nucleic acids, cellular differentiation, lipid metabolism, transcription factors` |
| 07 | **Agricultural and Biological Sciences** | `crop yield optimization, plant physiology, marine biology, soil microbiology, entomology study, botany research, sustainable agriculture, animal behavior, ecology systems, pest management, forestry conservation, photosynthesis mechanism, biodiversity preservation, aquaculture techniques, agronomy practices, seed germination, horticulture science, wildlife ecology, plant pathology, livestock breeding` |
| 08 | **Environmental Science** | `climate change mitigation, renewable resource management, air pollution monitoring, microplastics in oceans, deforestation rates, waste management systems, carbon footprint reduction, biodiversity loss, global warming impacts, ecosystem restoration, water quality analysis, urban sustainability, environmental impact assessment, glacier melting, conservation biology, greenhouse gas emissions, soil erosion control, renewable energy transition, climate adaptation strategies, acid rain causes` |
| 09 | **Business, Management and Accounting** | `corporate strategy, supply chain logistics, financial auditing, marketing analytics, human resource management, organizational behavior, consumer behavior trends, risk assessment framework, entrepreneurship ecosystems, project management methodologies, accounting principles, brand equity, leadership styles, business ethics, digital transformation strategy, operations management, corporate governance, market segmentation, strategic planning, financial reporting standards` |
| 10 | **Psychology** | `cognitive behavioral therapy, developmental psychology, social anxiety disorder, memory retention techniques, neuropsychology assessment, human behavior analysis, mental health counseling, personality traits theory, child development stages, addiction recovery mechanisms, emotional intelligence, perception and sensation, group dynamics psychology, depression treatment outcomes, stress management interventions, motivation theories, cognitive dissonance, behavioral psychology, mindfulness practices, sleep disorders psychology` |
| 11 | **Materials Science** | `nanomaterials synthesis, graphene applications, polymers characterization, metallurgy engineering, semiconductor fabrication, composite materials design, biomaterials tissue engineering, thin film deposition, corrosion resistance, superconductors properties, ceramic engineering, alloy development, material degradation, photovoltaic materials, mechanical testing of alloys, smart materials technology, crystal structure analysis, carbon nanotubes research, thermal conductivity materials, magnetic materials applications` |
| 12 | **Economics, Econometrics and Finance** | `macroeconomic policy, econometric modeling, financial market analysis, monetary theory, microeconomics principles, game theory applications, inflation rates forecast, labor economics, behavioral finance, portfolio optimization, international trade agreements, fiscal policy impact, time series analysis, asset pricing models, poverty reduction strategies, economic growth models, corporate finance theory, cryptocurrency economics, market equilibrium, public finance management` |
| 13 | **Health Professions** | `physical therapy techniques, occupational therapy interventions, speech language pathology, radiologic technology, emergency medical services, healthcare administration, audiology assessments, rehabilitation sciences, clinical nutrition, paramedic protocols, respiratory therapy management, health informatics systems, dietetics practice, patient care quality, medical laboratory technology, orthotics and prosthetics, interprofessional healthcare collaboration, community health education, sports medicine rehabilitation, physician assistant training` |
| 14 | **Physics and Astronomy** | `quantum mechanics, astrophysics research, dark matter detection, particle physics collision, general relativity theory, cosmology evolution, exoplanet discovery, nuclear fusion energy, condensed matter physics, string theory concepts, optics and photonics, black hole thermodynamics, gravitational waves detection, statistical mechanics, plasma physics applications, stellar evolution models, high energy physics, quantum entanglement experiments, spectroscopy techniques, thermodynamics principles` |
| 15 | **Chemistry** | `organic synthesis, analytical chemistry methods, inorganic compounds coordination, physical chemistry thermodynamics, spectroscopy chemical analysis, catalysis mechanism design, polymer chemistry polymerization, electrochemistry batteries, medicinal chemistry design, chromatography separation techniques, chemical kinetics reactions, mass spectrometry profiling, computational chemistry modeling, environmental chemistry monitoring, photochemistry solar conversion, biophysical chemistry structure, green chemistry principles, molecular orbital theory, supramolecular architecture, crystallography structure determination` |
| 16 | **Mathematics** | `linear algebra, differential equations solution, algebraic topology, number theory cryptography, calculus fundamentals, probability and statistics, discrete mathematics structures, numerical analysis algorithms, complex analysis functions, geometry axiom theories, combinatorics counting techniques, mathematical modeling simulation, set theory foundations, graph theory applications, real analysis limits, partial differential equations, abstract algebra groups, optimization theory algorithms, stochastic processes modeling, chaos theory dynamics` |
| 17 | **Neuroscience** | `synaptic plasticity, neurodegenerative diseases mechanisms, brain mapping fmri, cognitive neuroscience memory, neurotransmitter receptors pathways, neural network architecture, behavioral neuroscience addiction, neurogenesis adult brain, axon guidance development, spinal cord injury, sensory processing systems, motor control pathways, alzheimer disease pathology, parkinson motor deficits, neuroimmunology inflammation, sleep neural circuits, epilepsy seizure mechanisms, computational neuroscience models, neuropharmacology drugs action, brain computer interface` |
| 18 | **Decision Sciences** | `operations research optimization, decision analysis models, multi criteria decision making, game theory strategies, risk analysis management, linear programming applications, forecasting methods business, supply chain optimization, stochastic modeling systems, queuing theory performance, decision tree classification, predictive analytics framework, statistical decision theory, heuristic search optimization, inventory control models, simulation optimization methods, behavioral decision making, utility theory choices, data driven decision support, dynamic programming problems` |
| 19 | **Earth and Planetary Sciences** | `plate tectonics geology, seismology earthquake prediction, volcanology eruption monitoring, paleoclimatology proxy data, planetary geology mars, mineralogy crystal structures, sedimentology deposition environments, stratigraphy rock layers, geomorphology landscape evolution, hydrology water cycle, meteorology weather forecasting, oceanography ocean currents, geochemistry isotopic analysis, remote sensing earth, petrology rock formation, impact cratering planetary, paleontology fossil records, glaciology ice sheets, geophysics magnetic fields, environmental geology hazards` |
| 20 | **Immunology and Microbiology** | `t cell activation, antibody response mechanics, bacterial resistance antibiotics, viral replication cycle, autoimmune disease pathogenesis, innate immunity defense, vaccine development strategies, microbiome gut health, macrophage polarization function, pathogen virulence factors, cytokine storm response, mycology fungal infections, parasitology host interaction, adaptive immune system, antigen presentation pathway, bacteriophage therapy applications, immunotherapy cancer treatment, microbial biofilms formation, virology host defense, inflammation signaling pathways` |
| 21 | **Energy** | `solar cell efficiency, wind turbine aerodynamics, battery energy storage, hydrogen fuel cells, nuclear power generation, biofuel production technologies, geothermal energy extraction, energy grid optimization, fossil fuel alternative, hydroelectric power systems, energy efficiency buildings, carbon capture storage, renewable energy policy, smart grid infrastructure, tidal energy conversion, thermal energy storage, power electronics converters, microgrid energy systems, biomass combustion processes, energy consumption forecasting` |
| 22 | **Pharmacology, Toxicology and Pharmaceutics** | `drug delivery systems, pharmacokinetics modeling analysis, pharmacodynamics receptor binding, toxicology safety assessment, pharmaceutical formulation design, bioavailability drug absorption, cytotoxicity assays testing, clinical pharmacology trials, neuropharmacology drug effects, cardiotoxicity drug evaluation, nanoparticle drug carriers, pharmacogenomics personalized medicine, drug metabolism enzymes, adverse drug reactions, controlled release tablets, heavy metal toxicology, target identification drug, natural product pharmacology, dosage form optimization, endocrine disruptors toxicology` |
| 23 | **Nursing** | `patient care management, nursing education curriculum, clinical nursing practice, geriatric nursing care, pediatric nursing interventions, critical care nursing, palliative nursing care, nursing leadership styles, community health nursing, evidence based nursing, mental health nursing, maternal newborn nursing, wound care management, nurse practitioner roles, patient safety protocols, nursing burnout prevention, oncology nursing practices, chronic disease management, telehealth nursing care, infection control nursing` |
| 24 | **Chemical Engineering** | `process systems engineering, chemical reactor design, transport phenomena fluid, separation processes distillation, catalytic reaction engineering, bioprocess engineering fermentation, thermodynamics chemical mixtures, heat exchanger network, polymer processing extrusion, mass transfer operations, process safety management, fluidized bed reactor, chemical plant optimization, multi phase flow, computational fluid dynamics, industrial scale synthesis, green chemical engineering, adsorption separation kinetics, process control loops, materials processing chemical` |
| 25 | **Dentistry** | `endodontic treatment procedures, periodontal disease therapy, orthodontic alignment techniques, dental implant surgery, prosthodontics crown design, pediatric dentistry prevention, oral maxillofacial surgery, dental caries prevention, restorative dentistry materials, oral pathology diagnosis, laser dentistry applications, dental biomaterials wear, cone beam ct, salivary diagnostics biomarkers, aesthetic dentistry veneers, root canal morphology, gingival recession treatment, fluoride treatment efficacy, dental pulp stem cells, temporomandibular joint disorders` |
| 26 | **Veterinary** | `veterinary medicine diagnosis, canine parvovirus treatment, feline leukemia virus, equine sports medicine, bovine mastitis control, veterinary surgery techniques, animal nutrition guidelines, zoonotic disease transmission, veterinary oncology treatment, avian medicine care, small animal internal, livestock herd health, veterinary pharmacology drugs, animal welfare assessment, veterinary radiology imaging, feline behavior issues, canine hip dysplasia, veterinary epidemiology outbreaks, companion animal care, exotic pet medicine` |
## Latency results
| Query Configuration | Mean | Median | p95 |
| :-------------------------------------- | :---: | :----: | :---: |
| **Embedding Encode** | 35.81 | 35.11 | 42.98 |
| **Pure Lexical Search (`multi_match`)** | 44.03 | 43.21 | 52.12 |
|
| **Description Only (`description_vector`)** | 27.11 | 24.83 | 40.23 |
| **Display Name Only (`display_name_vector`)** | 42.71 | 45.33 | 55.51 |
| **Keywords Only (`keyword_vectors` - Nested)** | 47.65 | 47.06 | 56.88 |
| **Display Name & Description** | 46.62 | 49.22 | 59.43 |
| **Display Name & Keywords (Nested)** | 52.11 | 51.36 | 61.22 |
| **Combined (All 3 vector fields)** | 57.06 | 55.65 | 67.32 |
|
| **Hybrid Search (Lexical + All 3 vector fields)** | 58.65 | 57.09 | 69.10 |
- should query runs hybrid and semantic concurrently => nested Keyword vector search bottleneck
- Hybrid returns more results overall due to partailly matching words in display name & Keywords
- Query: "Cell Adhesion Molecules Research"
- Low rank return: "Q Methodology Applications"
- because: ["**Research** Methods", "Qualitative **Research**"] Keywords
- Changed k & num_candidates to 500 (fixed bug, where not all keywords were considered):
| Query Configuration | Mean | Median | p95 |
| :--- | :---: | :---: | :---: |
| **Embedding Encode** | 38.25 | 37.41 | 45.48 |
| **Pure Lexical Search (`multi_match`)** | 44.98 | 43.69 | 55.21 |
| **Description Only (`description_vector`)** | 29.69 | 27.76 | 45.46 |
| **Display Name Only (`display_name_vector`)** | 45.20 | 46.68 | 59.47 |
| **Keywords Only (`keyword_vectors` - Nested)** | 50.00 | 48.89 | 60.61 |
| **Display Name & Description** | 49.84 | 51.16 | 66.37 |
| **Display Name & Keywords (Nested)** | 55.50 | 54.16 | 66.12 |
| **Combined (All 3 vector fields)** | 61.81 | 59.74 | 75.30 |
| **Hybrid Search (Lexical + All 3 vector fields)** | 63.25 | 61.05 | 76.39 |
# Search Score Breakdown & Weight Analysis Report
---
## Global Score Contribution
| Weight Component | Boost | Avg. Score Contribution | Percentage of Total Score |
| :-------------------------------------------- | :---: | :---------------------: | :-----------------------: |
| **Lexical Match (`multi_match`)** | 1.0 | 36.2275 | 54.31% |
| **Title Vector (`display_name_vector`)** | 30.0 | 17.9748 | 26.95% |
| **Description Vector (`description_vector`)** | 15.0 | 2.5502 | 3.82% |
| **Nested Keywords (`keyword_vectors`)** | 25.0 | 9.9531 | 14.92% |
| After fix:
| **Lexical Match (`multi_match`)** | 1.0 | 38.2910 | 44.79% |
| **Title Vector (`display_name_vector`)** | 30.0 | 22.5727 | 26.40% |
| **Description Vector (`description_vector`)** | 15.0 | 3.3518 | 3.92% |
| **Nested Keywords (`keyword_vectors`)** | 25.0 | 21.2808 | 24.89% |
---
## Contribution Breakdown by Field
| Field | Avg. Score | Lexical % | Title Vector % | Description Vector % | Keywords Vector % |
| :------------------------------------------- | :--------: | :-------: | :------------: | :------------------: | :---------------: |
| Social Sciences | 76.10 | 42.6% | 27.0% | 6.2% | 24.2% |
| Medicine | 71.58 | 43.9% | 26.5% | 4.1% | 25.5% |
| Engineering | 67.73 | 43.8% | 27.6% | 3.5% | 25.2% |
| Computer Science | 69.63 | 47.3% | 23.4% | 4.0% | 25.3% |
| Arts and Humanities | 75.38 | 40.2% | 28.7% | 5.9% | 25.1% |
| Biochemistry, Genetics and Molecular Biology | 64.32 | 43.5% | 26.7% | 1.6% | 28.1% |
| Agricultural and Biological Sciences | 70.48 | 38.0% | 30.7% | 4.2% | 27.1% |
| Environmental Science | 72.92 | 44.3% | 26.3% | 5.0% | 24.3% |
| Business, Management and Accounting | 75.14 | 47.1% | 25.8% | 2.7% | 24.5% |
| Psychology | 67.50 | 40.8% | 28.5% | 4.9% | 25.8% |
| Materials Science | 75.99 | 40.4% | 28.5% | 6.4% | 24.7% |
| Economics, Econometrics and Finance | 67.58 | 43.0% | 25.3% | 5.7% | 25.9% |
| Health Professions | 62.96 | 41.9% | 28.4% | 3.2% | 26.5% |
| Physics and Astronomy | 70.10 | 47.5% | 24.4% | 3.6% | 24.5% |
| Chemistry | 73.17 | 44.6% | 26.8% | 4.2% | 24.4% |
| Mathematics | 74.83 | 48.1% | 24.7% | 4.4% | 22.9% |
| Neuroscience | 68.20 | 45.2% | 24.6% | 5.2% | 25.0% |
| Decision Sciences | 67.13 | 49.5% | 23.3% | 2.4% | 24.8% |
| Earth and Planetary Sciences | 64.59 | 41.3% | 28.9% | 2.4% | 27.3% |
| Immunology and Microbiology | 68.62 | 44.9% | 25.7% | 3.6% | 25.9% |
| Energy | 80.04 | 50.3% | 22.8% | 5.4% | 21.6% |
| Pharmacology, Toxicology and Pharmaceutics | 64.61 | 45.2% | 26.1% | 2.4% | 26.2% |
| Nursing | 75.86 | 47.8% | 26.5% | 2.8% | 22.8% |
| Chemical Engineering | 59.12 | 48.5% | 26.0% | 1.1% | 24.4% |
| Dentistry | 62.51 | 44.1% | 28.1% | 3.1% | 24.7% |
| Veterinary | 53.56 | 49.2% | 26.9% | 1.9% | 22.0% |
---
## Score Breakdown Examples (Top Match per Field Sample)
| Field & Query | Fixed Variant Performance | Bug Variant Performance |
| :------------------------------------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Social Sciences**<br>`"sociology"` | **Topic**: Emile Durkheim and Sociology<br>**Total Score**: 80.7964<br><br>• Lexical: 33.6289<br>• Title KNN: 25.3876<br>• Desc KNN: 12.1561<br>• Key KNN: 24.9897<br><br>**Keywords**:<br>• 'sociology' (0.9996)<br>• 'social conditions' (0.8254) | **Topic**: Emile Durkheim and Sociology<br>**Total Score**: 55.4088<br><br>• Lexical: 33.6289<br>• Title KNN: 0.0000<br>• Desc KNN: 12.1561<br>• Key KNN: 24.9897<br><br>**Keywords**:<br>• 'sociology' (0.9996)<br>• 'social conditions' (0.8254) |
| **Medicine**<br>`"cardiology"` | **Topic**: Cardiomyopathy and Myosin Studies<br>**Total Score**: 62.3436<br><br>• Lexical: 0.0000<br>• Title KNN: 26.0134<br>• Desc KNN: 12.4090<br>• Key KNN: 23.9212<br><br>**Keywords**:<br>• 'Cardiomyopathies' (0.9568)<br>• 'Cardiac Imaging' (0.9192) | **Topic**: Cardiac Imaging and Diagnostics<br>**Total Score**: 27.6677<br><br>• Lexical: 0.0000<br>• Title KNN: 27.6677<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Cardiac Imaging' (0.9192)<br>• 'Myocardial Infarction' (0.8564) |
| **Engineering**<br>`"civil engineering"` | **Topic**: Civil and Structural Engineering Research<br>**Total Score**: 97.2652<br><br>• Lexical: 60.8415<br>• Title KNN: 28.1018<br>• Desc KNN: 12.3099<br>• Key KNN: 24.8941<br><br>**Keywords**:<br>• 'Civil Engineering' (0.9958)<br>• 'Construction' (0.8388) | **Topic**: Civil and Structural Engineering Research<br>**Total Score**: 97.2652<br><br>• Lexical: 60.8415<br>• Title KNN: 28.1018<br>• Desc KNN: 12.3099<br>• Key KNN: 24.8941<br><br>**Keywords**:<br>• 'Civil Engineering' (0.9958)<br>• 'Construction' (0.8388) |
| **Computer Science**<br>`"machine learning"` | **Topic**: Machine Learning and Algorithms<br>**Total Score**: 99.2549<br><br>• Lexical: 55.5562<br>• Title KNN: 29.2590<br>• Desc KNN: 12.5187<br>• Key KNN: 24.9693<br><br>**Keywords**:<br>• 'Machine Learning' (0.9988)<br>• 'Deep Learning' (0.9119) | **Topic**: Machine Learning and Algorithms<br>**Total Score**: 74.2856<br><br>• Lexical: 55.5562<br>• Title KNN: 29.2590<br>• Desc KNN: 12.5187<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Machine Learning' (0.9988)<br>• 'Deep Learning' (0.9119) |
| **Arts and Humanities**<br>`"art history"` | **Topic**: Art, Politics, and Modernism<br>**Total Score**: 79.6751<br><br>• Lexical: 41.4462<br>• Title KNN: 26.8390<br>• Desc KNN: 12.2412<br>• Key KNN: 23.1472<br><br>**Keywords**:<br>• 'Contemporary Art' (0.9259)<br>• 'Art Theory' (0.8902) | **Topic**: Art History and Market Analysis<br>**Total Score**: 54.6477<br><br>• Lexical: 44.3255<br>• Title KNN: 27.6256<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Art Market' (0.8499) |
| **Biochemistry, Genetics...**<br>`"dna replication"` | **Topic**: DNA Repair Mechanisms<br>**Total Score**: 69.5873<br><br>• Lexical: 37.9645<br>• Title KNN: 25.5676<br>• Desc KNN: 0.0000<br>• Key KNN: 21.2950<br><br>**Keywords**:<br>• 'Homologous Recombination' (0.8518) | **Topic**: DNA Repair Mechanisms<br>**Total Score**: 48.2923<br><br>• Lexical: 37.9645<br>• Title KNN: 25.5676<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Homologous Recombination' (0.8518) |
| **Agricultural Sciences**<br>`"crop yield optimization"` | **Topic**: Crop Yield and Soil Fertility<br>**Total Score**: 86.9026<br><br>• Lexical: 72.9192<br>• Title KNN: 25.6184<br>• Desc KNN: 0.0000<br>• Key KNN: 21.9673<br><br>**Keywords**:<br>• 'Crop Management' (0.8787)<br>• 'Maize Yield' (0.8515) | **Topic**: Soil Management and Crop Yield<br>**Total Score**: 65.6488<br><br>• Lexical: 58.5754<br>• Title KNN: 26.3319<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'No-till Crop Production' (0.8136) |
| **Environmental Science**<br>`"climate change mitigation"` | **Topic**: Climate Change, Adaptation, Migration<br>**Total Score**: 95.6090<br><br>• Lexical: 55.1717<br>• Title KNN: 24.9003<br>• Desc KNN: 12.3419<br>• Key KNN: 23.2867<br><br>**Keywords**:<br>• 'Climate Change' (0.9315) | **Topic**: Climate Change and Sustainable Development<br>**Total Score**: 72.0562<br><br>• Lexical: 52.0331<br>• Title KNN: 27.6359<br>• Desc KNN: 12.3920<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Climate Change' (0.9314)<br>• 'Environmental Policy' (0.8447) |
| **Business & Accounting**<br>`"corporate strategy"` | **Topic**: Political Influence and Corporate Strategies<br>**Total Score**: 70.1485<br><br>• Lexical: 43.3796<br>• Title KNN: 25.4050<br>• Desc KNN: 0.0000<br>• Key KNN: 23.5512<br><br>**Keywords**:<br>• 'Business Strategy' (0.9420)<br>• 'Corporate Governance' (0.8537) | **Topic**: Corporate Management and Leadership<br>**Total Score**: 44.0634<br><br>• Lexical: 18.0385<br>• Title KNN: 26.0249<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• _None matched_ |
| **Psychology**<br>`"cognitive behavioral therapy"` | **Topic**: Psychological Treatments and Assessments<br>**Total Score**: 74.0625<br><br>• Lexical: 33.9552<br>• Title KNN: 26.3648<br>• Desc KNN: 0.0000<br>• Key KNN: 24.8575<br><br>**Keywords**:<br>• 'Cognitive Behavioral Therapy' (0.9943)<br>• 'Rational Emotive Behavior Therapy' (0.8906) | **Topic**: Psychological Treatments and Assessments<br>**Total Score**: 74.0625<br><br>• Lexical: 33.9552<br>• Title KNN: 26.3648<br>• Desc KNN: 0.0000<br>• Key KNN: 24.8575<br><br>**Keywords**:<br>• 'Cognitive Behavioral Therapy' (0.9943)<br>• 'Rational Emotive Behavior Therapy' (0.8906) |
| **Materials Science**<br>`"nanomaterials synthesis"` | **Topic**: Copper-based nanomaterials and applications<br>**Total Score**: 79.3170<br><br>• Lexical: 31.3198<br>• Title KNN: 25.5626<br>• Desc KNN: 12.8334<br>• Key KNN: 23.2389<br><br>**Keywords**:<br>• 'Nanostructures' (0.9296)<br>• 'Nanocrystals' (0.8989) | **Topic**: Nanoparticles: synthesis and applications<br>**Total Score**: 51.4193<br><br>• Lexical: 41.6580<br>• Title KNN: 28.1196<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Nanomaterials' (0.9593)<br>• 'Nanoparticles' (0.9017) |
| **Economics & Finance**<br>`"macroeconomic policy"` | **Topic**: Monetary Policy and Economic Impact<br>**Total Score**: 77.2466<br><br>• Lexical: 33.6052<br>• Title KNN: 27.9601<br>• Desc KNN: 12.7554<br>• Key KNN: 23.1466<br><br>**Keywords**:<br>• 'Monetary Policy' (0.9259)<br>• 'Fiscal Policy' (0.8719) | **Topic**: Monetary Policy and Economic Impact<br>**Total Score**: 54.1000<br><br>• Lexical: 33.6052<br>• Title KNN: 27.9601<br>• Desc KNN: 12.7554<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Monetary Policy' (0.9259)<br>• 'Fiscal Policy' (0.8719) |
| **Health Professions**<br>`"physical therapy techniques"` | **Topic**: Physical Activity and Health<br>**Total Score**: 63.6719<br><br>• Lexical: 35.4732<br>• Title KNN: 24.8417<br>• Desc KNN: 0.0000<br>• Key KNN: 21.5571<br><br>**Keywords**:<br>• 'Physical Fitness' (0.8623)<br>• 'Exercise' (0.8567) | **Topic**: Physical Education and Training Studies<br>**Total Score**: 41.6865<br><br>• Lexical: 34.0993<br>• Title KNN: 25.9162<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Physical Education' (0.8518)<br>• 'Athletic Training' (0.8386) |
| **Physics and Astronomy**<br>`"quantum mechanics"` | **Topic**: Quantum Mechanics and Applications<br>**Total Score**: 100.0179<br><br>• Lexical: 62.6773<br>• Title KNN: 29.4806<br>• Desc KNN: 12.8902<br>• Key KNN: 23.1009<br><br>**Keywords**:<br>• 'Quantum Interpretations' (0.9240)<br>• 'Quantum Measurement' (0.9195) | **Topic**: Quantum Mechanics and Non-Hermitian Physics<br>**Total Score**: 82.1469<br><br>• Lexical: 59.7515<br>• Title KNN: 28.2917<br>• Desc KNN: 0.0000<br>• Key KNN: 24.8390<br><br>**Keywords**:<br>• 'Quantum Mechanics' (0.9936)<br>• 'Non-Hermitian Physics' (0.8265) |
| **Chemistry**<br>`"organic synthesis"` | **Topic**: Organic Chemistry Synthesis Methods<br>**Total Score**: 93.3478<br><br>• Lexical: 51.1392<br>• Title KNN: 28.8346<br>• Desc KNN: 12.8016<br>• Key KNN: 21.2545<br><br>**Keywords**:<br>• 'Total Synthesis' (0.8502) | **Topic**: Organic Chemistry Synthesis Methods<br>**Total Score**: 72.0932<br><br>• Lexical: 51.1392<br>• Title KNN: 28.8346<br>• Desc KNN: 12.8016<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Total Synthesis' (0.8502) |
| **Mathematics**<br>`"linear algebra"` | **Topic**: Advanced Algebra and Logic<br>**Total Score**: 69.1804<br><br>• Lexical: 21.0841<br>• Title KNN: 26.3365<br>• Desc KNN: 0.0000<br>• Key KNN: 21.7598<br><br>**Keywords**:<br>• 'MV-algebras' (0.8704)<br>• 'Algebraic Semantics' (0.8542) | **Topic**: Matrix Theory and Algorithms<br>**Total Score**: 51.1267<br><br>• Lexical: 42.7259<br>• Title KNN: 0.0000<br>• Desc KNN: 0.0000<br>• Key KNN: 24.3482<br><br>**Keywords**:<br>• 'Numerical Linear Algebra' (0.9739) |
| **Neuroscience**<br>`"synaptic plasticity"` | **Topic**: Neuroscience and Neuropharmacology Research<br>**Total Score**: 59.8949<br><br>• Lexical: 34.7332<br>• Title KNN: 0.0000<br>• Desc KNN: 13.1294<br>• Key KNN: 24.0698<br><br>**Keywords**:<br>• 'Synaptic Plasticity' (0.9628)<br>• 'Neuronal Circuits' (0.8298) | **Topic**: Neuroscience and Neuropharmacology Research<br>**Total Score**: 59.8949<br><br>• Lexical: 34.7332<br>• Title KNN: 0.0000<br>• Desc KNN: 13.1294<br>• Key KNN: 24.0698<br><br>**Keywords**:<br>• 'Synaptic Plasticity' (0.9628)<br>• 'Neuronal Circuits' (0.8298) |
| **Decision Sciences**<br>`"operations research optimization"` | **Topic**: Operations Management Techniques<br>**Total Score**: 72.2617<br><br>• Lexical: 45.7187<br>• Title KNN: 25.8359<br>• Desc KNN: 0.0000<br>• Key KNN: 20.3829<br><br>**Keywords**:<br>• 'Operations Management' (0.8153) | **Topic**: Management and Optimization Techniques<br>**Total Score**: 67.5272<br><br>• Lexical: 38.2684<br>• Title KNN: 27.0016<br>• Desc KNN: 0.0000<br>• Key KNN: 22.7133<br><br>**Keywords**:<br>• 'Operations Research' (0.9085) |
| **Earth Sciences**<br>`"plate tectonics geology"` | **Topic**: Geological and Geochemical Analysis<br>**Total Score**: 81.4082<br><br>• Lexical: 47.1954<br>• Title KNN: 24.9384<br>• Desc KNN: 0.0000<br>• Key KNN: 24.0854<br><br>**Keywords**:<br>• 'Plate Tectonics' (0.9634)<br>• 'Tectonics' (0.9412) | **Topic**: Geological and Geophysical Studies<br>**Total Score**: 76.8806<br><br>• Lexical: 33.5170<br>• Title KNN: 25.9864<br>• Desc KNN: 0.0000<br>• Key KNN: 24.0846<br><br>**Keywords**:<br>• 'Plate Tectonics' (0.9634)<br>• 'Tectonic Model' (0.8970) |
| **Immunology & Micro.**<br>`"t cell activation"` | **Topic**: T-cell and B-cell Immunology<br>**Total Score**: 101.7294<br><br>• Lexical: 58.5911<br>• Title KNN: 26.2074<br>• Desc KNN: 12.7561<br>• Key KNN: 22.2172<br><br>**Keywords**:<br>• 'Memory T Cells' (0.8887)<br>• 'TGF-ß' (0.8379) | **Topic**: T-cell and B-cell Immunology<br>**Total Score**: 79.5122<br><br>• Lexical: 58.5911<br>• Title KNN: 26.2074<br>• Desc KNN: 12.7561<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Memory T Cells' (0.8887)<br>• 'TGF-ß' (0.8379) |
| **Energy**<br>`"solar cell efficiency"` | **Topic**: solar cell performance optimization<br>**Total Score**: 100.7331<br><br>• Lexical: 69.7479<br>• Title KNN: 28.9188<br>• Desc KNN: 12.4518<br>• Key KNN: 21.6075<br><br>**Keywords**:<br>• 'Energy Conversion Efficiency' (0.8643)<br>• 'Multijunction Solar Cells' (0.8636) | **Topic**: solar cell performance optimization<br>**Total Score**: 79.1256<br><br>• Lexical: 69.7479<br>• Title KNN: 28.9188<br>• Desc KNN: 12.4518<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Energy Conversion Efficiency' (0.8643)<br>• 'Multijunction Solar Cells' (0.8636) |
| **Pharmacology & Tox.**<br>`"drug delivery systems"` | **Topic**: Advanced Drug Delivery Systems<br>**Total Score**: 101.0864<br><br>• Lexical: 82.7073<br>• Title KNN: 29.0884<br>• Desc KNN: 0.0000<br>• Key KNN: 23.9235<br><br>**Keywords**:<br>• 'Drug Delivery' (0.9569) | **Topic**: Advanced Drug Delivery Systems<br>**Total Score**: 77.1629<br><br>• Lexical: 82.7073<br>• Title KNN: 29.0884<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Drug Delivery' (0.9569) |
| **Nursing**<br>`"patient care management"` | **Topic**: Family and Patient Care in ICU<br>**Total Score**: 81.2835<br><br>• Lexical: 62.5713<br>• Title KNN: 25.2221<br>• Desc KNN: 0.0000<br>• Key KNN: 23.3629<br><br>**Keywords**:<br>• 'Patient-Centered Care' (0.9345)<br>• 'Critical Care' (0.8654) | **Topic**: Health Services Management and Policy<br>**Total Score**: 49.0703<br><br>• Lexical: 44.9180<br>• Title KNN: 0.0000<br>• Desc KNN: 0.0000<br>• Key KNN: 24.1204<br><br>**Keywords**:<br>• 'patient care' (0.9648)<br>• 'hospital management' (0.9044) |
| **Chemical Engineering**<br>`"process systems engineering"` | **Topic**: Systems Engineering Methodologies<br>**Total Score**: 69.4196<br><br>• Lexical: 46.7857<br>• Title KNN: 27.1586<br>• Desc KNN: 0.0000<br>• Key KNN: 21.4144<br><br>**Keywords**:<br>• 'Interdisciplinary System Eng.' (0.8566)<br>• 'Model-Based Systems Eng.' (0.8462) | **Topic**: Control Systems in Engineering<br>**Total Score**: 48.0307<br><br>• Lexical: 30.2824<br>• Title KNN: 25.1976<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• _None matched_ |
| **Dentistry**<br>`"endodontic treatment procedures"` | **Topic**: Endodontics and Root Canal Treatments<br>**Total Score**: 85.0595<br><br>• Lexical: 33.2248<br>• Title KNN: 27.3373<br>• Desc KNN: 12.9073<br>• Key KNN: 24.7433<br><br>**Keywords**:<br>• 'Endodontic Treatment' (0.9897)<br>• 'Regenerative Endodontics' (0.9185) | **Topic**: Endodontics and Root Canal Treatments<br>**Total Score**: 85.0595<br><br>• Lexical: 33.2248<br>• Title KNN: 27.3373<br>• Desc KNN: 12.9073<br>• Key KNN: 24.7433<br><br>**Keywords**:<br>• 'Endodontic Treatment' (0.9897)<br>• 'Regenerative Endodontics' (0.9185) |
| **Veterinary**<br>`"veterinary medicine diagnosis"` | **Topic**: Animal health and immunology<br>**Total Score**: 70.5398<br><br>• Lexical: 36.6445<br>• Title KNN: 24.4738<br>• Desc KNN: 0.0000<br>• Key KNN: 24.6649<br><br>**Keywords**:<br>• 'Veterinary Diagnosis' (0.9866) | **Topic**: Veterinary Medicine and Surgery<br>**Total Score**: 63.5579<br><br>• Lexical: 36.3745<br>• Title KNN: 27.1833<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• _None matched_ |
@@ -0,0 +1,64 @@
# Approach
**NDCG@10**, **MRR@10**, **Recall@10** :
- Topic: Document
- OpenAlex: "display_name": "Impact of Light on Environment and Health",
- Keyword: Query
- OpenAlex: "keywords": [
"Nighttime Light Data",
"Economic Growth",
"Light Pollution",
"Remote Sensing",
"Population Mapping",
"Urbanization Dynamics",
"Artificial Light",
"Satellite Imagery",
"Poverty Prediction",
"Ecological Impacts" ]
Each Keyword is searched in the Topic display name Vector space
# Overall Leaderboard
> **Note** First round is invalid
First round (all topics, but included sibling topics messed up metrics)
| Rank | Model Name | Vector Dim | Params (M) | Query Latency (ms) | Throughput (docs/s) | NDCG@10 | MRR@10 | Recall@10 | Subfield NMI |
| :--- | :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |
| 1 | `intfloat/e5-large-v2` | 1024 | 335.1M | 96.63ms | 5.7 | **0.2304** | 0.5054 | 0.0691 | 0.5917 |
| 2 | `BAAI/bge-large-en-v1.5` | 1024 | 335.1M | 96.24ms | 5.8 | **0.2292** | 0.4944 | 0.0691 | 0.5921 |
| 3 | `intfloat/multilingual-e5-large` | 1024 | 559.9M | 104.13ms | 4.8 | **0.2131** | 0.4789 | 0.0636 | 0.5900 |
| 4 | `google/embeddinggemma-300m` | 768 | 307.6M | 47.11ms | 14.0 | **0.2121** | 0.4479 | 0.0637 | 0.6054 |
| 5 | `intfloat/multilingual-e5-base` | 768 | 278.0M | 29.11ms | 16.3 | **0.2100** | 0.4641 | 0.0620 | 0.5919 |
| 6 | `intfloat/multilingual-e5-small` | 384 | 117.7M | 12.15ms | 55.3 | **0.2021** | 0.4446 | 0.0594 | 0.5880 |
| 7 | `BAAI/bge-m3` | 1024 | 567.8M | 96.92ms | 4.8 | **0.1879** | 0.4219 | 0.0544 | 0.5929 |
| 8 | `paraphrase-multilingual-mpnet-base-v2` | 768 | 278.0M | 29.65ms | 17.0 | **0.1792** | 0.3565 | 0.0520 | 0.6010 |
| 9 | `sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2` | 384 | 117.7M | 12.12ms | 58.1 | **0.1748** | 0.3494 | 0.0514 | 0.5940 |
Second adjusted round (500 topics sample size)(seperated clustering into name and description fields)
| Rank | Model Name | Vector Dim | Params (M) | Query Latency (ms) | Throughput (docs/s) | NDCG@10 | MRR@10 | Recall@10 | Name NMI | Desc NMI |
| :--- | :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |
| 1 | `intfloat/e5-large-v2` | 1024 | 335.1M | 101.71ms | 5.6 | **0.4261** | 0.3797 | 0.5758 | 0.5254 | 0.5947 |
| 2 | `BAAI/bge-large-en-v1.5` | 1024 | 335.1M | 98.38ms | 5.6 | **0.4084** | 0.3628 | 0.5546 | 0.5591 | 0.5961 |
| 3 | `intfloat/multilingual-e5-large` | 1024 | 559.9M | 111.27ms | 4.8 | **0.3956** | 0.3501 | 0.5424 | 0.5171 | 0.5845 |
| 4 | `intfloat/multilingual-e5-base` | 768 | 278.0M | 28.86ms | 17.9 | **0.3807** | 0.3357 | 0.5256 | 0.5374 | 0.5851 |
| 5 | `google/embeddinggemma-300m` | 768 | 307.6M | 45.55ms | 15.7 | **0.3558** | 0.3121 | 0.4976 | 0.5485 | 0.6148 |
| 6 | `intfloat/multilingual-e5-small` | 384 | 117.7M | 11.74ms | 57.6 | **0.3531** | 0.3050 | 0.5078 | 0.5450 | 0.5914 |
| 7 | `sentence-transformers/all-MiniLM-L6-v2` | 384 | 22.7M | 7.07ms | 117.0 | **0.3471** | 0.3034 | 0.4882 | 0.5636 | 0.5936 |
| 8 | `BAAI/bge-m3` | 1024 | 567.8M | 96.19ms | 4.9 | **0.3221** | 0.2829 | 0.4484 | 0.5246 | 0.5885 |
| 9 | `sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2` | 384 | 117.7M | 12.63ms | 58.0 | **0.2350** | 0.2005 | 0.3468 | 0.5544 | 0.5984 |
| 10 | `paraphrase-multilingual-mpnet-base-v2` | 768 | 278.0M | 24.67ms | 22.2 | **0.2347** | 0.1999 | 0.3480 | 0.5638 | 0.6043 |
Baseline with all topics for second round:
| Rank | Model Name | Vector Dim | Params (M) | Query Latency (ms) | Throughput (docs/s) | NDCG@10 | MRR@10 | Recall@10 | Name NMI | Desc NMI |
| 1 | `intfloat/multilingual-e5-base` | 768 | 278.0M | 32.83ms | 16.5 | **0.3751** | 0.3290 | 0.5234 | 0.5374 | 0.5851 |
## Metric Definitions:
- **NDCG@10**: Normalized Discounted Cumulative Gain. Measures how well the query maps to the target topic at the top 10 positions.
- **MRR@10**: Mean Reciprocal Rank. Looks at the average of `1 / rank` for the first correctly matched topic.
- **Recall@10**: Percentage of times the target document (excluding sibling topics) was successfully retrieved in the top 10.
- **Name NMI**: Normalized Mutual Information of K-Means clusters of topic display names against ground truth OpenAlex subfields.
- **Desc NMI**: Normalized Mutual Information of K-Means clusters of topic descriptions against ground truth OpenAlex subfields.
- **Query Latency**: Time to encode a single search keyword.
- **Throughput**: Ingestion batch encoding speed.
+4 -1
View File
@@ -19,7 +19,10 @@ RUN pip install --root-user-action=ignore --no-cache-dir --disable-pip-version-c
"partial-json-parser==0.2.1.1.post7" \
"sqlmodel~=0.0.33" \
"argon2-cffi~=25.1.0" \
"pypdf==6.14.2"
"pandas~=2.3.3" \
"pypdf==6.14.2"\
"docker~=7.1.0" \
"croniter~=6.0.0"
COPY [ "src/main", "/home" ]
COPY [ "src/data", "/data" ]
+1 -1
View File
@@ -61,7 +61,7 @@ task exportOpenApiSpec(type: Exec) {
task runServeContainer(type: Exec) {
dependsOn createImage
commandLine 'docker', 'run', '--rm', '-v', "${projectDir}/src/main:/home", '-v', "${projectDir}/src/data:/data", '-p', '8000:8000', '-e', "DOCKER_DEFAULT_PLATFORM='${targetPlatform}'", '-e', "INSE_AUTH_STANDALONE=true", '-e', 'INSE_OPENALEX_WORKS_API_KEY', '--name', "${imageName}-service-serve", '--detach', "${imagePrefix}-service:${imageVersion}", 'run', '--reload', '--reload-dir', './inse'
commandLine 'docker', 'run', '--rm', '-v', "${projectDir}/src/main:/home", '-v', "${projectDir}/src/data:/data", '-v', '/var/run/docker.sock:/var/run/docker.sock', '-p', '8000:8000', '-e', "DOCKER_DEFAULT_PLATFORM='${targetPlatform}'", '-e', "INSE_AUTH_STANDALONE=true", '-e', 'INSE_OPENALEX_WORKS_API_KEY', '--name', "${imageName}-service-serve", '--detach', "${imagePrefix}-service:${imageVersion}", 'run', '--reload', '--reload-dir', './inse'
}
task stopServeContainer(type: Exec) {
+1
View File
@@ -22,6 +22,7 @@ dependencies = [
"torch",
"sqlmodel~=0.0.33",
"argon2-cffi~=25.1.0",
"pandas~=2.3.3",
]
[[tool.uv.index]]
+20
View File
@@ -0,0 +1,20 @@
import sys
import time
import logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger(__name__)
def main() -> None:
seconds = int(sys.argv[1]) if len(sys.argv) > 1 else 20
logger.info(f"Demo job started, running for {seconds} seconds.")
for elapsed in range(1, seconds + 1):
time.sleep(1)
if elapsed % 5 == 0:
logger.info(f"Progress: {elapsed}/{seconds} seconds.")
logger.info("Demo job finished successfully.")
if __name__ == "__main__":
main()
+21
View File
@@ -0,0 +1,21 @@
# Background-jobs worker image. Build from the repo root:
# docker build -f service/scripts/jobs-image/Dockerfile -t docker.nes.uni-due.de/inse/background-jobs:latest .
FROM python:3.13-slim
WORKDIR /app
# Headless Chrome for the bund foerderportal crawler (Selenium).
RUN apt-get update \
&& apt-get install -y --no-install-recommends chromium chromium-driver \
&& rm -rf /var/lib/apt/lists/*
ENV CHROME_BIN=/usr/bin/chromium \
CHROMEDRIVER_PATH=/usr/bin/chromedriver
# Install dependencies
COPY service/scripts/jobs-image/requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy the job code.
COPY background-jobs/app/ ./
COPY service/scripts/ ./service/scripts/
+137
View File
@@ -0,0 +1,137 @@
# Job Images
## Anlegen und Bearbeiten eines Jobs (UI)
Ein Job im Frontend ist nur eine **Definition** in der Datenbank, die auf ein
Image zeigt. Der eigentliche Job-Code steckt im Image. Reihenfolge daher immer:
**erst das Image nach Nexus pushen, dann den Job in der UI anlegen.**
### 1. Image bauen und pushen
Aus dem Repo-Root (Build-Kontext = Root), Beispiel News-Crawler (jedes
Dockerfile nennt in seinem Kopf den eigenen Build-Befehl):
```bash
docker build -f service/scripts/jobs-image/news-crawl/Dockerfile \
-t docker.nes.uni-due.de/inse/jobs/news-crawl:latest .
docker push docker.nes.uni-due.de/inse/jobs/news-crawl:latest
```
Login zu Nexus vorher, falls nötig: `docker login docker.nes.uni-due.de`
(Zugangsdaten wie in der Backend-`.env`, `BACKGROUND_JOBS_REGISTRY_*`).
Erst wenn Push erfolgreich war, taucht das Image in der Image-Auswahl der UI auf.
### 2. Job anlegen
1. Als **Superadmin** anmelden und die Seite **Jobs** öffnen.
2. Oben rechts prüfen, dass die Karten **Docker-Daemon** und **Nexus-Registry**
grün („Erreichbar") sind. Ist Nexus rot, bleibt die Image-Auswahl leer —
dann Registry/`.env` prüfen, bevor es weitergeht.
3. Auf **Neuer Job** klicken. Im Dialog:
- **Name** – Pflichtfeld, muss eindeutig sein (sonst 409).
- **Beschreibung**, **Ziel-Index** – optional, nur zur Anzeige.
- **Image** – Pflichtfeld. In das Feld tippen und aus der
Nexus-Autovervollständigung den passenden Tag wählen, z. B.
`docker.nes.uni-due.de/inse/jobs/news-crawl:latest`. Leer = Fehler.
- **Befehl** – optional. Wird an den `ENTRYPOINT` des Images **angehängt**
(z. B. `--max-items 50`). Leer lassen, wenn die Image-Defaults reichen.
- **Umgebungsvariablen** – optional, `KEY=VALUE` pro Zeile. Bei
Nexus-Images werden die INSE-Zugangsdaten (Elasticsearch/LLM) ohnehin
automatisch ergänzt; hier nur Zusätzliches/Overrides.
4. **Speichern**. Der Job erscheint in der Tabelle, zunächst ohne Zeitplan
(= nur manuell).
### 3. Job ausführen und beobachten
- **▶ Jetzt ausführen** startet einen Lauf. Das Backend pullt das Image und
startet einen Container namens `<job-slug>-run-<id>`.
- **⏹ Stoppen** bricht einen laufenden Lauf ab.
- **🗎 Logs** zeigt die Container-Logs (live während des Laufs, danach die in der
DB gespeicherten letzten Zeilen) sowie Dauer bzw. „läuft seit".
- Schlägt der Pull fehl (Image gelöscht/nicht gepusht), wird der Lauf
**fehlgeschlagen** mit `failed to pull image …` im Log — dann Image neu pushen.
### 4. Job bearbeiten
- In der **Name**-Spalte erscheint beim Hovern ein **Stift**-Symbol → öffnet den
Bearbeiten-Dialog. Dort lassen sich **Name, Beschreibung, Ziel-Index, Image,
Befehl und Env** ändern (gleiche Validierung wie beim Anlegen).
- Das **Kalender**-Symbol in der Aktionsspalte öffnet den **Zeitplan**-Dialog:
Cron-Ausdruck setzen (5 Felder) und Job aktiv/inaktiv schalten. Ein Zeitplan
macht aus einem manuellen Job einen automatisch laufenden.
- Bearbeiten ist gesperrt, solange ein Lauf des Jobs läuft.
### 5. Job löschen
Das **Papierkorb**-Symbol entfernt die Job-Definition. Das Image in Nexus bleibt
davon unberührt (siehe unten zum Image-Löschen).
One Docker image per job script. Each image installs only its own dependencies
and bakes its script as the `ENTRYPOINT`. Most jobs then run with no `command`
override — the job definition just points `image` at the matching tag. Where
several jobs share one script (the demos), they point at the same image and
differ only by their `command`.
## Images
| Job (DB name) | Image | Entrypoint | Notes |
| ----------------------- | --------------------- | ---------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| News-Crawler | `jobs/news-crawl` | `run_pipeline.py` | scrapy<2.13, Twisted<24.7; uploads to `NEWS_UPLOAD_INDEX` |
| Bund-Crawler | `jobs/bund-crawl` | `gpc.data.py --max-rows 200` | headless Chrome; uploads to `BUND_UPLOAD_INDEX`; capped, full export is ~300k rows |
| Project-Topic-Mapping | `jobs/project-topics` | `map_project_topics --output-index docker-job_test` | reads projects_bund_v1; needs host backend |
| News-Topic-Mapping | `jobs/news-topics` | `map_news_topics --output-index aktuell_openalex_topics` | bundles both topic_mapper pkgs; needs host backend |
| News-Keyword-Extraction | `jobs/news-keywords` | `sync.py --update-keywords --target-index docker-job_test` | ES + LLM creds; writes to test index |
| Demo-Job A / B / C | `jobs/demo` | `demo.py` (seconds via command: `20` / `25` / `30`) | no dependencies; one image, three job rows |
Each image is its own repository under the `jobs/` path namespace, prefixed
`docker.nes.uni-due.de/inse/` (e.g. `docker.nes.uni-due.de/inse/jobs/news-crawl:latest`).
The three demo jobs share the single `jobs/demo` repository.
The entrypoints carry no run limits: anything set in the job's `command` field is
appended to the entrypoint, so limits (`--max-items`, `--max-docs`, `--limit`) are
passed per run from the UI. The one exception is the Bund-Crawler, which keeps a
`--max-rows` cap in the image because its full export is ~300k rows.
## Build
From the repo root (the build context must be the repo root so the Dockerfiles
can copy `service/scripts/…` and `background-jobs/app/`):
```bash
docker build -f service/scripts/jobs-image/news-crawl/Dockerfile \
-t docker.nes.uni-due.de/inse/jobs/news-crawl:latest .
docker push docker.nes.uni-due.de/inse/jobs/news-crawl:latest
```
Each image's Dockerfile header lists its own build command.
## Running locally without pushing
Before each run the backend pulls the job's image from the registry when it is a
registry image (host `docker.nes.uni-due.de`). **There is no fallback to a local
copy:** if the pull fails, the run is marked _failed_ and the error is written to
the run log — a stale local image is never used silently. To run a locally built
image without pushing it, skip the pull attempt entirely:
```bash
export BACKGROUND_JOBS_PULL_BEFORE_RUN=false
```
With the pull disabled the backend uses whatever image with that tag exists on
the Docker host, so `docker build -t docker.nes.uni-due.de/inse/jobs/<name>:latest .`
is enough for local runs.
## Env vars
Because every tag lives under the `docker.nes.uni-due.de` registry host, the
backend treats these as registry images and injects the INSE Elasticsearch / LLM
credentials automatically (plus any per-job `env`).
Most images write to the test index by default: the crawlers upload into the
index named by `NEWS_UPLOAD_INDEX` / `BUND_UPLOAD_INDEX` (both baked to
`docker-job_test` in their Dockerfile), and the project mapper and the keyword
extraction write to `docker-job_test` via `--output-index` / `--target-index`.
The exception is News-Topic-Mapping, which writes to `aktuell_openalex_topics`.
To not contact Elasticsearch at all, pass `--skip-upload` (crawlers) or
`--dry-run` (mappers) through the job's command field.
@@ -0,0 +1,28 @@
# Bund-Crawler (foerderportal export via headless Chrome). Build from the repo root:
# docker build -f service/scripts/jobs-image/bund-crawl/Dockerfile -t docker.nes.uni-due.de/inse/jobs/bund-crawl:latest .
FROM python:3.13-slim
WORKDIR /app
ENV PYTHONUNBUFFERED=1
# Upload the crawled projects into the shared test index (gpc.data.py reads
# ELASTICSEARCH_INSE_* creds + BUND_UPLOAD_INDEX from the env).
ENV BUND_UPLOAD_INDEX=docker-job_test
# Headless Chrome for the Selenium crawler.
RUN apt-get update \
&& apt-get install -y --no-install-recommends chromium chromium-driver \
&& rm -rf /var/lib/apt/lists/*
ENV CHROME_BIN=/usr/bin/chromium \
CHROMEDRIVER_PATH=/usr/bin/chromedriver
COPY service/scripts/jobs-image/bund-crawl/requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY service/scripts/projects/bund/ ./service/scripts/projects/bund/
WORKDIR /app/service/scripts/projects/bund
# Capped on purpose: the full export is ~300k rows, so an uncapped run would
# write that entire volume into BUND_UPLOAD_INDEX. Raise or drop the cap by
# passing --max-rows N through the job's command field.
ENTRYPOINT ["python", "gpc.data.py", "--max-rows", "200"]
@@ -0,0 +1,3 @@
selenium~=4.20
pandas~=2.2
requests~=2.32
@@ -0,0 +1,21 @@
# News-Crawler (UDE 'aktuell'). Build from the repo root:
# docker build -f service/scripts/jobs-image/news-crawl/Dockerfile -t docker.nes.uni-due.de/inse/jobs/news-crawl:latest .
#
# scrapy<2.13 + Twisted<24.7 are load-bearing: the spiders use the removed
# start_requests() hook, and newer versions silently crawl 0 items.
FROM python:3.13-slim
WORKDIR /app
ENV PYTHONUNBUFFERED=1
# Upload the crawled articles into the shared test index (see upload_aktuell.py,
# which reads ELASTICSEARCH_INSE_* creds + NEWS_UPLOAD_INDEX from the env).
ENV NEWS_UPLOAD_INDEX=docker-job_test
COPY service/scripts/jobs-image/news-crawl/requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY service/scripts/news/ude/ ./service/scripts/news/ude/
# Uncapped: crawls every article and uploads to NEWS_UPLOAD_INDEX. Limit a run by
# passing --max-items N through the job's command field.
ENTRYPOINT ["python", "service/scripts/news/ude/run_pipeline.py"]
@@ -0,0 +1,3 @@
scrapy>=2.11,<2.13
Twisted>=22.10,<24.7
requests~=2.32
@@ -0,0 +1,21 @@
# News keyword extraction (LLM keyword extraction into docker-job_test).
# Build from the repo root:
# docker build -f service/scripts/jobs-image/news-keywords/Dockerfile -t docker.nes.uni-due.de/inse/jobs/news-keywords:latest .
#
# Needs Elasticsearch + LLM creds (injected as env vars by the backend for
# registry images). Calls the LLM once per entry.
FROM python:3.13-slim
WORKDIR /app
ENV PYTHONUNBUFFERED=1
COPY service/scripts/jobs-image/news-keywords/requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY background-jobs/app/ ./
# Writes into docker-job_test, leaving production aktuell_postproc untouched.
# A non-postproc target re-extracts entries that already have keywords (real
# content) and updates them in place, keyed on news_id (re-runs overwrite, no
# duplicates). Cap a run by appending --limit N via the job's command field.
ENTRYPOINT ["python", "sync.py", "--update-keywords", "--target-index", "docker-job_test"]
@@ -0,0 +1,3 @@
requests~=2.32
openai~=2.41
python-dotenv~=1.0
@@ -0,0 +1,24 @@
# News-Topic-Mapping (news keywords -> OpenAlex topics). Build from the repo root:
# docker build -f service/scripts/jobs-image/news-topics/Dockerfile -t docker.nes.uni-due.de/inse/jobs/news-topics:latest .
#
# map_news_topics imports map_project_topics as its "base", so both topic_mapper
# packages must be present. Needs a reachable backend and Elasticsearch creds
# (injected as env vars by the backend for registry images).
FROM python:3.13-slim
WORKDIR /app
ENV PYTHONUNBUFFERED=1
COPY service/scripts/jobs-image/news-topics/requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY service/scripts/news/topic_mapper/ ./service/scripts/news/topic_mapper/
COPY service/scripts/projects/topic_mapper/ ./service/scripts/projects/topic_mapper/
# Writes topic mappings into aktuell_openalex_topics. Only maps (article, keyword)
# pairs not already present in the output index; pass --overwrite to re-map all.
# Uncapped: limit a run by passing --max-docs N through the job's command field.
# host.docker.internal reaches the host backend for vector search.
ENTRYPOINT ["python", "-m", "service.scripts.news.topic_mapper.map_news_topics", \
"--output-index", "aktuell_openalex_topics", \
"--api-base-url", "http://host.docker.internal:8000"]
@@ -0,0 +1,2 @@
httpx>=0.27
python-dotenv>=1.0
@@ -0,0 +1,25 @@
# Projekt-Topic-Mapping (bund keywords -> OpenAlex topics). Build from the repo root:
# docker build -f service/scripts/jobs-image/project-topics/Dockerfile -t docker.nes.uni-due.de/inse/jobs/project-topics:latest .
#
# Needs a reachable backend (vector search) and Elasticsearch creds. The creds
# arrive as env vars injected by the backend for registry images.
FROM python:3.13-slim
WORKDIR /app
ENV PYTHONUNBUFFERED=1
COPY service/scripts/jobs-image/project-topics/requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY service/scripts/projects/topic_mapper/ ./service/scripts/projects/topic_mapper/
# Writes topic mappings into docker-job_test. Only maps (project, keyword) pairs
# not already present in the output index, so an interrupted run can be resumed.
# There is no overwrite flag: to re-map all, point --output-index at a fresh index.
# Uncapped: limit a run by passing --max-docs N through the job's command field.
# host.docker.internal reaches the host backend for vector search.
ENTRYPOINT ["python", "-m", "service.scripts.projects.topic_mapper.map_project_topics", \
"--source-index", "projects_bund_v1", \
"--text-field", "Leistungsplansystematik_fullname", \
"--output-index", "docker-job_test", \
"--api-base-url", "http://host.docker.internal:8000"]
@@ -0,0 +1,2 @@
httpx>=0.27
python-dotenv>=1.0
@@ -0,0 +1,9 @@
requests~=2.32
openai~=2.41
python-dotenv~=1.0
scrapy>=2.11,<2.13
Twisted>=22.10,<24.7
httpx~=0.27
selenium~=4.20
pandas~=2.2
elasticsearch>=7.17,<8
@@ -0,0 +1,80 @@
# News → OpenAlex topic mapping
Batch counterpart to `news.logic._match_topics_for_keywords`, which matches an
article's keywords on every detail request without persisting the result. This
script maps the LLM-extracted `keywords` of the enriched articles in
`aktuell_postproc` to OpenAlex topics via the backend's
`/api/topics/vector-search` endpoint, and persists one document per
(article, keyword) pair into an output index with the explicit mapping from
`news_mapping.py`:
```json
{
"news_id": "...",
"keyword": "<one of the article's keywords>",
"source_index": "aktuell_postproc",
"source_field": "keywords",
"topic_matches": [
{
"rank": 1,
"topic_id": "...",
"topic_display_name": "...",
"subfield": "...",
"field": "...",
"domain": "...",
"match_score": null
}
],
"match_method": "sentence_transformer",
"model_name": "...",
"built_at": "..."
}
```
`match_score` is `null` because the endpoint does not expose Elasticsearch
scores; `rank` preserves the search result order.
This script only ever **reads** `aktuell_postproc` and writes into the separate test index. Caching the topics back into `aktuell_postproc` is done by the news detail endpoint (`news/logic.py`), not here.
Keywords are **not** extracted here. `background-jobs/app/sync.py` (job `news`)
writes them into `aktuell_postproc` first, the same way the bund projects
already carry their keyword field before `map_project_topics.py` runs.
The Elasticsearch plumbing (point-in-time scan, batched topic search, bulk
indexing, retries) is imported from
`service/scripts/projects/topic_mapper/map_project_topics.py` rather than
duplicated — that directory must stay next to this one.
## Setup
```bash
pip install -r requirements.txt
```
Credentials are read from `service/src/main/inse/.env` by default (override
with `--env-file`), and the backend must be running (e.g. `./gradlew serve`)
because the topic search goes through its API.
## Usage
```bash
python map_news_topics.py --output-index docker-job_test
```
Test run against a few articles without writing anything:
```bash
python map_news_topics.py --output-index docker-job_test --dry-run --max-docs 50
```
Runs are resumable: (article, keyword) pairs already present in the output
index are skipped, and each unique keyword is searched only once across all
articles that use it. Pairs whose search failed are left unwritten so the next
run retries them.
## As a background job
Packaged as the `news-topics` registry image (see
`service/scripts/jobs-image/news-topics/Dockerfile`), writing into
`aktuell_openalex_topics`. The run is uncapped; limit a run by passing
`--max-docs N` through the job's command field.
@@ -0,0 +1,329 @@
#!/usr/bin/env python3
"""
map_news_topics.py — Map news keywords to OpenAlex topics.
Batch counterpart to news.logic._match_topics_for_keywords. This script streams
the enriched articles from aktuell_postproc, reads their LLM-extracted
'keywords', matches every unique keyword against OpenAlex topics and persists
one document per (article, keyword) pair into a separate output index:
{news_id, keyword, source_index, source_field, topic_matches[],
match_method, model_name, built_at}
The source index is only ever read. Writing the topics back into
aktuell_postproc is the job of the news detail endpoint, not of this script.
Keywords are not extracted here — sync.py (job 'news') writes them into
aktuell_postproc, the same way the bund projects already carry their keyword
field before map_project_topics.py runs.
The run is resumable: (article, keyword) pairs already present in the output
index are skipped, so an interrupted run can simply be restarted. Each unique
keyword is searched only once, across all articles that use it.
Usage:
python map_news_topics.py --output-index docker-job_test
Requires ELASTICSEARCH_INSE_URL/ELASTICSEARCH_INSE_API_KEY in the environment
or in the service .env, plus a running backend serving
/api/topics/vector-search (e.g. ./gradlew serve).
"""
from __future__ import annotations
import argparse
import asyncio
import hashlib
import json
import logging
import os
import sys
from datetime import datetime, timezone
from pathlib import Path
from dotenv import load_dotenv
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "projects" / "topic_mapper"))
import map_project_topics as base
sys.path.insert(0, str(Path(__file__).resolve().parent))
from news_mapping import NEWS_TOPICS_MAPPING
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger(__name__)
SOURCE_INDEX = "aktuell_postproc"
KEYWORD_FIELD = "keywords"
NEWS_ID_FIELD = "news_id"
async def ensure_index(index: str, cluster: str) -> None:
"""Creates the output index with the explicit mapping if it does not exist."""
url, headers = base.es_headers(cluster)
client = base.get_http_client()
response = await client.head(f"{url}/{index}", headers=headers)
if response.status_code == 200:
logger.info("Output index '%s' already exists.", index)
return
response = await client.put(
f"{url}/{index}", json={"mappings": NEWS_TOPICS_MAPPING}, headers=headers
)
response.raise_for_status()
logger.info("Created output index '%s' with explicit mapping.", index)
def output_doc_id(news_id: str, keyword: str) -> str:
"""Stable id per (article, keyword) pair.
Derived from news_id rather than the aktuell_postproc document id, so a
reindex of the postproc index does not duplicate the mappings.
"""
digest = hashlib.sha1(keyword.encode("utf-8")).hexdigest()[:12]
return f"{news_id}::{digest}"
async def fetch_source_entries(cluster: str, max_docs: int | None) -> dict[str, tuple[str, str]]:
"""Returns output_doc_id -> (news_id, keyword) for every enriched article."""
entries: dict[str, tuple[str, str]] = {}
total = 0
docs_with_keywords = 0
async for hit in base.scan(
index=SOURCE_INDEX,
cluster=cluster,
query={"exists": {"field": KEYWORD_FIELD}},
source=[NEWS_ID_FIELD, KEYWORD_FIELD],
):
total += 1
doc_source = hit.get("_source", {})
keywords = base.extract_text_values(doc_source, KEYWORD_FIELD)
news_id = doc_source.get(NEWS_ID_FIELD)
if keywords and news_id:
docs_with_keywords += 1
for keyword in keywords:
entries[output_doc_id(news_id, keyword)] = (news_id, keyword)
if total % 50000 == 0:
logger.info("Scanned %d source documents...", total)
if max_docs and total >= max_docs:
logger.info("Stopping scan at --max-docs=%d.", max_docs)
break
logger.info(
"Scanned %d documents from '%s', %d with non-empty '%s' (%d article/keyword pairs).",
total,
SOURCE_INDEX,
docs_with_keywords,
KEYWORD_FIELD,
len(entries),
)
return entries
async def run(args: argparse.Namespace) -> None:
built_at = datetime.now(timezone.utc).isoformat()
model_name = os.getenv("SENTENCE_TRANSFORMERS_MODEL_NAME")
await base.check_backend(args.api_base_url)
if not args.dry_run:
await ensure_index(index=args.output_index, cluster=args.output_cluster)
entries = await fetch_source_entries(cluster=args.source_cluster, max_docs=args.max_docs)
if not entries:
logger.warning("No keywords in '%s' — run the 'news' job first.", SOURCE_INDEX)
return
if args.overwrite:
logger.info("--overwrite: re-mapping every pair, existing documents are replaced.")
covered = set()
else:
covered = await base.fetch_covered_doc_ids(
index=args.output_index, cluster=args.output_cluster
)
pending = {doc_id: entry for doc_id, entry in entries.items() if doc_id not in covered}
logger.info(
"Coverage: %d/%d pairs already in '%s', %d still to be processed.",
len(entries) - len(pending),
len(entries),
args.output_index,
len(pending),
)
if not pending:
logger.info("Nothing left to process.")
return
docs_by_keyword: dict[str, list[tuple[str, str]]] = {}
for doc_id, (news_id, keyword) in pending.items():
docs_by_keyword.setdefault(keyword, []).append((doc_id, news_id))
unique_keywords = sorted(docs_by_keyword)
logger.info(
"%d unique keywords cover the %d pending pairs.", len(unique_keywords), len(pending)
)
backup_docs: list[dict] = []
docs_done = 0
keywords_done = 0
for start in range(0, len(unique_keywords), args.text_batch_size):
chunk = unique_keywords[start : start + args.text_batch_size]
matches_by_keyword = await base.match_keywords(
chunk,
api_base_url=args.api_base_url,
top_k=args.top_k,
search_type=args.search_type,
)
documents = []
for keyword in chunk:
if keyword not in matches_by_keyword:
continue # search failed — left for the next run
for doc_id, news_id in docs_by_keyword[keyword]:
documents.append(
(
doc_id,
{
"news_id": news_id,
"keyword": keyword,
"source_index": SOURCE_INDEX,
"source_field": KEYWORD_FIELD,
"topic_matches": matches_by_keyword[keyword],
"match_method": base.MATCH_METHOD,
"model_name": model_name,
"built_at": built_at,
},
)
)
if documents and not args.dry_run:
await base.bulk_index(
index=args.output_index, cluster=args.output_cluster, documents=documents
)
if args.output:
backup_docs.extend(doc for _, doc in documents)
keywords_done += len(chunk)
docs_done += len(documents)
logger.info(
"Progress: %d/%d keywords, %d/%d pending pairs indexed into '%s'.",
keywords_done,
len(unique_keywords),
docs_done,
len(pending),
args.output_index,
)
skipped = len(pending) - docs_done
if skipped:
logger.warning(
"%d pairs were NOT indexed due to failed searches — rerun the script to retry.",
skipped,
)
if args.output:
output_path = Path(args.output)
output_path.parent.mkdir(parents=True, exist_ok=True)
output_path.write_text(
json.dumps(backup_docs, indent=2, ensure_ascii=False), encoding="utf-8"
)
logger.info("Wrote local JSON backup (%d documents) to %s", len(backup_docs), output_path)
logger.info(
"Done. %d documents indexed this run, %d covered in total.",
docs_done,
len(covered) + docs_done,
)
def main() -> None:
parser = argparse.ArgumentParser(
description="Map the keywords of enriched news articles to OpenAlex topics.",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=(
"Examples:\n"
" python map_news_topics.py --output-index docker-job_test\n"
" python map_news_topics.py --output-index docker-job_test --dry-run --max-docs 50"
),
)
parser.add_argument(
"--output-index", required=True, help="Index to persist the topic mappings into"
)
parser.add_argument(
"--source-cluster",
default="inse",
choices=["inse", "nes"],
help=f"Cluster holding '{SOURCE_INDEX}' (default: inse)",
)
parser.add_argument(
"--output-cluster",
default="inse",
choices=["inse", "nes"],
help="Cluster of the output index (default: inse)",
)
parser.add_argument(
"--api-base-url",
default=base.DEFAULT_API_BASE_URL,
help=f"Base URL of the running backend (default: {base.DEFAULT_API_BASE_URL})",
)
parser.add_argument(
"--top-k",
type=int,
default=1,
help=(
"Number of topic matches per keyword (default: 1, matching the single "
"match the news detail endpoint shows). Only truncates the result list; "
"ranking is unaffected."
),
)
parser.add_argument(
"--search-type",
default="hybrid",
choices=["hybrid", "semantic"],
help="Topic search type, mirrors vector_search_topics (default: hybrid)",
)
parser.add_argument(
"--text-batch-size",
type=int,
default=base.TEXT_BATCH_SIZE,
help=f"Unique keywords searched per chunk (default: {base.TEXT_BATCH_SIZE})",
)
parser.add_argument(
"--env-file",
default=str(base.DEFAULT_ENV_FILE),
help=f"Path to a .env with Elasticsearch credentials (default: {base.DEFAULT_ENV_FILE})",
)
parser.add_argument(
"--max-docs",
type=int,
default=None,
help=f"Stop scanning '{SOURCE_INDEX}' after N documents (for test runs)",
)
parser.add_argument(
"--output",
default=None,
help="Optional path for a local JSON backup of the documents built this run",
)
parser.add_argument(
"--overwrite",
action="store_true",
help=(
"Re-map pairs that are already in the output index instead of skipping "
"them; document ids are deterministic, so they are replaced in place "
"(use after changing --top-k or --search-type)"
),
)
parser.add_argument(
"--dry-run",
action="store_true",
help="Build the mapping without creating/writing the output index",
)
args = parser.parse_args()
if args.env_file and Path(args.env_file).exists():
load_dotenv(dotenv_path=args.env_file)
asyncio.run(run(args))
if __name__ == "__main__":
main()
@@ -0,0 +1,30 @@
"""Elasticsearch mapping for news -> OpenAlex topic mapping indices.
One document per (news article, keyword) pair. Articles in aktuell_postproc
carry up to KEYWORD_LIMIT keywords each, so an article normally yields
several documents.
"""
NEWS_TOPICS_MAPPING = {
"properties": {
"news_id": {"type": "keyword"},
"keyword": {"type": "text", "fields": {"keyword": {"type": "keyword"}}},
"source_index": {"type": "keyword"},
"source_field": {"type": "keyword"},
"topic_matches": {
"type": "nested",
"properties": {
"rank": {"type": "integer"},
"topic_id": {"type": "keyword"},
"topic_display_name": {"type": "keyword"},
"subfield": {"type": "keyword"},
"field": {"type": "keyword"},
"domain": {"type": "keyword"},
"match_score": {"type": "float"},
},
},
"match_method": {"type": "keyword"},
"model_name": {"type": "keyword"},
"built_at": {"type": "date"},
}
}
@@ -0,0 +1,2 @@
httpx>=0.27
python-dotenv>=1.0
+42 -12
View File
@@ -3,6 +3,12 @@ import sys
import os
import shutil
import time
import argparse
import logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger(__name__)
def run_command(command, cwd=None):
"""Run a shell command and exit if it fails."""
@@ -12,11 +18,27 @@ def run_command(command, cwd=None):
#capture_output=True, #supresses output from subprocess
text=True)
if result.returncode != 0:
print(f"Command failed: {command}")
print("Error output:\n", result.stderr)
logger.error(f"Command failed: {command}")
logger.error(f"Error output:\n{result.stderr}")
sys.exit(result.returncode)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Crawl the UDE 'aktuell' news pages and upload the articles to Elasticsearch."
)
parser.add_argument(
"--skip-upload",
action="store_true",
help="Only crawl into out/*.json and never connect to Elasticsearch",
)
parser.add_argument(
"--max-items",
type=int,
default=None,
help="Stop each spider after N items (for short test runs)",
)
args = parser.parse_args()
start_time = time.time()
base_dir = os.path.dirname(os.path.abspath(__file__))
@@ -31,19 +53,27 @@ if __name__ == "__main__":
output_file_meta = os.path.join(out_dir, "meta.json")
print("Running Scrapy link crawler...")
run_command(f"scrapy crawl aktuell-links -O \"{output_file_links}\"", cwd=crawler_dir)
limit = f" -s CLOSESPIDER_ITEMCOUNT={args.max_items}" if args.max_items else ""
print("Running Scrapy meta crawler...")
run_command(f"scrapy crawl aktuell-metadata -O \"{output_file_meta}\"", cwd=crawler_dir)
logger.info("Running Scrapy link crawler...")
run_command(f"scrapy crawl aktuell-links -O \"{output_file_links}\"{limit}", cwd=crawler_dir)
print("Running upload script")
run_command(f"{sys.executable} upload_aktuell.py {output_file_meta}", cwd=base_dir)
logger.info("Running Scrapy meta crawler...")
run_command(f"scrapy crawl aktuell-metadata -O \"{output_file_meta}\"{limit}", cwd=crawler_dir)
if args.skip_upload:
logger.info("Skipping upload (--skip-upload): Elasticsearch was not contacted.")
else:
logger.info("Running upload script")
run_command(f"{sys.executable} upload_aktuell.py {output_file_meta}", cwd=base_dir)
end_time = time.time()
runtime_seconds = end_time - start_time
runtime_hours = runtime_seconds / 3600
print(f"Runtime: {runtime_hours:.2f} hours")
print("Finished crawling and uploading UDE news articles.")
runtime_hours = runtime_seconds / 3600
logger.info(f"Runtime: {runtime_hours:.2f} hours")
if args.skip_upload:
logger.info("Finished crawling UDE news articles (no upload).")
else:
logger.info("Finished crawling and uploading UDE news articles.")
+33 -221
View File
@@ -1,231 +1,39 @@
from elasticsearch import Elasticsearch
import sys
import os
import json
from datetime import datetime
import time
import logging
from urllib.parse import quote
# elasticsearch-connection should be adjusted
# uni-server
es = Elasticsearch()
import requests
index_name = "aktuell-test" #test indices to make sure everything works before uploading to the real index, ps. you lack rights to push to the real index, please contact the admin if you want to push to the real index
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger(__name__)
# The INSE key is index-scoped and can't hit cluster endpoints (e.g. GET /), so
# the elasticsearch client's ping/product-check would 403. We talk to the index
# endpoint directly over HTTP with the ApiKey header, like the other jobs do.
ES_URL = os.getenv("ELASTICSEARCH_INSE_URL", "http://localhost:9200").rstrip("/")
ES_API_KEY = os.getenv("ELASTICSEARCH_INSE_API_KEY")
# Default is a test index — you lack rights to push to the production index;
# contact the ES admin for that. Override via NEWS_UPLOAD_INDEX.
# The target index is never created here: an index that doesn't exist yet gets
# ES dynamic mapping, without the searchabilityAnalyzer the search relies on.
# Create it with the proper mapping before pointing a run at a new index.
INDEX_NAME = os.getenv("NEWS_UPLOAD_INDEX", "aktuell-test")
# checks if elastic is up and creates the index if not already done
def check_elastic():
if not es.ping():
sys.exit("No connection to Elasticsearch")
_session = requests.Session()
_session.headers.update({"Content-Type": "application/json"})
if ES_API_KEY:
_session.headers.update({"Authorization": f"ApiKey {ES_API_KEY}"})
if not es.indices.exists(index=index_name):
settings = {
"analysis": {
"analyzer": {
"searchabilityAnalyzer": {
"type": "custom",
"tokenizer": "standard",
"filter": [
"lowercase",
"asciifolding"
]
}
}
}
}
mappings = {
"properties": {
"subtitle": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"maintitle": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"author": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"date": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"date_year": {
"type": "long",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"date_full": {
"type": "long",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"intro_content": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"main_content": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"further_content": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"redaktion": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"full_content": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"tags": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"tags_nested": {
"type": "nested",
"properties": {
"tag": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 250
}
}
}
}
},
#"links": {
# "type": "text",
# "analyzer": "searchabilityAnalyzer",
# "search_analyzer": "searchabilityAnalyzer",
# "fields": {
# "keyword": {
# "type": "keyword",
# "ignore_above": 256
# }
# }
#},
"links_nested": {
"type": "nested",
"properties": {
"url": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 250
}
}
},
"text": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 250
}
}
}
}
},
}
}
es.indices.create(index=index_name, mappings=mappings, settings=settings)
def upload(path):
with open(path, "r", encoding='utf-8') as json_file:
with open(path, "r", encoding="utf-8") as json_file:
try:
json_loaded = json.load(json_file)
uploaded = 0
for news in json_loaded:
time.sleep(10 / 1000)
id = (str(news["date"]) + "_" + str(news["author"]) + "_" + str(news["maintitle"])).replace(" ", "").replace("/", "").replace("ö", "").replace("ä", "").replace("ü", "").replace("Ö", "").replace("Ä", "").replace("Ü", "").replace(".", "").replace("?", "")
@@ -241,7 +49,7 @@ def upload(path):
for p in range(len(tags)):
tags_nested.append({"tag": tags[p]})
dict = {
document = {
"subtitle": news["subtitle"],
"maintitle": news["maintitle"],
"tags": news["tags"],
@@ -255,21 +63,25 @@ def upload(path):
"tags_nested": tags_nested,
"date_year": news["date_year"],
"date_full": news["date_full"],
#"links": news["links"],
"links_nested": links_nested,
"url": news["url"]
}
es.index(index=index_name, id=id, document=dict)
response = _session.put(
f"{ES_URL}/{INDEX_NAME}/_doc/{quote(id, safe='')}",
json=document,
)
response.raise_for_status()
uploaded += 1
logger.info(f"Uploaded {uploaded} news articles to '{INDEX_NAME}'.")
except Exception as e:
print("--- Failed to upload news.")
print(e)
logger.error(f"Failed to upload news: {e}")
# main - entry point
if __name__ == '__main__':
check_elastic()
if len(sys.argv) != 2:
sys.exit("No path given.")
upload(sys.argv[1])
@@ -16,9 +16,7 @@
"relevance_score": 1.0
}
],
"expected_ipc_prefixes": [
"H01M"
],
"expected_ipc_prefixes": ["H01M"],
"mapping_status": "mapped",
"diagnostics": {
"search_path": "ipc",
@@ -57,12 +55,8 @@
"topic_score": 1.0,
"text_score": 1.0,
"topic_match_kind": "topic_id",
"matched_keywords": [
"fuel cell"
],
"matched_ipc_symbols": [
"H01M8/083"
],
"matched_keywords": ["fuel cell"],
"matched_ipc_symbols": ["H01M8/083"],
"text_retrieval": false,
"ipc": [
"H01M 4/90 20060101AFI20240910BHUS",
@@ -91,12 +85,8 @@
"topic_score": 1.0,
"text_score": 1.0,
"topic_match_kind": "topic_id",
"matched_keywords": [
"fuel cell"
],
"matched_ipc_symbols": [
"H01M8/083"
],
"matched_keywords": ["fuel cell"],
"matched_ipc_symbols": ["H01M8/083"],
"text_retrieval": false,
"ipc": [
"H01M 8/083 20160101AFI20210209BHUS",
@@ -142,12 +132,8 @@
"topic_score": 1.0,
"text_score": 1.0,
"topic_match_kind": "topic_id",
"matched_keywords": [
"fuel cell"
],
"matched_ipc_symbols": [
"H01M8/083"
],
"matched_keywords": ["fuel cell"],
"matched_ipc_symbols": ["H01M8/083"],
"text_retrieval": false,
"ipc": [
"H01M 8/06 20160101AFI20201124BHUS",
@@ -178,12 +164,8 @@
"topic_score": 1.0,
"text_score": 1.0,
"topic_match_kind": "topic_id",
"matched_keywords": [
"fuel cell"
],
"matched_ipc_symbols": [
"H01M8/083"
],
"matched_keywords": ["fuel cell"],
"matched_ipc_symbols": ["H01M8/083"],
"text_retrieval": false,
"ipc": [
"H01M 8/0221 20160101AFI20201124BHUS",
@@ -229,12 +211,8 @@
"topic_score": 1.0,
"text_score": 1.0,
"topic_match_kind": "topic_id",
"matched_keywords": [
"fuel cell"
],
"matched_ipc_symbols": [
"H01M8/083"
],
"matched_keywords": ["fuel cell"],
"matched_ipc_symbols": ["H01M8/083"],
"text_retrieval": false,
"ipc": [
"A62C 3/06 20060101AFI20190820BHEP",
@@ -260,12 +238,8 @@
"topic_score": 1.0,
"text_score": 1.0,
"topic_match_kind": "topic_id",
"matched_keywords": [
"fuel cell"
],
"matched_ipc_symbols": [
"H01M8/083"
],
"matched_keywords": ["fuel cell"],
"matched_ipc_symbols": ["H01M8/083"],
"text_retrieval": false,
"ipc": [
"H01M 12/08 20060101AFI20190521BHUS",
@@ -301,12 +275,8 @@
"topic_score": 1.0,
"text_score": 1.0,
"topic_match_kind": "topic_id",
"matched_keywords": [
"fuel cell"
],
"matched_ipc_symbols": [
"H01M8/083"
],
"matched_keywords": ["fuel cell"],
"matched_ipc_symbols": ["H01M8/083"],
"text_retrieval": false,
"ipc": [
"H01M 4/36 20060101AFI20181009BHUS",
@@ -338,12 +308,8 @@
"topic_score": 1.0,
"text_score": 1.0,
"topic_match_kind": "topic_id",
"matched_keywords": [
"fuel cell"
],
"matched_ipc_symbols": [
"H01M8/083"
],
"matched_keywords": ["fuel cell"],
"matched_ipc_symbols": ["H01M8/083"],
"text_retrieval": false,
"ipc": [
"H01M 8/08 20160101AFI20180626BHUS",
@@ -379,12 +345,8 @@
"topic_score": 1.0,
"text_score": 1.0,
"topic_match_kind": "topic_id",
"matched_keywords": [
"fuel cell"
],
"matched_ipc_symbols": [
"H01M8/083"
],
"matched_keywords": ["fuel cell"],
"matched_ipc_symbols": ["H01M8/083"],
"text_retrieval": false,
"ipc": [
"H01M 8/0656 20160101AFI20170424BHEP",
@@ -411,12 +373,8 @@
"topic_score": 1.0,
"text_score": 1.0,
"topic_match_kind": "topic_id",
"matched_keywords": [
"fuel cell"
],
"matched_ipc_symbols": [
"H01M8/083"
],
"matched_keywords": ["fuel cell"],
"matched_ipc_symbols": ["H01M8/083"],
"text_retrieval": false,
"ipc": [
"H01M 8/08 20160101AFI20170207BHUS",
@@ -445,12 +403,8 @@
"topic_score": 1.0,
"text_score": 1.0,
"topic_match_kind": "topic_id",
"matched_keywords": [
"fuel cell"
],
"matched_ipc_symbols": [
"H01M8/083"
],
"matched_keywords": ["fuel cell"],
"matched_ipc_symbols": ["H01M8/083"],
"text_retrieval": false,
"ipc": [
"H01M 8/06 20060101AFI20160614BHUS",
@@ -484,12 +438,8 @@
"topic_score": 1.0,
"text_score": 1.0,
"topic_match_kind": "topic_id",
"matched_keywords": [
"fuel cell"
],
"matched_ipc_symbols": [
"H01M8/083"
],
"matched_keywords": ["fuel cell"],
"matched_ipc_symbols": ["H01M8/083"],
"text_retrieval": false,
"ipc": [
"H01M 8/06 20060101AFI20151215BHUS",
@@ -515,12 +465,8 @@
"topic_score": 1.0,
"text_score": 1.0,
"topic_match_kind": "topic_id",
"matched_keywords": [
"fuel cell"
],
"matched_ipc_symbols": [
"H01M8/083"
],
"matched_keywords": ["fuel cell"],
"matched_ipc_symbols": ["H01M8/083"],
"text_retrieval": false,
"ipc": [
"H01M 8/04 20060101AFI20150714BHUS",
@@ -548,12 +494,8 @@
"topic_score": 1.0,
"text_score": 1.0,
"topic_match_kind": "topic_id",
"matched_keywords": [
"fuel cell"
],
"matched_ipc_symbols": [
"H01M8/083"
],
"matched_keywords": ["fuel cell"],
"matched_ipc_symbols": ["H01M8/083"],
"text_retrieval": false,
"ipc": [
"H01M 8/22 20060101AFI20150310BHUS",
@@ -579,12 +521,8 @@
"topic_score": 1.0,
"text_score": 1.0,
"topic_match_kind": "topic_id",
"matched_keywords": [
"fuel cell"
],
"matched_ipc_symbols": [
"H01M8/083"
],
"matched_keywords": ["fuel cell"],
"matched_ipc_symbols": ["H01M8/083"],
"text_retrieval": false,
"ipc": [
"H01M 8/10 20060101AFI20150310BHUS",
@@ -621,12 +559,8 @@
"topic_score": 1.0,
"text_score": 1.0,
"topic_match_kind": "topic_id",
"matched_keywords": [
"fuel cell"
],
"matched_ipc_symbols": [
"H01M8/083"
],
"matched_keywords": ["fuel cell"],
"matched_ipc_symbols": ["H01M8/083"],
"text_retrieval": false,
"ipc": [
"H01M 8/06 20060101AFI20141125BHUS",
@@ -652,12 +586,8 @@
"topic_score": 1.0,
"text_score": 1.0,
"topic_match_kind": "topic_id",
"matched_keywords": [
"fuel cell"
],
"matched_ipc_symbols": [
"H01M8/083"
],
"matched_keywords": ["fuel cell"],
"matched_ipc_symbols": ["H01M8/083"],
"text_retrieval": false,
"ipc": [
"H01M 8/08 20060101AFI20140930BHUS",
@@ -685,12 +615,8 @@
"topic_score": 1.0,
"text_score": 0.6666666666666666,
"topic_match_kind": "topic_id",
"matched_keywords": [
"fuel cell"
],
"matched_ipc_symbols": [
"H01M8/083"
],
"matched_keywords": ["fuel cell"],
"matched_ipc_symbols": ["H01M8/083"],
"text_retrieval": false,
"ipc": [
"H01M 4/90 20060101AFI20251230BHUS",
@@ -719,12 +645,8 @@
"topic_score": 1.0,
"text_score": 0.6666666666666666,
"topic_match_kind": "topic_id",
"matched_keywords": [
"fuel cell"
],
"matched_ipc_symbols": [
"H01M8/083"
],
"matched_keywords": ["fuel cell"],
"matched_ipc_symbols": ["H01M8/083"],
"text_retrieval": false,
"ipc": [
"H01M 8/04082 20160101AFI20250909BHUS",
@@ -754,12 +676,8 @@
"topic_score": 1.0,
"text_score": 0.6666666666666666,
"topic_match_kind": "topic_id",
"matched_keywords": [
"fuel cell"
],
"matched_ipc_symbols": [
"H01M8/083"
],
"matched_keywords": ["fuel cell"],
"matched_ipc_symbols": ["H01M8/083"],
"text_retrieval": false,
"ipc": [
"H01M 8/083 20160101AFI20250722BHUS",
@@ -825,10 +743,7 @@
"US12412912",
"US12368175"
],
"irrelevant_patent_ids": [
"US10847825",
"EP3549641"
]
"irrelevant_patent_ids": ["US10847825", "EP3549641"]
},
{
"id": "speech-recognition",
@@ -844,9 +759,7 @@
"relevance_score": 1.0
}
],
"expected_ipc_prefixes": [
"G10L"
],
"expected_ipc_prefixes": ["G10L"],
"mapping_status": "mapped",
"diagnostics": {
"search_path": "ipc",
@@ -895,12 +808,8 @@
"topic_score": 1.0,
"text_score": 0.6666666666666666,
"topic_match_kind": "topic_id",
"matched_keywords": [
"speech recognition"
],
"matched_ipc_symbols": [
"H04M2201/405"
],
"matched_keywords": ["speech recognition"],
"matched_ipc_symbols": ["H04M2201/405"],
"text_retrieval": false,
"ipc": [
"G10L 15/00 20130101AFI20241105BHUS",
@@ -947,12 +856,8 @@
"topic_score": 1.0,
"text_score": 0.6666666666666666,
"topic_match_kind": "topic_id",
"matched_keywords": [
"speech recognition"
],
"matched_ipc_symbols": [
"H04M2201/405"
],
"matched_keywords": ["speech recognition"],
"matched_ipc_symbols": ["H04M2201/405"],
"text_retrieval": false,
"ipc": [
"G10L 15/00 20130101AFI20230411BHUS",
@@ -999,12 +904,8 @@
"topic_score": 1.0,
"text_score": 0.6666666666666666,
"topic_match_kind": "topic_id",
"matched_keywords": [
"speech recognition"
],
"matched_ipc_symbols": [
"H04M2201/405"
],
"matched_keywords": ["speech recognition"],
"matched_ipc_symbols": ["H04M2201/405"],
"text_retrieval": false,
"ipc": [
"H04M 3/42 20060101AFI20230307BHUS",
@@ -1033,12 +934,8 @@
"topic_score": 1.0,
"text_score": 0.6666666666666666,
"topic_match_kind": "topic_id",
"matched_keywords": [
"speech recognition"
],
"matched_ipc_symbols": [
"H04M2201/405"
],
"matched_keywords": ["speech recognition"],
"matched_ipc_symbols": ["H04M2201/405"],
"text_retrieval": false,
"ipc": [
"H04M 3/42 20060101AFI20200811BHUS",
@@ -1085,12 +982,8 @@
"topic_score": 1.0,
"text_score": 0.6666666666666666,
"topic_match_kind": "topic_id",
"matched_keywords": [
"speech recognition"
],
"matched_ipc_symbols": [
"H04M2201/405"
],
"matched_keywords": ["speech recognition"],
"matched_ipc_symbols": ["H04M2201/405"],
"text_retrieval": false,
"ipc": [
"H04M 3/493 20060101AFI20170919BHUS",
@@ -1142,12 +1035,8 @@
"topic_score": 1.0,
"text_score": 0.6666666666666666,
"topic_match_kind": "topic_id",
"matched_keywords": [
"speech recognition"
],
"matched_ipc_symbols": [
"H04M2201/405"
],
"matched_keywords": ["speech recognition"],
"matched_ipc_symbols": ["H04M2201/405"],
"text_retrieval": false,
"ipc": [
"G10L 17/00 20130101AFI20170620BHUS",
@@ -1180,12 +1069,8 @@
"topic_score": 1.0,
"text_score": 0.6666666666666666,
"topic_match_kind": "topic_id",
"matched_keywords": [
"speech recognition"
],
"matched_ipc_symbols": [
"H04M2201/405"
],
"matched_keywords": ["speech recognition"],
"matched_ipc_symbols": ["H04M2201/405"],
"text_retrieval": false,
"ipc": [
"G06F 3/16 20060101AFI20160628BHUS",
@@ -1220,12 +1105,8 @@
"topic_score": 1.0,
"text_score": 1.0,
"topic_match_kind": "topic_id",
"matched_keywords": [
"speech recognition"
],
"matched_ipc_symbols": [
"H04M2201/405"
],
"matched_keywords": ["speech recognition"],
"matched_ipc_symbols": ["H04M2201/405"],
"text_retrieval": false,
"ipc": [
"H04M 1/64 20060101AFI20170815BHUS",
@@ -1258,12 +1139,8 @@
"topic_score": 1.0,
"text_score": 0.3333333333333333,
"topic_match_kind": "topic_id",
"matched_keywords": [
"speech recognition"
],
"matched_ipc_symbols": [
"G10L17/14"
],
"matched_keywords": ["speech recognition"],
"matched_ipc_symbols": ["G10L17/14"],
"text_retrieval": false,
"ipc": [
"G10L 17/14 20130101AFI20260317BHUS",
@@ -1299,12 +1176,8 @@
"topic_score": 1.0,
"text_score": 0.3333333333333333,
"topic_match_kind": "topic_id",
"matched_keywords": [
"speech recognition"
],
"matched_ipc_symbols": [
"G10L17/14"
],
"matched_keywords": ["speech recognition"],
"matched_ipc_symbols": ["G10L17/14"],
"text_retrieval": false,
"ipc": [
"H04M 3/493 20060101AFI20190827BHUS",
@@ -1335,12 +1208,8 @@
"topic_score": 1.0,
"text_score": 0.3333333333333333,
"topic_match_kind": "topic_id",
"matched_keywords": [
"speech recognition"
],
"matched_ipc_symbols": [
"G10L17/14"
],
"matched_keywords": ["speech recognition"],
"matched_ipc_symbols": ["G10L17/14"],
"text_retrieval": false,
"ipc": [
"H04M 3/493 20060101AFI20160614BHUS",
@@ -1376,12 +1245,8 @@
"topic_score": 1.0,
"text_score": 0.3333333333333333,
"topic_match_kind": "topic_id",
"matched_keywords": [
"speech recognition"
],
"matched_ipc_symbols": [
"H04M2201/405"
],
"matched_keywords": ["speech recognition"],
"matched_ipc_symbols": ["H04M2201/405"],
"text_retrieval": false,
"ipc": [
"G10L 15/00 20130101AFI20260428BHUS",
@@ -1424,12 +1289,8 @@
"topic_score": 1.0,
"text_score": 0.3333333333333333,
"topic_match_kind": "topic_id",
"matched_keywords": [
"speech recognition"
],
"matched_ipc_symbols": [
"H04M2201/405"
],
"matched_keywords": ["speech recognition"],
"matched_ipc_symbols": ["H04M2201/405"],
"text_retrieval": false,
"ipc": [
"G10L 17/26 20130101AFI20260331BHUS",
@@ -1480,12 +1341,8 @@
"topic_score": 1.0,
"text_score": 0.3333333333333333,
"topic_match_kind": "topic_id",
"matched_keywords": [
"speech recognition"
],
"matched_ipc_symbols": [
"H04M2201/405"
],
"matched_keywords": ["speech recognition"],
"matched_ipc_symbols": ["H04M2201/405"],
"text_retrieval": false,
"ipc": [
"H04M 3/00 20060101AFI20170214BHUS",
@@ -1526,12 +1383,8 @@
"topic_score": 1.0,
"text_score": 0.6666666666666666,
"topic_match_kind": "topic_id",
"matched_keywords": [
"speech recognition"
],
"matched_ipc_symbols": [
"H04M2201/405"
],
"matched_keywords": ["speech recognition"],
"matched_ipc_symbols": ["H04M2201/405"],
"text_retrieval": false,
"ipc": [
"G10L 15/183 20130101AFI20251125BHUS",
@@ -1568,12 +1421,8 @@
"topic_score": 1.0,
"text_score": 0.6666666666666666,
"topic_match_kind": "topic_id",
"matched_keywords": [
"speech recognition"
],
"matched_ipc_symbols": [
"H04M2201/405"
],
"matched_keywords": ["speech recognition"],
"matched_ipc_symbols": ["H04M2201/405"],
"text_retrieval": false,
"ipc": [
"H04M 3/51 20060101AFI20241029BHUS",
@@ -1616,12 +1465,8 @@
"topic_score": 1.0,
"text_score": 0.6666666666666666,
"topic_match_kind": "topic_id",
"matched_keywords": [
"speech recognition"
],
"matched_ipc_symbols": [
"H04M2201/405"
],
"matched_keywords": ["speech recognition"],
"matched_ipc_symbols": ["H04M2201/405"],
"text_retrieval": false,
"ipc": [
"H04M 3/51 20060101AFI20240910BHUS",
@@ -1664,12 +1509,8 @@
"topic_score": 1.0,
"text_score": 0.6666666666666666,
"topic_match_kind": "topic_id",
"matched_keywords": [
"speech recognition"
],
"matched_ipc_symbols": [
"H04M2201/405"
],
"matched_keywords": ["speech recognition"],
"matched_ipc_symbols": ["H04M2201/405"],
"text_retrieval": false,
"ipc": [
"H04M 3/51 20060101AFI20231107BHUS",
@@ -1712,12 +1553,8 @@
"topic_score": 1.0,
"text_score": 0.6666666666666666,
"topic_match_kind": "topic_id",
"matched_keywords": [
"speech recognition"
],
"matched_ipc_symbols": [
"H04M2201/405"
],
"matched_keywords": ["speech recognition"],
"matched_ipc_symbols": ["H04M2201/405"],
"text_retrieval": false,
"ipc": [
"H04M 3/51 20060101AFI20230718BHUS",
@@ -1760,12 +1597,8 @@
"topic_score": 1.0,
"text_score": 0.6666666666666666,
"topic_match_kind": "topic_id",
"matched_keywords": [
"speech recognition"
],
"matched_ipc_symbols": [
"H04M2201/405"
],
"matched_keywords": ["speech recognition"],
"matched_ipc_symbols": ["H04M2201/405"],
"text_retrieval": false,
"ipc": [
"H04M 11/00 20060101AFI20201208BHUS",
@@ -1837,9 +1670,7 @@
"US11706338",
"US10863033"
],
"irrelevant_patent_ids": [
"US10397400"
]
"irrelevant_patent_ids": ["US10397400"]
}
],
"labeling_status": {
@@ -1851,4 +1682,4 @@
},
"warning": "KI-gestützte Vorlabelierung anhand von Titel sowie IPC/CPC-Evidenz. Für einen wissenschaftlichen Goldstandard sollten Grenzfälle fachlich geprüft werden."
}
}
}
@@ -2,11 +2,7 @@
"version": 1,
"presentation": true,
"description": "goldset for two IPC cases.",
"ks": [
5,
10,
20
],
"ks": [5, 10, 20],
"cases": [
{
"id": "fuel-cell",
@@ -22,9 +18,7 @@
"relevance_score": 1.0
}
],
"expected_ipc_prefixes": [
"H01M"
],
"expected_ipc_prefixes": ["H01M"],
"relevant_patent_ids": [
"US12087951",
"US10916789",
@@ -45,10 +39,7 @@
"US12412912",
"US12368175"
],
"irrelevant_patent_ids": [
"US10847825",
"EP3549641"
],
"irrelevant_patent_ids": ["US10847825", "EP3549641"],
"relevance_grades": {
"US12087951": 2,
"US10916789": 2,
@@ -82,12 +73,8 @@
"topic_score": 1.0,
"text_score": 1.0,
"topic_match_kind": "topic_id",
"matched_keywords": [
"fuel cell"
],
"matched_ipc_symbols": [
"H01M8/083"
],
"matched_keywords": ["fuel cell"],
"matched_ipc_symbols": ["H01M8/083"],
"text_retrieval": false,
"ipc": [
"H01M 4/90 20060101AFI20240910BHUS",
@@ -116,12 +103,8 @@
"topic_score": 1.0,
"text_score": 1.0,
"topic_match_kind": "topic_id",
"matched_keywords": [
"fuel cell"
],
"matched_ipc_symbols": [
"H01M8/083"
],
"matched_keywords": ["fuel cell"],
"matched_ipc_symbols": ["H01M8/083"],
"text_retrieval": false,
"ipc": [
"H01M 8/083 20160101AFI20210209BHUS",
@@ -167,12 +150,8 @@
"topic_score": 1.0,
"text_score": 1.0,
"topic_match_kind": "topic_id",
"matched_keywords": [
"fuel cell"
],
"matched_ipc_symbols": [
"H01M8/083"
],
"matched_keywords": ["fuel cell"],
"matched_ipc_symbols": ["H01M8/083"],
"text_retrieval": false,
"ipc": [
"H01M 8/06 20160101AFI20201124BHUS",
@@ -203,12 +182,8 @@
"topic_score": 1.0,
"text_score": 1.0,
"topic_match_kind": "topic_id",
"matched_keywords": [
"fuel cell"
],
"matched_ipc_symbols": [
"H01M8/083"
],
"matched_keywords": ["fuel cell"],
"matched_ipc_symbols": ["H01M8/083"],
"text_retrieval": false,
"ipc": [
"H01M 8/0221 20160101AFI20201124BHUS",
@@ -254,12 +229,8 @@
"topic_score": 1.0,
"text_score": 1.0,
"topic_match_kind": "topic_id",
"matched_keywords": [
"fuel cell"
],
"matched_ipc_symbols": [
"H01M8/083"
],
"matched_keywords": ["fuel cell"],
"matched_ipc_symbols": ["H01M8/083"],
"text_retrieval": false,
"ipc": [
"A62C 3/06 20060101AFI20190820BHEP",
@@ -285,12 +256,8 @@
"topic_score": 1.0,
"text_score": 1.0,
"topic_match_kind": "topic_id",
"matched_keywords": [
"fuel cell"
],
"matched_ipc_symbols": [
"H01M8/083"
],
"matched_keywords": ["fuel cell"],
"matched_ipc_symbols": ["H01M8/083"],
"text_retrieval": false,
"ipc": [
"H01M 12/08 20060101AFI20190521BHUS",
@@ -326,12 +293,8 @@
"topic_score": 1.0,
"text_score": 1.0,
"topic_match_kind": "topic_id",
"matched_keywords": [
"fuel cell"
],
"matched_ipc_symbols": [
"H01M8/083"
],
"matched_keywords": ["fuel cell"],
"matched_ipc_symbols": ["H01M8/083"],
"text_retrieval": false,
"ipc": [
"H01M 4/36 20060101AFI20181009BHUS",
@@ -363,12 +326,8 @@
"topic_score": 1.0,
"text_score": 1.0,
"topic_match_kind": "topic_id",
"matched_keywords": [
"fuel cell"
],
"matched_ipc_symbols": [
"H01M8/083"
],
"matched_keywords": ["fuel cell"],
"matched_ipc_symbols": ["H01M8/083"],
"text_retrieval": false,
"ipc": [
"H01M 8/08 20160101AFI20180626BHUS",
@@ -404,12 +363,8 @@
"topic_score": 1.0,
"text_score": 1.0,
"topic_match_kind": "topic_id",
"matched_keywords": [
"fuel cell"
],
"matched_ipc_symbols": [
"H01M8/083"
],
"matched_keywords": ["fuel cell"],
"matched_ipc_symbols": ["H01M8/083"],
"text_retrieval": false,
"ipc": [
"H01M 8/0656 20160101AFI20170424BHEP",
@@ -436,12 +391,8 @@
"topic_score": 1.0,
"text_score": 1.0,
"topic_match_kind": "topic_id",
"matched_keywords": [
"fuel cell"
],
"matched_ipc_symbols": [
"H01M8/083"
],
"matched_keywords": ["fuel cell"],
"matched_ipc_symbols": ["H01M8/083"],
"text_retrieval": false,
"ipc": [
"H01M 8/08 20160101AFI20170207BHUS",
@@ -470,12 +421,8 @@
"topic_score": 1.0,
"text_score": 1.0,
"topic_match_kind": "topic_id",
"matched_keywords": [
"fuel cell"
],
"matched_ipc_symbols": [
"H01M8/083"
],
"matched_keywords": ["fuel cell"],
"matched_ipc_symbols": ["H01M8/083"],
"text_retrieval": false,
"ipc": [
"H01M 8/06 20060101AFI20160614BHUS",
@@ -509,12 +456,8 @@
"topic_score": 1.0,
"text_score": 1.0,
"topic_match_kind": "topic_id",
"matched_keywords": [
"fuel cell"
],
"matched_ipc_symbols": [
"H01M8/083"
],
"matched_keywords": ["fuel cell"],
"matched_ipc_symbols": ["H01M8/083"],
"text_retrieval": false,
"ipc": [
"H01M 8/06 20060101AFI20151215BHUS",
@@ -540,12 +483,8 @@
"topic_score": 1.0,
"text_score": 1.0,
"topic_match_kind": "topic_id",
"matched_keywords": [
"fuel cell"
],
"matched_ipc_symbols": [
"H01M8/083"
],
"matched_keywords": ["fuel cell"],
"matched_ipc_symbols": ["H01M8/083"],
"text_retrieval": false,
"ipc": [
"H01M 8/04 20060101AFI20150714BHUS",
@@ -573,12 +512,8 @@
"topic_score": 1.0,
"text_score": 1.0,
"topic_match_kind": "topic_id",
"matched_keywords": [
"fuel cell"
],
"matched_ipc_symbols": [
"H01M8/083"
],
"matched_keywords": ["fuel cell"],
"matched_ipc_symbols": ["H01M8/083"],
"text_retrieval": false,
"ipc": [
"H01M 8/22 20060101AFI20150310BHUS",
@@ -604,12 +539,8 @@
"topic_score": 1.0,
"text_score": 1.0,
"topic_match_kind": "topic_id",
"matched_keywords": [
"fuel cell"
],
"matched_ipc_symbols": [
"H01M8/083"
],
"matched_keywords": ["fuel cell"],
"matched_ipc_symbols": ["H01M8/083"],
"text_retrieval": false,
"ipc": [
"H01M 8/10 20060101AFI20150310BHUS",
@@ -646,12 +577,8 @@
"topic_score": 1.0,
"text_score": 1.0,
"topic_match_kind": "topic_id",
"matched_keywords": [
"fuel cell"
],
"matched_ipc_symbols": [
"H01M8/083"
],
"matched_keywords": ["fuel cell"],
"matched_ipc_symbols": ["H01M8/083"],
"text_retrieval": false,
"ipc": [
"H01M 8/06 20060101AFI20141125BHUS",
@@ -677,12 +604,8 @@
"topic_score": 1.0,
"text_score": 1.0,
"topic_match_kind": "topic_id",
"matched_keywords": [
"fuel cell"
],
"matched_ipc_symbols": [
"H01M8/083"
],
"matched_keywords": ["fuel cell"],
"matched_ipc_symbols": ["H01M8/083"],
"text_retrieval": false,
"ipc": [
"H01M 8/08 20060101AFI20140930BHUS",
@@ -710,12 +633,8 @@
"topic_score": 1.0,
"text_score": 0.6666666666666666,
"topic_match_kind": "topic_id",
"matched_keywords": [
"fuel cell"
],
"matched_ipc_symbols": [
"H01M8/083"
],
"matched_keywords": ["fuel cell"],
"matched_ipc_symbols": ["H01M8/083"],
"text_retrieval": false,
"ipc": [
"H01M 4/90 20060101AFI20251230BHUS",
@@ -744,12 +663,8 @@
"topic_score": 1.0,
"text_score": 0.6666666666666666,
"topic_match_kind": "topic_id",
"matched_keywords": [
"fuel cell"
],
"matched_ipc_symbols": [
"H01M8/083"
],
"matched_keywords": ["fuel cell"],
"matched_ipc_symbols": ["H01M8/083"],
"text_retrieval": false,
"ipc": [
"H01M 8/04082 20160101AFI20250909BHUS",
@@ -779,12 +694,8 @@
"topic_score": 1.0,
"text_score": 0.6666666666666666,
"topic_match_kind": "topic_id",
"matched_keywords": [
"fuel cell"
],
"matched_ipc_symbols": [
"H01M8/083"
],
"matched_keywords": ["fuel cell"],
"matched_ipc_symbols": ["H01M8/083"],
"text_retrieval": false,
"ipc": [
"H01M 8/083 20160101AFI20250722BHUS",
@@ -823,9 +734,7 @@
"relevance_score": 1.0
}
],
"expected_ipc_prefixes": [
"G10L"
],
"expected_ipc_prefixes": ["G10L"],
"relevant_patent_ids": [
"US12137183",
"US11627221",
@@ -847,9 +756,7 @@
"US11706338",
"US10863033"
],
"irrelevant_patent_ids": [
"US10397400"
],
"irrelevant_patent_ids": ["US10397400"],
"relevance_grades": {
"US12137183": 2,
"US11627221": 2,
@@ -883,12 +790,8 @@
"topic_score": 1.0,
"text_score": 0.6666666666666666,
"topic_match_kind": "topic_id",
"matched_keywords": [
"speech recognition"
],
"matched_ipc_symbols": [
"H04M2201/405"
],
"matched_keywords": ["speech recognition"],
"matched_ipc_symbols": ["H04M2201/405"],
"text_retrieval": false,
"ipc": [
"G10L 15/00 20130101AFI20241105BHUS",
@@ -935,12 +838,8 @@
"topic_score": 1.0,
"text_score": 0.6666666666666666,
"topic_match_kind": "topic_id",
"matched_keywords": [
"speech recognition"
],
"matched_ipc_symbols": [
"H04M2201/405"
],
"matched_keywords": ["speech recognition"],
"matched_ipc_symbols": ["H04M2201/405"],
"text_retrieval": false,
"ipc": [
"G10L 15/00 20130101AFI20230411BHUS",
@@ -987,12 +886,8 @@
"topic_score": 1.0,
"text_score": 0.6666666666666666,
"topic_match_kind": "topic_id",
"matched_keywords": [
"speech recognition"
],
"matched_ipc_symbols": [
"H04M2201/405"
],
"matched_keywords": ["speech recognition"],
"matched_ipc_symbols": ["H04M2201/405"],
"text_retrieval": false,
"ipc": [
"H04M 3/42 20060101AFI20230307BHUS",
@@ -1021,12 +916,8 @@
"topic_score": 1.0,
"text_score": 0.6666666666666666,
"topic_match_kind": "topic_id",
"matched_keywords": [
"speech recognition"
],
"matched_ipc_symbols": [
"H04M2201/405"
],
"matched_keywords": ["speech recognition"],
"matched_ipc_symbols": ["H04M2201/405"],
"text_retrieval": false,
"ipc": [
"H04M 3/42 20060101AFI20200811BHUS",
@@ -1073,12 +964,8 @@
"topic_score": 1.0,
"text_score": 0.6666666666666666,
"topic_match_kind": "topic_id",
"matched_keywords": [
"speech recognition"
],
"matched_ipc_symbols": [
"H04M2201/405"
],
"matched_keywords": ["speech recognition"],
"matched_ipc_symbols": ["H04M2201/405"],
"text_retrieval": false,
"ipc": [
"H04M 3/493 20060101AFI20170919BHUS",
@@ -1130,12 +1017,8 @@
"topic_score": 1.0,
"text_score": 0.6666666666666666,
"topic_match_kind": "topic_id",
"matched_keywords": [
"speech recognition"
],
"matched_ipc_symbols": [
"H04M2201/405"
],
"matched_keywords": ["speech recognition"],
"matched_ipc_symbols": ["H04M2201/405"],
"text_retrieval": false,
"ipc": [
"G10L 17/00 20130101AFI20170620BHUS",
@@ -1168,12 +1051,8 @@
"topic_score": 1.0,
"text_score": 0.6666666666666666,
"topic_match_kind": "topic_id",
"matched_keywords": [
"speech recognition"
],
"matched_ipc_symbols": [
"H04M2201/405"
],
"matched_keywords": ["speech recognition"],
"matched_ipc_symbols": ["H04M2201/405"],
"text_retrieval": false,
"ipc": [
"G06F 3/16 20060101AFI20160628BHUS",
@@ -1208,12 +1087,8 @@
"topic_score": 1.0,
"text_score": 1.0,
"topic_match_kind": "topic_id",
"matched_keywords": [
"speech recognition"
],
"matched_ipc_symbols": [
"H04M2201/405"
],
"matched_keywords": ["speech recognition"],
"matched_ipc_symbols": ["H04M2201/405"],
"text_retrieval": false,
"ipc": [
"H04M 1/64 20060101AFI20170815BHUS",
@@ -1246,12 +1121,8 @@
"topic_score": 1.0,
"text_score": 0.3333333333333333,
"topic_match_kind": "topic_id",
"matched_keywords": [
"speech recognition"
],
"matched_ipc_symbols": [
"G10L17/14"
],
"matched_keywords": ["speech recognition"],
"matched_ipc_symbols": ["G10L17/14"],
"text_retrieval": false,
"ipc": [
"G10L 17/14 20130101AFI20260317BHUS",
@@ -1287,12 +1158,8 @@
"topic_score": 1.0,
"text_score": 0.3333333333333333,
"topic_match_kind": "topic_id",
"matched_keywords": [
"speech recognition"
],
"matched_ipc_symbols": [
"G10L17/14"
],
"matched_keywords": ["speech recognition"],
"matched_ipc_symbols": ["G10L17/14"],
"text_retrieval": false,
"ipc": [
"H04M 3/493 20060101AFI20190827BHUS",
@@ -1323,12 +1190,8 @@
"topic_score": 1.0,
"text_score": 0.3333333333333333,
"topic_match_kind": "topic_id",
"matched_keywords": [
"speech recognition"
],
"matched_ipc_symbols": [
"G10L17/14"
],
"matched_keywords": ["speech recognition"],
"matched_ipc_symbols": ["G10L17/14"],
"text_retrieval": false,
"ipc": [
"H04M 3/493 20060101AFI20160614BHUS",
@@ -1364,12 +1227,8 @@
"topic_score": 1.0,
"text_score": 0.3333333333333333,
"topic_match_kind": "topic_id",
"matched_keywords": [
"speech recognition"
],
"matched_ipc_symbols": [
"H04M2201/405"
],
"matched_keywords": ["speech recognition"],
"matched_ipc_symbols": ["H04M2201/405"],
"text_retrieval": false,
"ipc": [
"G10L 15/00 20130101AFI20260428BHUS",
@@ -1412,12 +1271,8 @@
"topic_score": 1.0,
"text_score": 0.3333333333333333,
"topic_match_kind": "topic_id",
"matched_keywords": [
"speech recognition"
],
"matched_ipc_symbols": [
"H04M2201/405"
],
"matched_keywords": ["speech recognition"],
"matched_ipc_symbols": ["H04M2201/405"],
"text_retrieval": false,
"ipc": [
"G10L 17/26 20130101AFI20260331BHUS",
@@ -1468,12 +1323,8 @@
"topic_score": 1.0,
"text_score": 0.3333333333333333,
"topic_match_kind": "topic_id",
"matched_keywords": [
"speech recognition"
],
"matched_ipc_symbols": [
"H04M2201/405"
],
"matched_keywords": ["speech recognition"],
"matched_ipc_symbols": ["H04M2201/405"],
"text_retrieval": false,
"ipc": [
"H04M 3/00 20060101AFI20170214BHUS",
@@ -1514,12 +1365,8 @@
"topic_score": 1.0,
"text_score": 0.6666666666666666,
"topic_match_kind": "topic_id",
"matched_keywords": [
"speech recognition"
],
"matched_ipc_symbols": [
"H04M2201/405"
],
"matched_keywords": ["speech recognition"],
"matched_ipc_symbols": ["H04M2201/405"],
"text_retrieval": false,
"ipc": [
"G10L 15/183 20130101AFI20251125BHUS",
@@ -1556,12 +1403,8 @@
"topic_score": 1.0,
"text_score": 0.6666666666666666,
"topic_match_kind": "topic_id",
"matched_keywords": [
"speech recognition"
],
"matched_ipc_symbols": [
"H04M2201/405"
],
"matched_keywords": ["speech recognition"],
"matched_ipc_symbols": ["H04M2201/405"],
"text_retrieval": false,
"ipc": [
"H04M 3/51 20060101AFI20241029BHUS",
@@ -1604,12 +1447,8 @@
"topic_score": 1.0,
"text_score": 0.6666666666666666,
"topic_match_kind": "topic_id",
"matched_keywords": [
"speech recognition"
],
"matched_ipc_symbols": [
"H04M2201/405"
],
"matched_keywords": ["speech recognition"],
"matched_ipc_symbols": ["H04M2201/405"],
"text_retrieval": false,
"ipc": [
"H04M 3/51 20060101AFI20240910BHUS",
@@ -1652,12 +1491,8 @@
"topic_score": 1.0,
"text_score": 0.6666666666666666,
"topic_match_kind": "topic_id",
"matched_keywords": [
"speech recognition"
],
"matched_ipc_symbols": [
"H04M2201/405"
],
"matched_keywords": ["speech recognition"],
"matched_ipc_symbols": ["H04M2201/405"],
"text_retrieval": false,
"ipc": [
"H04M 3/51 20060101AFI20231107BHUS",
@@ -1700,12 +1535,8 @@
"topic_score": 1.0,
"text_score": 0.6666666666666666,
"topic_match_kind": "topic_id",
"matched_keywords": [
"speech recognition"
],
"matched_ipc_symbols": [
"H04M2201/405"
],
"matched_keywords": ["speech recognition"],
"matched_ipc_symbols": ["H04M2201/405"],
"text_retrieval": false,
"ipc": [
"H04M 3/51 20060101AFI20230718BHUS",
@@ -1748,12 +1579,8 @@
"topic_score": 1.0,
"text_score": 0.6666666666666666,
"topic_match_kind": "topic_id",
"matched_keywords": [
"speech recognition"
],
"matched_ipc_symbols": [
"H04M2201/405"
],
"matched_keywords": ["speech recognition"],
"matched_ipc_symbols": ["H04M2201/405"],
"text_retrieval": false,
"ipc": [
"H04M 11/00 20060101AFI20201208BHUS",
@@ -1784,4 +1611,4 @@
]
}
]
}
}
+102 -120
View File
@@ -12,14 +12,34 @@ import pandas as pd
import json
from datetime import datetime
import sys
from elasticsearch import Elasticsearch, helpers
from elasticsearch.helpers import bulk,BulkIndexError
import os
import math
import requests
import hashlib
import argparse
import logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger(__name__)
download_path=os.path.abspath(os.getcwd())
es = Elasticsearch()
# The INSE key is index-scoped and can't hit cluster endpoints (e.g. GET /), so
# the elasticsearch client's ping/product-check would 403. We POST to _bulk
# directly over HTTP with the ApiKey header, like the other jobs do.
ES_URL = os.getenv("ELASTICSEARCH_INSE_URL", "http://localhost:9200").rstrip("/")
ES_API_KEY = os.getenv("ELASTICSEARCH_INSE_API_KEY")
# Default is a test index — you lack rights to push to the production index;
# contact the ES admin for that. Override via BUND_UPLOAD_INDEX.
# The target index is never created here: an index that doesn't exist yet gets
# ES dynamic mapping, without the searchabilityAnalyzer the search relies on.
# Create it with the proper mapping before pointing a run at a new index.
INDEX_NAME = os.getenv("BUND_UPLOAD_INDEX", "projects_bund_test")
_session = requests.Session()
if ES_API_KEY:
_session.headers.update({"Authorization": f"ApiKey {ES_API_KEY}"})
def crawl_data(link,driver):
driver.get(link)
@@ -41,123 +61,61 @@ def crawl_data(link,driver):
time.sleep(2)
# Switch to the alert and Clicks the "OK" button
Alert(driver).accept()
print("downloading data")
logger.info("downloading data")
else:
# The element is likely a honeypot, do not interact
print("Honeypot detected, skipping interaction")
logger.info("Honeypot detected, skipping interaction")
def check_elastic_online():
if not es.ping():
sys.exit("No connection to Elasticsearch")
else :
print("Elasticsearch connection established")
def check_elastic_index(df, index_name):
if not es.indices.exists(index=index_name):
print(index_name + " index wasn't found. Creating a new one..")
settings = {
"analysis": {
"analyzer": {
"searchabilityAnalyzer": {
"type": "custom",
"tokenizer": "standard",
"filter": [
"lowercase",
"asciifolding"
]
}
}
}
}
mappings = {}
properties = {}
def _clean(value):
# pandas/numpy scalars -> native python; NaN -> None (ES rejects NaN in JSON).
if hasattr(value, "item"):
value = value.item()
if isinstance(value, float) and math.isnan(value):
return None
return value
for key in list(df.columns):
if key in ("funding_start", "funding_end", "datum"):
properties[key] = {
"type": "date",
"format": "dd.MM.yyyy"
}
elif key == "Publikationsdatum":
properties[key] = {
"type": "date",
"format": "yyyy"
}
elif key == "unix_timestamp":
properties[key] = {
"type": "long"
}
elif key == "Fördersumme":
properties[key] = {
"type": "float"
}
elif key == "new":
properties[key] = {
"type": "boolean"
}
else:
properties[key] = {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
mappings["properties"] = properties
es.indices.create(index=index_name, mappings=mappings, settings=settings)
es.indices.refresh(index=index_name)
print("The new index '"+index_name+"' has been created")
else:
print(index_name + " already exists. Uploading data...")
def upload_data(df, index_name):
logger.info("Uploading data...")
def upload_data(df,index_name):
def fill_docs_to_upload(row):
docs = []
for _, row in df.iterrows():
doc_id = hashlib.sha256(str(row['Förderkennzeichen']).encode('utf-8')).hexdigest()
doc = {
"_op_type": "update", # Update existing documents
"_index": index_name,
"_id": doc_id,
"doc": {
"new":False
},
"upsert":{
**row.to_dict(),
"new":True
}
}
source = {key: _clean(val) for key, val in row.to_dict().items()}
source["new"] = True
docs.append((doc_id, source))
docs_to_upload.append(doc)
print("Uploading data...")
try:
check_elastic_index(df, index_name)
except Exception as e:
print("Error while creating index")
print(e)
docs_to_upload = []
df.apply(fill_docs_to_upload,axis=1)
def bulk_docs(docs,data_rate):
response_sum = 0
for i in range(0, len(docs), data_rate):
try:
response = helpers.bulk(es,docs[i:i + data_rate])
response_sum = response_sum + response[0]
except BulkIndexError as e:
print(f"{len(e.errors)} document(s) failed to index.")
for error in e.errors:
print("Error details:", error)
print ("Upload is completed. "+ str(response_sum) +" documents have been uploaded." )
data_rate = 200
bulk_docs(docs_to_upload,data_rate)
uploaded = 0
for i in range(0, len(docs), data_rate):
batch = docs[i:i + data_rate]
lines = []
for doc_id, source in batch:
# update + upsert: flag an existing project as not-new, or create an
# unseen one from the row (with new=True).
lines.append(json.dumps({"update": {"_index": index_name, "_id": doc_id}}))
lines.append(json.dumps({"doc": {"new": False}, "upsert": source}, default=str))
payload = ("\n".join(lines) + "\n").encode("utf-8")
response = _session.post(
f"{ES_URL}/_bulk",
data=payload,
headers={"Content-Type": "application/x-ndjson"},
)
response.raise_for_status()
result = response.json()
if result.get("errors"):
failed = [item for item in result["items"]
if next(iter(item.values())).get("status", 200) >= 300]
logger.error(f"{len(failed)} document(s) failed to index.")
for item in failed[:5]:
logger.error(f"Error details: {item}")
uploaded += len(batch) - len(failed)
else:
uploaded += len(batch)
logger.info(f"Upload is completed. {uploaded} documents have been uploaded to '{index_name}'.")
@@ -170,7 +128,7 @@ def wait_for_file_complete(download_path,file_name):
fname.endswith(".part") or fname.endswith(".crdownload")
for fname in os.listdir(download_path)
):
print(f"Download complete: {file_name}")
logger.info(f"Download complete: {file_name}")
return True
if any(fname.endswith((".part", ".crdownload")) for fname in os.listdir(download_path)):
time.sleep(1)
@@ -180,7 +138,7 @@ def wait_for_file_complete(download_path,file_name):
def format_data(df):
print("Formattind data...")
logger.info("Formatting data...")
df.drop(list(df.filter(regex='.1|Unnamed')), axis=1, inplace=True)
def clean_format(text):
if isinstance(text, str):
@@ -233,7 +191,10 @@ def setup_chrome_driver(download_path):
"download.directory_upgrade": True,
"plugins.always_open_pdf_externally": True,
})
chromedriver_path = "/home/inse/miniconda3/envs/airflow/bin/chromedriver"
chrome_bin = os.getenv("CHROME_BIN")
if chrome_bin:
options.binary_location = chrome_bin
chromedriver_path = os.getenv("CHROMEDRIVER_PATH", "/usr/bin/chromedriver")
service = Service(executable_path=chromedriver_path)
driver = webdriver.Chrome(service=service, options=options)
return driver
@@ -241,7 +202,23 @@ def setup_chrome_driver(download_path):
# main - entry point
if __name__ == '__main__':
print("Starting")
parser = argparse.ArgumentParser(
description="Crawl the bund foerderportal project export and upload it to Elasticsearch."
)
parser.add_argument(
"--skip-upload",
action="store_true",
help="Only crawl and format the export; never connect to Elasticsearch",
)
parser.add_argument(
"--max-rows",
type=int,
default=None,
help="Keep at most this many rows of the formatted export (e.g. for a smoke test).",
)
args = parser.parse_args()
logger.info("Starting")
file_path = os.path.join(os.path.abspath(os.getcwd()), 'Suchliste.csv')
if not os.path.exists(file_path):
driver = setup_chrome_driver(download_path)
@@ -249,14 +226,19 @@ if __name__ == '__main__':
crawl_data(link_to_crawl,driver)
wait_for_file_complete(download_path, "Suchliste.csv")
driver.close()
file = pd.read_csv(file_path,encoding = "latin1",sep=";")
df = pd.DataFrame(file)
df_formatted = format_data(df)
index_name = "projects_bund_test" #test indices to make sure everything works before uploading to the real index, ps. you lack rights to push to the real index, please contact the admin if you want to push to the real index
check_elastic_online()
upload_data(df_formatted,index_name)
os.remove(file_path)
if args.max_rows:
df_formatted = df_formatted.head(args.max_rows)
if args.skip_upload:
logger.info(f"Skipping upload (--skip-upload): Elasticsearch was not contacted. "
f"Formatted {len(df_formatted)} rows.")
else:
upload_data(df_formatted, INDEX_NAME)
os.remove(file_path)
+10 -1
View File
@@ -12,8 +12,17 @@ ELASTICSEARCH_API_KEY=am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ
ELASTICSEARCH_INSE_URL=https://inse.nes.uni-due.de/elastic
ELASTICSEARCH_INSE_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
# Debugging: Log every outgoing Elasticsearch query (index + payload)
PRINT_ES_QUERIES=false
# Debugging: Log the duration of every Elasticsearch request
PRINT_ES_TIMINGS=true
# Sentence Transformers Configuration
SENTENCE_TRANSFORMERS_MODEL_NAME=intfloat/multilingual-e5-base
TOKEN_ISSUER_ID=inse
TOKEN_HMAC_KEY=9dd09c80dd0796fa24bd2007f4cf57fc28c9a38909b7e83bb2d73121c5bc69c7
TOKEN_HMAC_KEY=9dd09c80dd0796fa24bd2007f4cf57fc28c9a38909b7e83bb2d73121c5bc69c7
# Docker-Registry-Login für Background-Jobs (Nexus, nes.uni-due.de)
BACKGROUND_JOBS_REGISTRY_USERNAME=student
BACKGROUND_JOBS_REGISTRY_PASSWORD=nes-student!
@@ -57,6 +57,20 @@ def test_accounts_are_activated_by_default(session):
assert user.activated is True
def test_current_account_profile_includes_all_roles(session):
organization, _, user = create_accounts(session)
user.roles = [UserRole.USER, UserRole.MANAGER]
session.add(user)
session.commit()
profile = service.get_current_account(
session,
access_token(UserRole.MANAGER, user.id, organization.id),
)
assert profile.roles == [UserRole.MANAGER, UserRole.USER]
def test_superadmin_can_deactivate_and_reactivate_account(session):
organization, superadmin, user = create_accounts(session)
token = access_token(UserRole.SUPER_ADMIN, superadmin.id, organization.id)
+8
View File
@@ -256,6 +256,10 @@ class AccessTokenMetadata(BaseTokenData):
effective_organization_id: uuid.UUID = Field(
description="The unique identifier of the organization associated with this access token.",
)
effective_institution_id: str | None = Field(
default=None,
description="The OpenAlex institution ID associated with this access token, if applicable.",
)
def is_impersonating(self) -> bool:
"""Determine if the access token is being used for impersonation.
@@ -303,6 +307,10 @@ class RefreshTokenMetadata(BaseTokenData):
effective_organization_id: uuid.UUID = Field(
description="The unique identifier of the organization associated with this access token.",
)
effective_institution_id: str | None = Field(
default=None,
description="The OpenAlex institution ID associated with this access token, if applicable.",
)
class RefreshToken(RefreshTokenMetadata):
+44
View File
@@ -48,6 +48,7 @@ EFFECTIVE_ACCOUNT_ID_KEY = "effective_account_id"
EFFECTIVE_ROLE_KEY = "effective_role"
EFFECTIVE_ROLES_KEY = "effective_roles"
EFFECTIVE_ORGANIZATION_ID_KEY = "effective_organization_id"
EFFECTIVE_INSTITUTION_ID_KEY = "effective_institution_id"
EPOCH_KEY = "epoch"
USER_FINGERPRINT_HASH_KEY = "user_fingerprint_hash"
@@ -622,6 +623,7 @@ def _get_current_user_access_token_payload(
effective_organization_id=uuid.UUID(
access_token_payload[EFFECTIVE_ORGANIZATION_ID_KEY]
),
effective_institution_id=access_token_payload.get(EFFECTIVE_INSTITUTION_ID_KEY),
user_fingerprint_hash=access_token_payload[USER_FINGERPRINT_HASH_KEY],
)
@@ -667,6 +669,9 @@ def _get_current_user_refresh_token_payload(
effective_organization_id=uuid.UUID(
refresh_token_payload[EFFECTIVE_ORGANIZATION_ID_KEY]
),
effective_institution_id=refresh_token_payload.get(
EFFECTIVE_INSTITUTION_ID_KEY
),
)
logger.debug("Extracted refresh token payload: %s", refresh_token)
@@ -779,6 +784,34 @@ def _get_account_organization(session: Session, account_id: uuid.UUID) -> uuid.U
return account.organization_id
def _get_account_institution_id(
session: Session, account_id: uuid.UUID
) -> Optional[str]:
"""Retrieves the OpenAlex institution ID for the given account ID.
Args:
session (Session): The database session.
account_id (uuid.UUID): The unique identifier of the account for which to retrieve the OpenAlex institution ID.
Returns:
Optional[str]: The OpenAlex institution ID associated with the given account ID, or None if not available.
"""
account = session.get(Account, account_id)
if not account or account.deleted or not account.activated or account.id is None:
raise AccountNotFoundException
organization = session.get(Organization, account.organization_id)
if not organization:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Organization not found.",
)
return organization.openalex_institution_id
def _is_valid_impersonation(
session: Session, real_account_id: uuid.UUID, effective_account_id: uuid.UUID
) -> bool:
@@ -871,6 +904,9 @@ def get_access_token(
organization_id = _get_account_organization(
session=session, account_id=effective_account_id
)
effective_institution_id = _get_account_institution_id(
session=session, account_id=effective_account_id
)
user_fingerprint_hash = _set_access_fp_cookie(response=response)
@@ -879,6 +915,7 @@ def get_access_token(
effective_account_id=effective_account_id,
effective_role=role,
effective_organization_id=organization_id,
effective_institution_id=effective_institution_id,
epoch=epoch,
user_fingerprint_hash=user_fingerprint_hash,
effective_roles=roles,
@@ -889,6 +926,7 @@ def get_access_token(
effective_account_id=effective_account_id,
effective_role=role,
effective_organization_id=organization_id,
effective_institution_id=effective_institution_id,
epoch=epoch,
effective_roles=roles,
)
@@ -993,6 +1031,7 @@ def refresh_access_token(
effective_account_id=refresh_token.effective_account_id,
effective_role=refresh_token.effective_role,
effective_organization_id=refresh_token.effective_organization_id,
effective_institution_id=refresh_token.effective_institution_id,
epoch=refresh_token.epoch,
user_fingerprint_hash=user_fingerprint_hash,
effective_roles=refresh_token.effective_roles,
@@ -1043,6 +1082,7 @@ def _set_refresh_token(
effective_organization_id: uuid.UUID,
epoch: int,
effective_roles: list[UserRole] | None = None,
effective_institution_id: Optional[str] = None,
) -> RefreshTokenMetadata:
"""Builds a refresh token for the specified account IDs, role, organization ID, epoch, and fingerprint hash.
@@ -1068,6 +1108,7 @@ def _set_refresh_token(
EFFECTIVE_ROLE_KEY: effective_role.value,
EFFECTIVE_ROLES_KEY: [role.value for role in effective_roles],
EFFECTIVE_ORGANIZATION_ID_KEY: str(effective_organization_id),
EFFECTIVE_INSTITUTION_ID_KEY: effective_institution_id,
EPOCH_KEY: epoch,
}
@@ -1096,6 +1137,7 @@ def _build_access_token(
epoch: int,
user_fingerprint_hash: str,
effective_roles: list[UserRole] | None = None,
effective_institution_id: Optional[str] = None,
) -> AccessToken:
"""Builds an access token for the specified account IDs, role, organization ID, epoch, and fingerprint hash.
@@ -1123,6 +1165,7 @@ def _build_access_token(
EFFECTIVE_ORGANIZATION_ID_KEY: str(effective_organization_id),
EPOCH_KEY: epoch,
USER_FINGERPRINT_HASH_KEY: user_fingerprint_hash,
EFFECTIVE_INSTITUTION_ID_KEY: effective_institution_id,
}
raw_token = _build_token(
@@ -1139,6 +1182,7 @@ def _build_access_token(
effective_role=effective_role,
effective_roles=effective_roles,
effective_organization_id=effective_organization_id,
effective_institution_id=effective_institution_id,
user_fingerprint_hash=user_fingerprint_hash,
raw_token=raw_token,
)
@@ -147,6 +147,8 @@ def test_token_build_verify_and_fp_checks(in_memory_session, settings_backup):
session=in_memory_session,
)
assert payload[auth_service.REAL_ACCOUNT_ID_KEY] == str(acc.id)
assert payload[auth_service.EFFECTIVE_ROLES_KEY] == [acc.role.value]
assert access_token.effective_roles == [acc.role]
with pytest.raises(Exception):
auth_service._verify_access_token_fp(
@@ -200,6 +202,66 @@ def test_access_and_refresh_token_flow(in_memory_session, settings_backup):
assert refreshed.real_account_id == access_response.access_token.real_account_id
def test_access_and_refresh_token_preserve_multiple_roles(
in_memory_session, settings_backup
):
config_module.settings.token_hmac_key = "multi-role-key"
config_module.settings.token_issuer_id = "multi-role-issuer"
email = "multi-role@example.com"
password = "pwflow"
org, acc = create_org_and_account(in_memory_session, email, password)
acc.roles = [UserRole.USER, UserRole.MANAGER]
in_memory_session.add(acc)
in_memory_session.commit()
in_memory_session.refresh(acc)
assert acc.id is not None
response = Response()
id_token = auth_service._build_id_token(response, acc.id, acc.epoch)
access_response = auth_service.get_access_token(
response, in_memory_session, id_token, acc.id
)
assert access_response.access_token.effective_role == UserRole.MANAGER
assert access_response.access_token.effective_roles == [
UserRole.MANAGER,
UserRole.USER,
]
secure_fgp = _get_cookie_value(response, auth_service.ACCESS_FP_COOKIE_KEY)
access_payload = auth_service._verify_access_token_fp(
secure_fgp=secure_fgp,
raw_access_token=access_response.access_token.raw_token,
session=in_memory_session,
)
assert access_payload[auth_service.EFFECTIVE_ROLE_KEY] == UserRole.MANAGER.value
assert access_payload[auth_service.EFFECTIVE_ROLES_KEY] == [
UserRole.MANAGER.value,
UserRole.USER.value,
]
raw_refresh_token = _get_cookie_value(response, auth_service.REFRESH_TOKEN_COOKIE_KEY)
refresh_payload = auth_service._verify_refresh_token(
raw_refresh_token=raw_refresh_token,
session=in_memory_session,
)
assert refresh_payload[auth_service.EFFECTIVE_ROLE_KEY] == UserRole.MANAGER.value
assert refresh_payload[auth_service.EFFECTIVE_ROLES_KEY] == [
UserRole.MANAGER.value,
UserRole.USER.value,
]
refresh_token = auth_service._get_current_user_refresh_token_payload(
in_memory_session,
raw_refresh_token,
)
refreshed = auth_service.refresh_access_token(Response(), refresh_token)
assert refreshed.effective_role == UserRole.MANAGER
assert refreshed.effective_roles == [UserRole.MANAGER, UserRole.USER]
def test_logout_and_change_password(in_memory_session, settings_backup):
config_module.settings.token_hmac_key = "logout-key"
config_module.settings.token_issuer_id = "logout-issuer"
@@ -0,0 +1,231 @@
from __future__ import annotations
from collections.abc import Iterable
from datetime import datetime, timezone
from typing import Any, Literal
AFFILIATION_LOOKBACK_YEARS = 2
OPENALEX_ID_PREFIX = "https://openalex.org/"
AffiliationYearMode = Literal["all", "in", "from"]
def current_affiliation_year_cutoff(
reference_time: datetime | None = None,
) -> int:
"""Return the inclusive first year used for active membership.
The shared active cohort includes affiliation years greater than or equal
to the current UTC year minus ``AFFILIATION_LOOKBACK_YEARS``.
``reference_time`` exists so callers can make the cutoff deterministic
when needed.
"""
current_time = reference_time or datetime.now(timezone.utc)
return current_time.year - AFFILIATION_LOOKBACK_YEARS
def build_institution_affiliation_query(
institution_id: str,
year_mode: AffiliationYearMode = "all",
year: int | None = None,
) -> dict[str, Any]:
"""Build an affiliation query for an institution and optional year rule.
``all`` accepts an affiliation from any year and requires ``year=None``.
``in`` requires an affiliation in exactly ``year``.
``from`` requires an affiliation in ``year`` or any later year.
Institution IDs are normalized to their full OpenAlex URL.
"""
normalized_institution_id = _normalize_openalex_id(institution_id)
_validate_year_mode(year_mode, year)
affiliation_filters: list[dict[str, Any]] = [
{
"term": {
"affiliations.institution.id": normalized_institution_id
}
}
]
if year_mode == "in":
affiliation_filters.append(
{"term": {"affiliations.years": year}}
)
elif year_mode == "from":
affiliation_filters.append(
{"range": {"affiliations.years": {"gte": year}}}
)
return {
"nested": {
"path": "affiliations",
"query": {"bool": {"filter": affiliation_filters}},
}
}
def build_institution_membership_query(
institution_id: str,
year_mode: AffiliationYearMode = "all",
year: int | None = None,
author_ids: Iterable[str] | None = None,
) -> dict[str, Any]:
"""Build an institution membership query for the selected year mode.
Membership is accepted when one of these conditions matches:
1. The institution is both last known and present in the selected
affiliation period.
2. The institution is last known and no affiliation institution IDs are
available. This fallback is used only for ``all`` and ``from``.
3. The institution is present in the selected affiliation period and no
last-known institution IDs are available.
``in`` deliberately excludes condition 2 because an exact year requires
explicit affiliation evidence for that year. When ``author_ids`` are
supplied, the query is restricted to those authors in the same
Elasticsearch request. Empty ``author_ids`` produce ``match_none``.
Institution and author IDs are normalized to full OpenAlex URLs.
"""
normalized_institution_id = _normalize_openalex_id(institution_id)
affiliation = build_institution_affiliation_query(
normalized_institution_id,
year_mode=year_mode,
year=year,
)
author_filters: list[dict[str, Any]] = []
if author_ids is not None:
normalized_author_ids = list(
dict.fromkeys(
_normalize_openalex_id(author_id)
for author_id in author_ids
if author_id and author_id.strip()
)
)
if not normalized_author_ids:
return {"match_none": {}}
author_filters.append({"terms": {"id": normalized_author_ids}})
matching_last_known_institution = {
"nested": {
"path": "last_known_institutions",
"query": {
"term": {
"last_known_institutions.id": normalized_institution_id
}
},
}
}
any_affiliation_id = {
"nested": {
"path": "affiliations",
"query": {
"exists": {
"field": "affiliations.institution.id"
}
},
}
}
any_last_known_institution_id = {
"nested": {
"path": "last_known_institutions",
"query": {
"exists": {
"field": "last_known_institutions.id"
}
},
}
}
# Confirmed by both last-known and affiliation evidence.
membership_branches: list[dict[str, Any]] = [
{
"bool": {
"filter": [
matching_last_known_institution,
affiliation,
]
}
},
# Affiliation evidence is accepted when last-known data is unavailable.
{
"bool": {
"filter": [affiliation],
"must_not": [any_last_known_institution_id],
}
},
]
if year_mode != "in":
# Last-known is the fallback only when affiliation IDs are unavailable.
membership_branches.insert(
1,
{
"bool": {
"filter": [matching_last_known_institution],
"must_not": [any_affiliation_id],
}
},
)
membership_query = {
"bool": {
"should": membership_branches,
"minimum_should_match": 1,
}
}
if not author_filters:
return membership_query
return {
"bool": {
"filter": [
*author_filters,
membership_query,
],
}
}
def build_active_institution_membership_query(
institution_id: str,
author_ids: Iterable[str] | None = None,
reference_time: datetime | None = None,
) -> dict[str, Any]:
"""Build the shared active-cohort query.
Active membership uses ``from`` with the inclusive cutoff returned by
``current_affiliation_year_cutoff``. It therefore applies the same
membership and fallback rules everywhere that consumes this helper.
"""
return build_institution_membership_query(
institution_id=institution_id,
year_mode="from",
year=current_affiliation_year_cutoff(reference_time),
author_ids=author_ids,
)
def _validate_year_mode(
year_mode: AffiliationYearMode,
year: int | None,
) -> None:
if year_mode not in {"all", "in", "from"}:
raise ValueError(f"Unsupported affiliation year mode: {year_mode}")
if year_mode == "all":
if year is not None:
raise ValueError("year must be omitted when year_mode is 'all'")
return
if isinstance(year, bool) or not isinstance(year, int):
raise ValueError(f"year is required when year_mode is '{year_mode}'")
def _normalize_openalex_id(raw_id: str) -> str:
normalized_id = raw_id.strip()
if normalized_id.startswith(OPENALEX_ID_PREFIX):
return normalized_id
return f"{OPENALEX_ID_PREFIX}{normalized_id}"
@@ -0,0 +1,117 @@
import datetime
import logging
from datetime import timedelta
from inse.authors.v2.model import (
CollaborationGraph,
CollaborationGraphJob,
CollaborationGraphStatus,
)
from sqlmodel import Session, select
logger = logging.getLogger(__name__)
JOB_RETENTION = timedelta(hours=1)
def create_collaboration_graph_job(session: Session, graph_id: str) -> None:
"""Creates a new collaboration graph job in the database.
Args:
session (Session): The SQLModel session to use for database operations.
graph_id (str): The ID of the collaboration graph for which to create a job.
"""
existing = session.get(CollaborationGraphJob, graph_id)
if existing:
logger.info(f"Job for graph_id {graph_id} already exists.")
return
job = CollaborationGraphJob(
graph_id=graph_id, status=CollaborationGraphStatus.PENDING
)
session.add(job)
session.commit()
def get_collaboration_graph_job(
session: Session, graph_id: str
) -> CollaborationGraphJob | None:
"""Retrieves a collaboration graph job from the database by its graph ID.
Args:
session (Session): The SQLModel session to use for database operations.
graph_id (str): The ID of the collaboration graph for which to retrieve the job.
Returns:
CollaborationGraphJob | None: The collaboration graph job if found, otherwise None.
"""
return session.get(CollaborationGraphJob, graph_id)
def mark_collaboration_graph_job_completed(
session: Session, graph_id: str, result: CollaborationGraph
) -> None:
"""Marks a collaboration graph job as completed and stores the result.
Args:
session (Session): The SQLModel session to use for database operations.
graph_id (str): The ID of the collaboration graph for which to mark the job as completed.
result (CollaborationGraph): The result of the collaboration graph generation.
"""
job = get_collaboration_graph_job(session, graph_id)
if not job:
logger.warning(
f"No job found for graph_id {graph_id}. Cannot mark as completed."
)
return
job.status = CollaborationGraphStatus.COMPLETED
job.set_result(result)
job.updated_at = datetime.datetime.now(datetime.timezone.utc)
session.add(job)
session.commit()
def mark_collaboration_graph_job_failed(
session: Session, graph_id: str, error_message: str
) -> None:
"""Marks a collaboration graph job as failed and stores the error message.
Args:
session (Session): The SQLModel session to use for database operations.
graph_id (str): The ID of the collaboration graph for which to mark the job as failed.
error_message (str): The error message describing the failure.
"""
job = get_collaboration_graph_job(session, graph_id)
if not job:
logger.warning(f"No job found for graph_id {graph_id}. Cannot mark as failed.")
return
job.status = CollaborationGraphStatus.FAILED
job.error_message = error_message
job.updated_at = datetime.datetime.now(datetime.timezone.utc)
session.add(job)
session.commit()
def cleanup_old_collaboration_graph_jobs(
session: Session, max_age: timedelta = JOB_RETENTION
) -> int:
"""Cleans up old collaboration graph jobs that are older than the retention period.
Args:
session (Session): The SQLModel session to use for database operations.
max_age (timedelta): The maximum age of jobs to retain.
Returns:
int: The number of stale jobs that were cleaned up.
"""
cutoff_time = datetime.datetime.now(datetime.timezone.utc) - max_age
statement = select(CollaborationGraphJob).where(
CollaborationGraphJob.created_at < cutoff_time
)
stale_jobs = session.exec(statement).all()
count = len(stale_jobs)
for job in stale_jobs:
session.delete(job)
session.commit()
if count:
logger.debug("Cleaned up %d stale collaboration graph jobs", count)
return count
+187
View File
@@ -0,0 +1,187 @@
from datetime import datetime
from enum import StrEnum
from inse.model import Page
from inse.models.openalex.author import Author
from pydantic import BaseModel
from sqlmodel import Field, SQLModel
class AuthorPage(Page[Author]):
"""A paginated response containing a list of authors."""
class MatchMode(StrEnum):
AND = "and"
OR = "or"
class GraphFilterType(StrEnum):
PUBLICATION_FILTERED = "publication_filtered"
COLLABORATOR_FILTERED = "collaborator_filtered"
class AuthorNode(BaseModel):
id: str = Field(description="The ID of the author.")
display_name: str = Field(description="The display name of the author.")
institution_ids: list[str] = Field(
default_factory=list,
description="IDs of institutions this author is affiliated with.",
)
class WorkNode(BaseModel):
id: str = Field(description="The ID of the work.")
display_name: str = Field(description="The title of the work.")
publication_year: int = Field(description="The publication year of the work.")
author_ids: list[str] = Field(
default_factory=list,
description="IDs of authors who contributed to this work.",
)
class InstitutionNode(BaseModel):
id: str = Field(description="The ID of the institution.")
display_name: str = Field(description="The display name of the institution.")
class Edge(BaseModel):
source: str = Field(description="The ID of the source node.")
target: str = Field(description="The ID of the target node.")
weight: float = Field(description="The weight of the edge.")
class InternalCollaborationGraph(BaseModel):
root_author_id: str = Field(description="The ID of the root author.")
authors: dict[str, AuthorNode] = Field(default_factory=dict)
institutions: dict[str, InstitutionNode] = Field(default_factory=dict)
works: dict[str, WorkNode] = Field(default_factory=dict)
edges: list[Edge] = Field(
default_factory=list,
description="Person-to-person collaboration edges only.",
)
def add_author(
self, author: AuthorNode, institution_ids: list[str] | None = None
) -> None:
existing = self.authors.get(author.id)
if existing is None:
author.institution_ids = list(dict.fromkeys(institution_ids or []))
self.authors[author.id] = author
elif institution_ids:
merged = dict.fromkeys(existing.institution_ids)
merged.update(dict.fromkeys(institution_ids))
existing.institution_ids = list(merged)
def add_institution(self, institution: InstitutionNode) -> None:
self.institutions.setdefault(institution.id, institution)
def add_work(self, work: WorkNode, author_ids: list[str] | None = None) -> None:
existing = self.works.get(work.id)
if existing is None:
work.author_ids = list(dict.fromkeys(author_ids or []))
self.works[work.id] = work
elif author_ids:
merged = dict.fromkeys(existing.author_ids)
merged.update(dict.fromkeys(author_ids))
existing.author_ids = list(merged)
def add_edge(self, edge: Edge) -> None:
self.edges.append(edge)
class CollaborationGraph(BaseModel):
root_author_id: str = Field(description="The ID of the root author.")
authors: list[AuthorNode] = Field(
default_factory=list, description="A list of author nodes."
)
institutions: list[InstitutionNode] = Field(
default_factory=list, description="A list of institution nodes."
)
works: list[WorkNode] = Field(
default_factory=list, description="A list of work nodes."
)
edges: list[Edge] = Field(
default_factory=list, description="A list of edges in the collaboration graph."
)
@classmethod
def from_internal_graph(
cls, internal_graph: InternalCollaborationGraph, min_edge_weight: float = 2.0
) -> "CollaborationGraph":
return cls(
root_author_id=internal_graph.root_author_id,
authors=list(internal_graph.authors.values()),
institutions=list(internal_graph.institutions.values()),
works=list(internal_graph.works.values()),
edges=_collapse_edges(internal_graph.edges, min_weight=min_edge_weight),
)
def _collapse_edges(edges: list[Edge], min_weight: float = 2.0) -> list[Edge]:
reduced: dict[frozenset[str], Edge] = {}
for edge in edges:
key = frozenset((edge.source, edge.target))
existing = reduced.get(key)
if existing is None:
reduced[key] = Edge(
source=edge.source, target=edge.target, weight=edge.weight
)
else:
existing.weight += edge.weight
return [edge for edge in reduced.values() if edge.weight >= min_weight]
class CollaborationGraphStatus(StrEnum):
PENDING = "pending"
COMPLETED = "completed"
FAILED = "failed"
class StartCollaborationGraphResponse(BaseModel):
graph_id: str = Field(description="The ID of the collaboration graph.")
class CollaborationGraphStatusResponse(BaseModel):
status: CollaborationGraphStatus = Field(
description="The status of the collaboration graph."
)
result: CollaborationGraph | None = Field(
default=None, description="The collaboration graph result if completed."
)
error_message: str | None = Field(
default=None, description="The error message if the graph generation failed."
)
class CollaborationGraphJob(SQLModel, table=True):
__tablename__ = "collaboration_graph_jobs" # type: ignore
graph_id: str = Field(
primary_key=True,
description="The ID of the collaboration graph generation task.",
)
status: CollaborationGraphStatus = Field(
default=CollaborationGraphStatus.PENDING,
description="The status of the collaboration graph generation task.",
)
result: str | None = Field(
default=None,
description="The JSON-serialized result of the collaboration graph generation task.",
)
error_message: str | None = Field(
default=None,
description="The error message if the collaboration graph generation failed.",
)
created_at: datetime = Field(default_factory=datetime.utcnow)
updated_at: datetime = Field(default_factory=datetime.utcnow)
def get_result(self) -> "CollaborationGraph | None":
if self.result is None:
return None
return CollaborationGraph.model_validate_json(self.result)
def set_result(self, value: BaseModel | None) -> None:
self.result = value.model_dump_json() if value is not None else None
+148
View File
@@ -0,0 +1,148 @@
import logging
from typing import Annotated
import inse.authors.v2.service as authors_service
from fastapi import APIRouter, BackgroundTasks, Path, Query
from inse.authors.v2.model import (
AuthorPage,
CollaborationGraphStatusResponse,
StartCollaborationGraphResponse,
)
from inse.database import SessionDep
from inse.models.openalex.author import Author
from inse.router_prefixes import RouterPrefixes
from inse.tags import Tags
logger = logging.getLogger(__name__)
router = APIRouter(prefix=RouterPrefixes.AUTHORS_V2, tags=[Tags.AUTHORS_V2])
@router.get(
"/{raw_oa_author_id}",
operation_id="getAuthorById",
summary="Returns an author for a given author ID.",
)
async def get_author_by_id(
raw_oa_author_id: Annotated[
str,
Path(description="The ID of the author to retrieve."),
],
) -> Author:
return await authors_service.get_author_by_id_strict_or_raise(
raw_oa_author_id=raw_oa_author_id
)
@router.get(
"/authors/id",
operation_id="getAuthorsByIds",
summary="Returns a paginated list of authors for a given list of author IDs.",
)
async def get_authors_by_ids(
author_ids: Annotated[
list[str] | None,
Query(description="A list of author IDs to retrieve."),
] = None,
) -> AuthorPage:
return await authors_service.get_authors_by_ids(author_ids=author_ids or [])
@router.get(
"/autocomplete/selector",
operation_id="autocompleteAuthorsForSelector",
summary="Returns a paginated list of authors for a given search term based on their display name.",
)
async def autocomplete_authors_for_selector(
query: Annotated[
str,
Query(
description="A search term to filter authors by (partial matches allowed)."
),
] = "",
) -> AuthorPage:
return await authors_service.autocomplete_authors_for_selector(query=query)
@router.post(
"/collaboration-graph",
operation_id="startCollaborationGraph",
summary="Returns a collaboration graph for a given author ID.",
)
def start_collaboration_graph(
session: SessionDep,
background_tasks: BackgroundTasks,
raw_oa_author_id: Annotated[
str,
Query(
description="The raw OpenAlex author ID for which to retrieve the collaboration graph."
),
],
year_from: Annotated[
int | None,
Query(
description="The starting year to filter the works by (optional).",
),
] = None,
year_to: Annotated[
int | None,
Query(
description="The ending year to filter the works by (optional).",
),
] = None,
min_collaborators: Annotated[
int | None,
Query(
description="The minimum number of collaborators to filter the works by (optional).",
),
] = None,
max_collaborators: Annotated[
int | None,
Query(
description="The maximum number of collaborators to filter the works by (optional).",
),
] = None,
topic_ids: Annotated[
list[str] | None,
Query(
description="A list of topic IDs to filter the works by (optional).",
),
] = None,
institution_ids: Annotated[
list[str] | None,
Query(
description="A list of institution IDs to filter the works by (optional).",
),
] = None,
) -> StartCollaborationGraphResponse:
return authors_service.start_collaboration_graph(
session=session,
background_tasks=background_tasks,
raw_oa_author_id=raw_oa_author_id,
year_from=year_from,
year_to=year_to,
min_collaborators=min_collaborators,
max_collaborators=max_collaborators,
topic_ids=topic_ids,
institution_ids=institution_ids,
)
@router.get(
"/collaboration-graph/{graph_id}/status",
operation_id="getCollaborationGraphStatus",
summary="Returns the status of a collaboration graph generation task.",
)
def get_collaboration_graph_status(
session: SessionDep,
graph_id: Annotated[
str,
Path(
description="The ID of the collaboration graph generation task.",
),
],
) -> CollaborationGraphStatusResponse:
return authors_service.get_collaboration_graph_status(
session=session, graph_id=graph_id
)
+718
View File
@@ -0,0 +1,718 @@
import logging
import inse.works.v2.service as works_service
from fastapi import BackgroundTasks
from inse.authors.institution_membership_query import (
build_active_institution_membership_query,
)
from inse.authors.v2 import collaboration_graph_jobs
from inse.authors.v2.model import (
AuthorNode,
AuthorPage,
CollaborationGraph,
CollaborationGraphStatus,
CollaborationGraphStatusResponse,
InstitutionNode,
InternalCollaborationGraph,
MatchMode,
StartCollaborationGraphResponse,
WorkNode,
)
from inse.exceptions import NotFoundException
from inse.integrations import elasticsearch
from inse.model import ESIndex
from inse.models.openalex.author import Author
from inse.works.v2.model import WorkPageV2
from sqlmodel import Session
logger = logging.getLogger(__name__)
async def search_authors(
page: int = 0,
size: int = 10,
query: dict | None = None,
source: list[str] | None = None,
sort: list[dict] | None = None,
body: dict | None = None,
) -> AuthorPage:
"""Searches for authors in the OpenAlex Elasticsearch index based on the provided parameters.
Args:
page (int, optional): The page number for pagination (0-indexed). Defaults to 0.
size (int, optional): The number of results to return per page. Defaults to 10.
query (Optional[Dict], optional): The search query. Defaults to None.
source (Optional[List[str]], optional): The fields to include in the response. Defaults to None.
sort (Optional[List[dict]], optional): The sorting criteria. Defaults to None.
body (Optional[dict], optional): The request body for the search query. Defaults to None.
Returns:
AuthorPage: A page of authors matching the search criteria.
"""
response = await elasticsearch.search(
ESIndex.OPENALEX_AUTHORS,
query=query,
source=source,
size=size,
offset=size * page,
sort=sort,
body=body,
)
hits_block = response.get("hits", {})
hits = hits_block.get("hits", [])
authors: list[Author] = []
for hit in hits:
_source = hit.get("_source", {})
authors.append(Author.from_dict(_source)) # type: ignore
return AuthorPage(elements=authors, total=len(authors), page=page, size=size)
async def get_author_by_id(raw_oa_author_id: str) -> Author | None:
"""Retrieves an author from the OpenAlex Elasticsearch index based on the provided author ID.
Args:
raw_oa_author_id (str): The raw OpenAlex author ID of the author to retrieve.
Returns:
Optional[Author]: The retrieved author, or None if not found.
"""
response = await elasticsearch.get(
index=ESIndex.OPENALEX_AUTHORS, doc_id=raw_oa_author_id
)
if not response.get("found"):
return None
return Author.from_dict(response.get("_source", {})) # type: ignore
async def get_author_by_id_strict_or_raise(raw_oa_author_id: str) -> Author:
"""Retrieves an author from the OpenAlex Elasticsearch index based on the provided author ID.
Args:
raw_oa_author_id (str): The raw OpenAlex author ID of the author to retrieve.
Returns:
Author: The retrieved author.
Raises:
ValueError: If the author is not found.
"""
author = await get_author_by_id(raw_oa_author_id=raw_oa_author_id)
if not author:
raise NotFoundException(f"Author with ID {raw_oa_author_id} not found.")
return author
async def autocomplete_authors_for_selector(query: str) -> AuthorPage:
"""Autocompletes authors based on a search term for use in a selector component.
Args:
query (str): The search term to filter authors by (partial matches allowed).
Returns:
AuthorPage: A page of authors matching the search criteria.
"""
return await search_authors(
page=0,
size=10,
query={"match_phrase_prefix": {"display_name": query}},
source=[
"id",
"display_name",
"orcid",
"last_known_institutions",
"works_count",
],
)
async def get_authors_by_ids(author_ids: list[str]) -> AuthorPage:
"""Retrieves authors based on a list of author IDs.
Args:
author_ids (List[str]): A list of author IDs to retrieve.
Returns:
AuthorPage: A page of authors matching the provided IDs.
"""
if not author_ids:
return AuthorPage(elements=[], total=0, page=0, size=0)
return await search_authors(
page=0,
size=len(author_ids),
query={"terms": {"id": author_ids}},
source=[
"id",
"display_name",
"orcid",
"last_known_institutions",
"works_count",
],
)
async def author_currently_belongs_to_institution(
raw_oa_author_id: str,
raw_oa_institution_id: str,
) -> bool:
"""Return whether one author belongs to the institution's active cohort.
Args:
raw_oa_author_id (str): The ID of the author to check.
raw_oa_institution_id (str): The ID of the institution to check.
Returns:
bool: True if the author matches the shared active-membership query.
"""
matching_author_ids = await authors_currently_belong_to_institution(
[raw_oa_author_id],
raw_oa_institution_id,
)
return bool(matching_author_ids)
async def authors_currently_belong_to_institution(
raw_oa_author_ids: list[str],
raw_oa_institution_id: str,
) -> set[str]:
"""Return active cohort members using one query for all supplied authors."""
author_ids = list(dict.fromkeys(filter(None, raw_oa_author_ids)))
if not author_ids:
return set()
authors = await search_authors(
page=0,
size=len(author_ids),
query=build_active_institution_membership_query(
institution_id=raw_oa_institution_id,
author_ids=author_ids,
),
source=["id"],
)
return {author.id for author in authors.elements if author.id}
def _build_collaboration_graph_query(
raw_oa_author_id: str,
year_from: int | None = None,
year_to: int | None = None,
min_collaborators: int | None = None,
max_collaborators: int | None = None,
topic_ids: list[str] | None = None,
topic_match_mode: MatchMode = MatchMode.OR,
institution_ids: list[str] | None = None,
):
"""Builds an Elasticsearch query for retrieving a collaboration graph for a given author ID, optionally filtered by year range, collaborator count, topic IDs, and institution IDs.
Args:
raw_oa_author_id (str): The raw OpenAlex author ID for which to build the collaboration graph.
year_from (int | None, optional): The starting year to filter the works by (optional). Defaults to None.
year_to (int | None, optional): The ending year to filter the works by (optional). Defaults to None.
min_collaborators (int | None, optional): The minimum number of collaborators to filter the works by (optional). Defaults to None.
max_collaborators (int | None, optional): The maximum number of collaborators to filter the works by (optional). Defaults to None.
topic_ids (list[str] | None, optional): A list of topic IDs to filter the works by (optional). Defaults to None.
topic_match_mode (MatchMode, optional): The mode for matching topics (optional). Defaults to MatchMode.OR.
institution_ids (list[str] | None, optional): A list of institution IDs to filter the works by (optional). Defaults to None.
Raises:
ValueError: If the topic_match_mode is not valid.
ValueError: If the topic_ids list is empty.
ValueError: If the institution_ids list is empty.
Returns:
_type_: The built Elasticsearch query for the collaboration graph.
"""
author_id = _prefix_id(raw_oa_author_id)
must: list[dict] = [
{
"nested": {
"path": "authorships",
"query": {"term": {"authorships.author.id": author_id}},
}
}
]
if year_from is not None or year_to is not None:
range_query: dict = {}
if year_from is not None:
range_query["gte"] = year_from
if year_to is not None:
range_query["lte"] = year_to
must.append({"range": {"publication_year": range_query}})
if min_collaborators is not None or max_collaborators is not None:
range_query: dict = {}
if min_collaborators is not None:
range_query["gte"] = min_collaborators
if max_collaborators is not None:
range_query["lte"] = max_collaborators
must.append({"range": {"authors_count": range_query}})
if topic_ids is not None:
if not topic_ids:
raise ValueError("topic_ids must be a non-empty list if provided")
if topic_match_mode not in (MatchMode.OR, MatchMode.AND):
raise ValueError('topic_match_mode must be "or" or "and"')
if topic_match_mode == MatchMode.OR:
must.append(
{
"nested": {
"path": "topics",
"query": {"terms": {"topics.id": topic_ids}},
}
}
)
else:
for topic_id in topic_ids:
must.append(
{
"nested": {
"path": "topics",
"query": {"term": {"topics.id": topic_id}},
}
}
)
if institution_ids is not None:
if not institution_ids:
raise ValueError("institution_ids must be a non-empty list if provided")
must.append(
{
"nested": {
"path": "authorships",
"query": {
"nested": {
"path": "authorships.institutions",
"query": {
"terms": {
"authorships.institutions.id": institution_ids
}
},
}
},
}
}
)
query = {
"bool": {
"must": must,
}
}
logger.debug("Collaboration graph query for author %s: %s", raw_oa_author_id, query)
return query
COLLABORATION_GRAPH_SOURCE_FIELDS = [
"id",
"display_name",
"publication_year",
"authors_count",
"authorships.author.id",
"authorships.author.display_name",
"authorships.institutions.id",
"authorships.institutions.display_name",
]
def _get_collaboration_graph_cache_key(
raw_oa_author_id: str,
year_from: int | None = None,
year_to: int | None = None,
min_collaborators: int | None = None,
max_collaborators: int | None = None,
topic_ids: list[str] | None = None,
institution_ids: list[str] | None = None,
) -> str:
"""Generates a cache key for the collaboration graph based on the provided parameters.
Args:
raw_oa_author_id (str): The raw OpenAlex author ID for which to generate the cache key.
year_from (int | None, optional): The starting year to filter the works by (optional). Defaults to None.
year_to (int | None, optional): The ending year to filter the works by (optional). Defaults to None.
min_collaborators (int | None, optional): The minimum number of collaborators to filter the works by (optional). Defaults to None.
max_collaborators (int | None, optional): The maximum number of collaborators to filter the works by (optional). Defaults to None.
topic_ids (list[str] | None, optional): A list of topic IDs to filter the works by (optional). Defaults to None.
institution_ids (list[str] | None, optional): A list of institution IDs to filter the works by (optional). Defaults to None.
Returns:
str: The generated cache key.
"""
return f"collaboration_graph:{raw_oa_author_id}:{year_from}:{year_to}:{min_collaborators}:{max_collaborators}:{':'.join(sorted([_remove_prefix_id(id) for id in topic_ids or []]))}:{':'.join(sorted([_remove_prefix_id(id) for id in institution_ids or []]))}"
async def _build_collaboration_graph(
raw_oa_author_id: str,
year_from: int | None = None,
year_to: int | None = None,
min_collaborators: int | None = None,
max_collaborators: int | None = None,
topic_ids: list[str] | None = None,
institution_ids: list[str] | None = None,
) -> CollaborationGraph:
"""Gets a collaboration graph for a given author ID, optionally filtered by year range, collaborator count, topic IDs, and institution IDs.
Args:
raw_oa_author_id (str): The raw OpenAlex author ID for which to retrieve the collaboration graph.
year_from (int | None, optional): The starting year to filter the works by (optional). Defaults to None.
year_to (int | None, optional): The ending year to filter the works by (optional). Defaults to None.
min_collaborators (int | None, optional): The minimum number of collaborators to filter the works by (optional). Defaults to None.
max_collaborators (int | None, optional): The maximum number of collaborators to filter the works by (optional). Defaults to None.
topic_ids (list[str] | None, optional): A list of topic IDs to filter the works by (optional). Defaults to None.
institution_ids (list[str] | None, optional): A list of institution IDs to filter the works by (optional). Defaults to None.
Returns:
CollaborationGraph: The collaboration graph for the given author ID.
"""
query = _build_collaboration_graph_query(
raw_oa_author_id=raw_oa_author_id,
year_from=year_from,
year_to=year_to,
min_collaborators=min_collaborators,
max_collaborators=max_collaborators,
topic_ids=topic_ids,
institution_ids=institution_ids,
)
logger.debug(
f"Searching works for collaboration graph of author {raw_oa_author_id} with query: {query}"
)
work_page: WorkPageV2 = await works_service._search_works(
query=query,
source=COLLABORATION_GRAPH_SOURCE_FIELDS,
page=0,
size=10000,
sort=[{"publication_year": "desc"}, {"id": "asc"}],
)
logger.debug(
f"Retrieved {len(work_page.elements)} works for collaboration graph of author {raw_oa_author_id} (total: {work_page.total})"
)
return _build_collaboration_graph_from_works(
page=work_page, raw_oa_author_id=raw_oa_author_id
)
def _build_collaboration_graph_from_works(
page: WorkPageV2, raw_oa_author_id: str, min_edge_weight: float = 1.0
) -> CollaborationGraph:
"""Builds a collaboration graph from a page of works and a raw OpenAlex author ID.
Args:
page (WorkPageV2): The page of works from which to build the collaboration graph.
raw_oa_author_id (str): The raw OpenAlex author ID for which to build the collaboration graph.
min_edge_weight (float, optional): Minimum weight for a collaboration edge to be
included in the result. Filters out authors who only co-authored a single
work together. Defaults to 1.0.
Returns:
CollaborationGraph: The built collaboration graph.
"""
works = page.elements
internal_graph = InternalCollaborationGraph(
root_author_id=_prefix_id(raw_oa_author_id)
)
for work in works:
if not work.id or not work.display_name or not work.publication_year:
continue
work_author_ids: list[str] = []
for authorship in work.authorships or []:
author = authorship.author
if not author or not author.id or not author.display_name:
continue
institution_ids: list[str] = []
for institution in authorship.institutions or []:
if (
not institution
or not institution.id
or not institution.display_name
):
continue
internal_graph.add_institution(
InstitutionNode(
id=institution.id, display_name=institution.display_name
)
)
institution_ids.append(institution.id)
internal_graph.add_author(
AuthorNode(id=author.id, display_name=author.display_name),
institution_ids=institution_ids,
)
work_author_ids.append(author.id)
internal_graph.add_work(
WorkNode(
id=work.id,
display_name=work.display_name,
publication_year=work.publication_year,
),
author_ids=work_author_ids,
)
# Toggle to add edges between all pairs of authors for each work. This can create a dense graph if many authors co-author works together.
# for author_a, author_b in combinations(sorted(set(work_author_ids)), 2):
# internal_graph.add_edge(Edge(source=author_a, target=author_b, weight=1.0))
graph = CollaborationGraph.from_internal_graph(
internal_graph, min_edge_weight=min_edge_weight
)
logger.debug(
f"Built collaboration graph for author {raw_oa_author_id}: "
f"{len(graph.authors)} authors, {len(graph.works)} works, "
f"{len(graph.institutions)} institutions, {len(graph.edges)} edges"
)
return graph
jobs: dict[str, dict] = {}
def start_collaboration_graph(
session: Session,
background_tasks: BackgroundTasks,
raw_oa_author_id: str,
year_from: int | None = None,
year_to: int | None = None,
min_collaborators: int | None = None,
max_collaborators: int | None = None,
topic_ids: list[str] | None = None,
institution_ids: list[str] | None = None,
) -> StartCollaborationGraphResponse:
"""Starts the process of generating a collaboration graph for a given author ID, optionally filtered by year range, collaborator count, topic IDs, and institution IDs.
Args:
raw_oa_author_id (str): The raw OpenAlex author ID for which to generate the collaboration graph.
year_from (int | None, optional): The starting year to filter the works by (optional). Defaults to None.
year_to (int | None, optional): The ending year to filter the works by (optional). Defaults to None.
min_collaborators (int | None, optional): The minimum number of collaborators to filter the works by (optional). Defaults to None.
max_collaborators (int | None, optional): The maximum number of collaborators to filter the works by (optional). Defaults to None.
topic_ids (list[str] | None, optional): A list of topic IDs to filter the works by (optional). Defaults to None.
institution_ids (list[str] | None, optional): A list of institution IDs to filter the works by (optional). Defaults to None.
Returns:
StartCollaborationGraphResponse: The response containing the cache key for the collaboration graph generation process.
"""
cache_key = _get_collaboration_graph_cache_key(
raw_oa_author_id=raw_oa_author_id,
year_from=year_from,
year_to=year_to,
min_collaborators=min_collaborators,
max_collaborators=max_collaborators,
topic_ids=topic_ids,
institution_ids=institution_ids,
)
logger.debug("Generated cache key for collaboration graph: %s", cache_key)
existing_job = collaboration_graph_jobs.get_collaboration_graph_job(
session, cache_key
)
if existing_job:
logger.debug(
"Collaboration graph job already exists for cache key: %s, status: %s",
cache_key,
existing_job.status,
)
return StartCollaborationGraphResponse(graph_id=cache_key)
collaboration_graph_jobs.create_collaboration_graph_job(session, cache_key)
background_tasks.add_task(
_run_collaboration_graph_job,
session,
cache_key,
raw_oa_author_id,
year_from,
year_to,
min_collaborators,
max_collaborators,
topic_ids,
institution_ids,
)
logger.debug(
"Started background task for collaboration graph job with cache key: %s",
cache_key,
)
return StartCollaborationGraphResponse(graph_id=cache_key)
async def _run_collaboration_graph_job(
session: Session,
cache_key: str,
raw_oa_author_id: str,
year_from: int | None = None,
year_to: int | None = None,
min_collaborators: int | None = None,
max_collaborators: int | None = None,
topic_ids: list[str] | None = None,
institution_ids: list[str] | None = None,
) -> None:
"""Runs the collaboration graph generation job in the background and updates the job status in the jobs dictionary.
Args:
cache_key (str): The cache key for the collaboration graph generation process.
raw_oa_author_id (str): The raw OpenAlex author ID for which to generate the collaboration graph.
year_from (int | None, optional): The starting year to filter the works by (optional). Defaults to None.
year_to (int | None, optional): The ending year to filter the works by (optional). Defaults to None.
min_collaborators (int | None, optional): The minimum number of collaborators to filter the works by (optional). Defaults to None.
max_collaborators (int | None, optional): The maximum number of collaborators to filter the works by (optional). Defaults to None.
topic_ids (list[str] | None, optional): A list of topic IDs to filter the works by (optional). Defaults to None.
institution_ids (list[str] | None, optional): A list of institution IDs to filter the works by (optional). Defaults to None.
"""
try:
result = await _build_collaboration_graph(
raw_oa_author_id=raw_oa_author_id,
year_from=year_from,
year_to=year_to,
min_collaborators=min_collaborators,
max_collaborators=max_collaborators,
topic_ids=topic_ids,
institution_ids=institution_ids,
)
logger.debug(
f"Collaboration graph job completed successfully for cache key: {cache_key}"
)
collaboration_graph_jobs.mark_collaboration_graph_job_completed(
session, cache_key, result
)
logger.debug(
f"Collaboration graph job marked as completed for cache key: {cache_key}"
)
except Exception as e:
logger.exception("Collaboration graph job failed: %s", cache_key)
collaboration_graph_jobs.mark_collaboration_graph_job_failed(
session, cache_key, str(e)
)
logger.debug(
f"Collaboration graph job marked as failed for cache key: {cache_key}, error: {e!s}"
)
def get_collaboration_graph_status(
session: Session,
graph_id: str,
) -> CollaborationGraphStatusResponse:
"""Retrieves the status of a collaboration graph generation process based on the provided graph ID.
Args:
graph_id (str): The ID of the collaboration graph generation process.
Returns:
CollaborationGraphStatusResponse: The response containing the status and result (if completed) of the collaboration graph generation process.
"""
job = collaboration_graph_jobs.get_collaboration_graph_job(session, graph_id)
if not job:
logger.debug("No job found for the provided graph ID: %s", graph_id)
return CollaborationGraphStatusResponse(
status=CollaborationGraphStatus.FAILED,
error_message="No job found for the provided graph ID.",
)
logger.debug(
"Retrieved job status for graph ID: %s, status: %s",
graph_id,
job.status,
)
status = job.status
result = (
job.get_result() if job.status == CollaborationGraphStatus.COMPLETED else None
)
error_message = job.error_message
if result and job.status == CollaborationGraphStatus.COMPLETED:
if _is_graph_empty(result):
status = CollaborationGraphStatus.FAILED
result = None
error_message = "Der generierte Kollaborationsgraph ist leer. Bitte versuchen Sie es mit anderen Filtereinstellungen."
logger.debug(
"Collaboration graph for graph ID: %s is empty, marking as failed.",
graph_id,
)
elif _is_graph_too_large(result):
status = CollaborationGraphStatus.FAILED
result = None
error_message = "Der generierte Kollaborationsgraph ist zu groß, um ihn anzuzeigen. Bitte versuchen Sie es mit anderen Filtereinstellungen."
logger.debug(
"Collaboration graph for graph ID: %s is too large, marking as failed.",
graph_id,
)
return CollaborationGraphStatusResponse(
status=status,
result=result,
error_message=error_message,
)
def _is_graph_empty(graph: CollaborationGraph) -> bool:
"""Returns True if the collaboration graph has no authors, works, or institutions.
Args:
graph (CollaborationGraph): The collaboration graph to check.
Returns:
bool: True if the graph is empty, False otherwise.
"""
return not (graph.authors or graph.works or graph.institutions)
def _is_graph_too_large(graph: CollaborationGraph, max_nodes: int = 1000) -> bool:
"""Returns True if the total number of nodes (authors, works, and institutions) in the graph exceeds the specified max_nodes limit.
Args:
graph (CollaborationGraph): The collaboration graph to check.
max_nodes (int, optional): The maximum number of nodes allowed. Defaults to 1000.
Returns:
bool: True if the graph is too large, False otherwise.
"""
return len(graph.authors + graph.works + graph.institutions) > max_nodes
def _prefix_id(raw_oa_id: str) -> str:
"""Prefixes the raw OpenAlex ID with "https://openalex.org/" if it does not already start with that prefix.
Args:
raw_oa_id (str): The raw OpenAlex ID to prefix.
Returns:
str: The prefixed OpenAlex ID.
"""
if not raw_oa_id.startswith("https://openalex.org/"):
return f"https://openalex.org/{raw_oa_id}"
return raw_oa_id
def _remove_prefix_id(prefixed_oa_id: str) -> str:
"""Removes the "https://openalex.org/" prefix from the provided OpenAlex ID if it starts with that prefix.
Args:
prefixed_oa_id (str): The OpenAlex ID with the prefix to remove.
Returns:
str: The OpenAlex ID without the prefix.
"""
if prefixed_oa_id.startswith("https://openalex.org/"):
return prefixed_oa_id[len("https://openalex.org/") :]
return prefixed_oa_id
@@ -0,0 +1,146 @@
"""
Database tables and API schemas for the background job runner.
"""
from datetime import datetime, timezone
from enum import StrEnum
from typing import Optional
from pydantic import BaseModel
from sqlmodel import JSON, Column, Field, SQLModel
class JobRunStatus(StrEnum):
RUNNING = "running"
SUCCEEDED = "succeeded"
FAILED = "failed"
STOPPED = "stopped"
class JobTriggeredBy(StrEnum):
SCHEDULE = "schedule"
MANUAL = "manual"
def utcnow() -> datetime:
return datetime.now(timezone.utc).replace(tzinfo=None)
class JobDefinition(SQLModel, table=True):
__tablename__ = "background_job_definition"
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field(
index=True, unique=True, description="Human-readable job name shown in the UI."
)
description: str = Field(default="", description="What this job does.")
target_index: str = Field(
default="", description="Elasticsearch index the job writes to (UI info)."
)
image: Optional[str] = Field(
default=None,
description="Docker image to run. Null falls back to the configured "
"background-jobs image.",
)
command: Optional[str] = Field(
default=None,
description="Command passed to the image. Null uses the job name (for "
"known jobs) or the image's default entrypoint.",
)
env: dict[str, str] = Field(
default_factory=dict,
sa_column=Column(JSON),
description="Extra environment variables passed to the container.",
)
schedule: Optional[str] = Field(
default=None,
description="Cron expression in UTC (e.g. '0 3 * * *'). Null = manual only.",
)
enabled: bool = Field(
default=True, description="Disabled definitions are never scheduled."
)
next_run_at: Optional[datetime] = Field(
default=None, description="Computed by the scheduler from the cron expression."
)
created_at: datetime = Field(default_factory=utcnow)
class JobRun(SQLModel, table=True):
__tablename__ = "background_job_run"
id: Optional[int] = Field(default=None, primary_key=True)
definition_id: int = Field(
foreign_key="background_job_definition.id", index=True
)
container_id: Optional[str] = Field(default=None)
status: JobRunStatus = Field(default=JobRunStatus.RUNNING)
triggered_by: JobTriggeredBy = Field(
description="Whether the scheduler or a superadmin started this run."
)
started_at: datetime = Field(default_factory=utcnow)
finished_at: Optional[datetime] = Field(default=None)
exit_code: Optional[int] = Field(default=None)
logs: Optional[str] = Field(
default=None,
description="Captured stdout/stderr, filled in when the run finishes "
"(the container itself is removed afterwards).",
)
class JobDefinitionCreateRequest(BaseModel):
name: str
image: Optional[str] = None
command: Optional[str] = None
env: dict[str, str] = {}
description: str = ""
target_index: str = ""
schedule: Optional[str] = None
enabled: bool = True
class JobDefinitionUpdateRequest(BaseModel):
name: Optional[str] = None
image: Optional[str] = None
command: Optional[str] = None
env: Optional[dict[str, str]] = None
description: Optional[str] = None
target_index: Optional[str] = None
schedule: Optional[str] = None
enabled: Optional[bool] = None
class BackgroundJobTask(BaseModel):
id: int
name: str
description: str
target_index: str
image: Optional[str]
command: Optional[str]
env: dict[str, str]
schedule: Optional[str]
enabled: bool
next_run_at: Optional[datetime]
last_run: Optional[JobRun]
status: str
class JobRunLogs(BaseModel):
run_id: int
status: JobRunStatus
logs: str
class DockerHealth(BaseModel):
reachable: bool
detail: str
class RegistryHealth(BaseModel):
reachable: bool
detail: str
host: str
class AvailableImages(BaseModel):
images: list[str]
detail: str = ""
@@ -0,0 +1,161 @@
from fastapi import APIRouter, Depends, Query, Response, status
from sqlmodel import Session
from inse.auth import service as auth_service
from inse.auth.model import AccessTokenMetadata
from inse.database import get_session
from inse.tags import Tags
from . import service
from .model import (
AvailableImages,
BackgroundJobTask,
DockerHealth,
RegistryHealth,
JobDefinitionCreateRequest,
JobDefinitionUpdateRequest,
JobRun,
JobRunLogs,
)
router = APIRouter(prefix="/api/background-jobs", tags=[Tags.BACKGROUND_JOBS])
@router.get(
"/tasks",
operation_id="getBackgroundJobTasks",
response_model=list[BackgroundJobTask],
)
async def get_tasks(
session: Session = Depends(get_session),
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> list[BackgroundJobTask]:
return service.get_tasks(session, access_token)
@router.post(
"/tasks",
operation_id="createBackgroundJobTask",
response_model=BackgroundJobTask,
status_code=status.HTTP_201_CREATED,
)
async def create_task(
payload: JobDefinitionCreateRequest,
session: Session = Depends(get_session),
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> BackgroundJobTask:
return service.create_task(session, access_token, payload)
@router.delete(
"/tasks/{task_id}",
operation_id="deleteBackgroundJobTask",
status_code=status.HTTP_204_NO_CONTENT,
)
async def delete_task(
task_id: int,
session: Session = Depends(get_session),
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> Response:
service.delete_task(session, access_token, task_id)
return Response(status_code=status.HTTP_204_NO_CONTENT)
@router.patch(
"/tasks/{task_id}",
operation_id="updateBackgroundJobTask",
response_model=BackgroundJobTask,
)
async def update_task(
task_id: int,
payload: JobDefinitionUpdateRequest,
session: Session = Depends(get_session),
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> BackgroundJobTask:
return service.update_task(session, access_token, task_id, payload)
@router.post(
"/tasks/{task_id}/run",
operation_id="runBackgroundJobTask",
response_model=JobRun,
)
async def run_task(
task_id: int,
session: Session = Depends(get_session),
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> JobRun:
return service.trigger_run(session, access_token, task_id)
@router.get(
"/tasks/{task_id}/runs",
operation_id="getBackgroundJobTaskRuns",
response_model=list[JobRun],
)
async def get_task_runs(
task_id: int,
limit: int = Query(default=20, ge=1, le=100),
session: Session = Depends(get_session),
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> list[JobRun]:
return service.get_task_runs(session, access_token, task_id, limit)
@router.get(
"/runs/{run_id}/logs",
operation_id="getBackgroundJobRunLogs",
response_model=JobRunLogs,
)
async def get_run_logs(
run_id: int,
session: Session = Depends(get_session),
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> JobRunLogs:
return service.get_run_logs(session, access_token, run_id)
@router.post(
"/runs/{run_id}/stop",
operation_id="stopBackgroundJobRun",
response_model=JobRun,
)
async def stop_run(
run_id: int,
session: Session = Depends(get_session),
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> JobRun:
return service.stop_run(session, access_token, run_id)
@router.get(
"/available-images",
operation_id="getBackgroundJobAvailableImages",
response_model=AvailableImages,
)
async def get_available_images(
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> AvailableImages:
return service.get_available_images(access_token)
@router.get(
"/docker-health",
operation_id="getBackgroundJobsDockerHealth",
response_model=DockerHealth,
)
async def docker_health(
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> DockerHealth:
return service.docker_health(access_token)
@router.get(
"/registry-health",
operation_id="getBackgroundJobsRegistryHealth",
response_model=RegistryHealth,
)
async def registry_health(
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> RegistryHealth:
return service.registry_health(access_token)
@@ -0,0 +1,376 @@
"""
Launches background job containers via the host's Docker daemon and runs the
periodic schedule/reconcile loop.
"""
import asyncio
import logging
import re
from datetime import datetime
from threading import RLock
from typing import Optional
import docker
import httpx
from croniter import croniter
from docker.errors import NotFound
from sqlalchemy import update as sa_update
from sqlmodel import Session, select
from inse import config
from inse.database import engine
from .model import JobDefinition, JobRun, JobRunStatus, JobTriggeredBy, utcnow
logger = logging.getLogger(__name__)
settings = config.get_settings()
RUN_STATE_LOCK = RLock()
_client: Optional[docker.DockerClient] = None
def get_docker_client() -> docker.DockerClient:
global _client
if _client is None:
_client = docker.from_env()
return _client
def docker_reachable() -> tuple[bool, str]:
try:
get_docker_client().ping()
return True, "ok"
except Exception as error: # noqa: BLE001
return False, str(error)
def registry_reachable() -> tuple[bool, str]:
username = settings.background_jobs_registry_username
password = settings.background_jobs_registry_password
auth = (username, password) if username and password else None
host = registry_host()
try:
with httpx.Client(timeout=8.0, auth=auth) as client:
response = client.get(f"https://{host}/v2/")
if response.status_code == 200:
return True, "ok"
if response.status_code == 401:
return False, "authentication failed (401)"
return False, f"unexpected status {response.status_code}"
except Exception as error: # noqa: BLE001
return False, str(error)
def compute_next_run(schedule: str) -> datetime:
return croniter(schedule, utcnow()).get_next(datetime)
def job_environment() -> dict[str, str]:
environment = {
"INSE_ELASTIC_URL": settings.elasticsearch_inse_url,
"INSE_ELASTIC_API_KEY": settings.elasticsearch_inse_api_key,
"INSE_LLM_BASE_URL": settings.llm_api_url,
"INSE_LLM_API_KEY": settings.llm_api_key,
"INSE_LLM_MODEL": settings.llm_model,
"ELASTICSEARCH_INSE_URL": settings.elasticsearch_inse_url,
"ELASTICSEARCH_INSE_API_KEY": settings.elasticsearch_inse_api_key,
"SENTENCE_TRANSFORMERS_MODEL_NAME": settings.sentence_transformers_model_name,
}
return {key: value for key, value in environment.items() if value}
def registry_host() -> str:
return settings.background_jobs_image.split("/", 1)[0]
REGISTRY_IMAGE_LIMIT = 500
def list_registry_images() -> tuple[list[str], str]:
username = settings.background_jobs_registry_username
password = settings.background_jobs_registry_password
if not username or not password:
return [], "registry credentials are not configured"
host = registry_host()
base = f"https://{host}"
try:
with httpx.Client(timeout=10.0, auth=(username, password)) as client:
catalog = client.get(
f"{base}/v2/_catalog", params={"n": REGISTRY_IMAGE_LIMIT}
)
catalog.raise_for_status()
repositories = catalog.json().get("repositories", []) or []
images: list[str] = []
for repository in repositories:
try:
response = client.get(f"{base}/v2/{repository}/tags/list")
response.raise_for_status()
tags = response.json().get("tags") or []
except Exception: # noqa: BLE001
tags = []
if tags:
images.extend(f"{host}/{repository}:{tag}" for tag in tags)
else:
images.append(f"{host}/{repository}")
return sorted(images), ""
except Exception as error: # noqa: BLE001
logger.warning("Could not list registry images.", exc_info=True)
return [], str(error)
def resolve_image(definition: JobDefinition) -> Optional[str]:
return definition.image or None
def is_registry_image(image: Optional[str]) -> bool:
return bool(image) and image.split("/", 1)[0] == registry_host()
def container_name(definition: JobDefinition, run: JobRun) -> str:
slug = definition.name.lower()
slug = (
slug.replace("ä", "ae")
.replace("ö", "oe")
.replace("ü", "ue")
.replace("ß", "ss")
)
slug = re.sub(r"[^a-z0-9]+", "-", slug).strip("-")[:40].strip("-")
return f"{slug or 'job'}-run-{run.id}"
def resolve_command(definition: JobDefinition):
return definition.command or None
def resolve_environment(definition: JobDefinition) -> dict[str, str]:
base = job_environment() if is_registry_image(resolve_image(definition)) else {}
return {**base, **(definition.env or {})}
def registry_auth() -> Optional[dict[str, str]]:
if (
settings.background_jobs_registry_username
and settings.background_jobs_registry_password
):
return {
"username": settings.background_jobs_registry_username,
"password": settings.background_jobs_registry_password,
}
return None
def pull_image(image: str) -> None:
get_docker_client().images.pull(image, auth_config=registry_auth())
logger.info("Pulled image '%s' from the registry.", image)
def start_run(
session: Session, definition: JobDefinition, triggered_by: JobTriggeredBy
) -> JobRun:
run = JobRun(definition_id=definition.id, triggered_by=triggered_by)
session.add(run)
session.commit()
session.refresh(run)
image = resolve_image(definition)
if not image:
run.status = JobRunStatus.FAILED
run.finished_at = utcnow()
run.logs = "[system] No image configured for this job."
session.add(run)
session.commit()
session.refresh(run)
return run
if settings.background_jobs_pull_before_run and is_registry_image(image):
try:
pull_image(image)
except Exception as error: # noqa: BLE001
run.status = JobRunStatus.FAILED
run.finished_at = utcnow()
run.logs = (
f"[system] Failed to pull image '{image}' from the registry.\n"
f"[system] {error}"
)
session.add(run)
session.commit()
session.refresh(run)
return run
try:
container = get_docker_client().containers.run(
image=image,
command=resolve_command(definition),
environment=resolve_environment(definition),
detach=True,
name=container_name(definition, run),
remove=False,
)
run.container_id = container.id
except Exception as error: # noqa: BLE001
run.status = JobRunStatus.FAILED
run.finished_at = utcnow()
run.logs = (
f"[system] Failed to start the container for image '{image}'.\n"
f"[system] {error}"
)
session.add(run)
session.commit()
session.refresh(run)
return run
def has_running_run(session: Session, definition_id: int) -> bool:
return (
session.exec(
select(JobRun).where(
JobRun.definition_id == definition_id,
JobRun.status == JobRunStatus.RUNNING,
)
).first()
is not None
)
def schedule_due_jobs(session: Session) -> None:
now = utcnow()
scheduled = session.exec(
select(JobDefinition).where(
JobDefinition.enabled == True, # noqa: E712
JobDefinition.schedule != None, # noqa: E711
)
).all()
for definition in scheduled:
if definition.next_run_at is None:
definition.next_run_at = compute_next_run(definition.schedule)
session.add(definition)
continue
if definition.next_run_at > now:
continue
if has_running_run(session, definition.id):
logger.info(
"Skipping '%s': previous run still running.", definition.name
)
else:
run = start_run(session, definition, JobTriggeredBy.SCHEDULE)
logger.info(
"Started scheduled run %s of '%s'.", run.id, definition.name
)
definition.next_run_at = compute_next_run(definition.schedule)
session.add(definition)
session.commit()
def finalize_run(
session: Session,
run: JobRun,
*,
new_status: JobRunStatus,
expected_status: JobRunStatus = JobRunStatus.RUNNING,
exit_code: Optional[int] = None,
logs: Optional[str] = None,
) -> bool:
values: dict = {"status": new_status, "finished_at": utcnow()}
if exit_code is not None:
values["exit_code"] = exit_code
if logs is not None:
values["logs"] = logs
result = session.execute(
sa_update(JobRun)
.where(JobRun.id == run.id, JobRun.status == expected_status)
.values(**values)
)
return result.rowcount > 0
def append_system_log(logs: str, message: str) -> str:
base = logs.rstrip()
return f"{base}\n[system] {message}" if base else f"[system] {message}"
def remove_container(container, run_id: int) -> None:
try:
container.remove()
except Exception: # noqa: BLE001
logger.warning(
"Could not remove container for run %s.", run_id, exc_info=True
)
def reconcile_runs(session: Session) -> None:
with RUN_STATE_LOCK:
_reconcile_runs(session)
def _reconcile_runs(session: Session) -> None:
running = session.exec(
select(JobRun).where(JobRun.status == JobRunStatus.RUNNING)
).all()
for run in running:
if not run.container_id:
continue
try:
container = get_docker_client().containers.get(run.container_id)
except NotFound:
applied = finalize_run(
session,
run,
new_status=JobRunStatus.FAILED,
logs=(run.logs or "")
+ "\n[container disappeared before reconciliation]",
)
if applied:
session.commit()
logger.info(
"Run %s finished: failed (container disappeared).", run.id
)
continue
container.reload()
if container.status in ("exited", "dead"):
exit_code = container.attrs["State"]["ExitCode"]
new_status = (
JobRunStatus.SUCCEEDED if exit_code == 0 else JobRunStatus.FAILED
)
applied = finalize_run(
session,
run,
new_status=new_status,
exit_code=exit_code,
logs=container.logs().decode("utf-8", errors="replace"),
)
if applied:
session.commit()
remove_container(container, run.id)
logger.info(
"Run %s finished: %s (exit %s).", run.id, new_status, exit_code
)
session.commit()
def tick() -> None:
with Session(engine) as session:
schedule_due_jobs(session)
reconcile_runs(session)
async def scheduler_loop() -> None:
logger.info(
"Background job scheduler started (tick every %ss).",
settings.background_jobs_tick_seconds,
)
while True:
try:
await asyncio.to_thread(tick)
except Exception: # noqa: BLE001
logger.exception("Background job scheduler tick failed.")
await asyncio.sleep(settings.background_jobs_tick_seconds)
@@ -0,0 +1,401 @@
"""
Business logic for the superadmin-only background job endpoints.
"""
import logging
from croniter import croniter
from docker.errors import APIError, NotFound
from fastapi import HTTPException, status
from sqlmodel import Session, col, select
from inse import config
from inse.auth.model import AccessTokenMetadata, UserRole
from . import runner
from .model import (
AvailableImages,
BackgroundJobTask,
DockerHealth,
RegistryHealth,
JobDefinition,
JobDefinitionCreateRequest,
JobDefinitionUpdateRequest,
JobRun,
JobRunLogs,
JobRunStatus,
JobTriggeredBy,
utcnow,
)
logger = logging.getLogger(__name__)
settings = config.get_settings()
def _require_super_admin(access_token: AccessTokenMetadata) -> None:
if access_token.effective_role != UserRole.SUPER_ADMIN:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Only superadmins can manage background jobs.",
)
def _get_definition(session: Session, definition_id: int) -> JobDefinition:
definition = session.get(JobDefinition, definition_id)
if not definition:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Unknown background job task id {definition_id}.",
)
return definition
def _get_run(session: Session, run_id: int) -> JobRun:
run = session.get(JobRun, run_id)
if not run:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Unknown background job run id {run_id}.",
)
return run
def _last_run(session: Session, definition_id: int) -> JobRun | None:
return session.exec(
select(JobRun)
.where(JobRun.definition_id == definition_id)
.order_by(col(JobRun.id).desc())
).first()
def _to_task(session: Session, definition: JobDefinition) -> BackgroundJobTask:
last_run = _last_run(session, definition.id)
if last_run is None:
derived_status = "idle"
elif last_run.status == JobRunStatus.RUNNING:
derived_status = "running"
else:
derived_status = last_run.status.value
return BackgroundJobTask(
id=definition.id,
name=definition.name,
description=definition.description,
target_index=definition.target_index,
image=definition.image,
command=definition.command,
env=definition.env or {},
schedule=definition.schedule,
enabled=definition.enabled,
next_run_at=definition.next_run_at,
last_run=last_run,
status=derived_status,
)
def get_tasks(
session: Session, access_token: AccessTokenMetadata
) -> list[BackgroundJobTask]:
_require_super_admin(access_token)
definitions = session.exec(
select(JobDefinition).order_by(col(JobDefinition.id))
).all()
return [_to_task(session, definition) for definition in definitions]
def create_task(
session: Session,
access_token: AccessTokenMetadata,
payload: JobDefinitionCreateRequest,
) -> BackgroundJobTask:
_require_super_admin(access_token)
name = payload.name.strip()
if not name:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="Task name must not be empty.",
)
image = (payload.image or "").strip()
if not image:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="An image must be selected.",
)
if payload.schedule is not None and not croniter.is_valid(payload.schedule):
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=f"Invalid cron expression: '{payload.schedule}'.",
)
if session.exec(select(JobDefinition).where(JobDefinition.name == name)).first():
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail=f"A task named '{name}' already exists.",
)
definition = JobDefinition(
name=name,
image=image,
command=payload.command,
env=payload.env or {},
description=payload.description,
target_index=payload.target_index,
schedule=payload.schedule,
enabled=payload.enabled,
)
if definition.enabled and definition.schedule:
definition.next_run_at = runner.compute_next_run(definition.schedule)
session.add(definition)
session.commit()
session.refresh(definition)
logger.info("Created background job task '%s'.", name)
return _to_task(session, definition)
def delete_task(
session: Session, access_token: AccessTokenMetadata, definition_id: int
) -> None:
_require_super_admin(access_token)
definition = _get_definition(session, definition_id)
if runner.has_running_run(session, definition.id):
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail=f"'{definition.name}' is running. Stop the run first.",
)
runs = session.exec(
select(JobRun).where(JobRun.definition_id == definition.id)
).all()
for run in runs:
session.delete(run)
session.delete(definition)
session.commit()
logger.info(
"Deleted background job task '%s' (%d runs removed).",
definition.name,
len(runs),
)
def update_task(
session: Session,
access_token: AccessTokenMetadata,
definition_id: int,
payload: JobDefinitionUpdateRequest,
) -> BackgroundJobTask:
_require_super_admin(access_token)
changes = payload.model_dump(exclude_unset=True)
if changes.get("schedule") is not None and not croniter.is_valid(
changes["schedule"]
):
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=f"Invalid cron expression: '{changes['schedule']}'.",
)
if "name" in changes:
name = (changes["name"] or "").strip()
if not name:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="Task name must not be empty.",
)
duplicate = session.exec(
select(JobDefinition).where(
JobDefinition.name == name,
JobDefinition.id != definition_id,
)
).first()
if duplicate:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail=f"A task named '{name}' already exists.",
)
changes["name"] = name
if "image" in changes:
image = (changes["image"] or "").strip()
if not image:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="An image must be selected.",
)
changes["image"] = image
definition = _get_definition(session, definition_id)
for key, value in changes.items():
setattr(definition, key, value)
if "schedule" in changes or "enabled" in changes:
definition.next_run_at = (
runner.compute_next_run(definition.schedule)
if definition.enabled and definition.schedule
else None
)
session.add(definition)
session.commit()
session.refresh(definition)
return _to_task(session, definition)
def trigger_run(
session: Session, access_token: AccessTokenMetadata, definition_id: int
) -> JobRun:
_require_super_admin(access_token)
definition = _get_definition(session, definition_id)
if runner.has_running_run(session, definition.id):
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail=f"'{definition.name}' is already running.",
)
return runner.start_run(session, definition, JobTriggeredBy.MANUAL)
def get_task_runs(
session: Session,
access_token: AccessTokenMetadata,
definition_id: int,
limit: int,
) -> list[JobRun]:
_require_super_admin(access_token)
_get_definition(session, definition_id)
return session.exec(
select(JobRun)
.where(JobRun.definition_id == definition_id)
.order_by(col(JobRun.id).desc())
.limit(limit)
).all()
LOG_TAIL_LINES = 200
def _tail_log_lines(text: str, limit: int = LOG_TAIL_LINES) -> str:
lines = text.splitlines()
if len(lines) <= limit:
return text
return "\n".join(lines[-limit:])
def get_run_logs(
session: Session, access_token: AccessTokenMetadata, run_id: int
) -> JobRunLogs:
_require_super_admin(access_token)
run = _get_run(session, run_id)
if run.status == JobRunStatus.RUNNING and run.container_id:
try:
container = runner.get_docker_client().containers.get(run.container_id)
return JobRunLogs(
run_id=run_id,
status=run.status,
logs=container.logs(tail=LOG_TAIL_LINES).decode(
"utf-8", errors="replace"
),
)
except Exception: # noqa: BLE001
pass
return JobRunLogs(
run_id=run_id, status=run.status, logs=_tail_log_lines(run.logs or "")
)
def stop_run(
session: Session, access_token: AccessTokenMetadata, run_id: int
) -> JobRun:
_require_super_admin(access_token)
with runner.RUN_STATE_LOCK:
run = _get_run(session, run_id)
session.refresh(run)
if run.status != JobRunStatus.RUNNING or not run.container_id:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail=f"Run {run_id} is not running.",
)
requested_at = utcnow().isoformat(timespec="seconds") + "Z"
stop_message = f"Stop requested at {requested_at}."
try:
container = runner.get_docker_client().containers.get(run.container_id)
container.reload()
except NotFound as error:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail=f"Container for run {run_id} no longer exists.",
) from error
except Exception as error: # noqa: BLE001
logger.warning(
"Could not inspect run %s before stopping.", run_id, exc_info=True
)
raise HTTPException(
status_code=status.HTTP_502_BAD_GATEWAY,
detail=f"Could not inspect container for run {run_id}.",
) from error
stopped_by_request = False
if container.status not in ("exited", "dead"):
try:
container.stop(timeout=2)
stopped_by_request = True
except APIError as error:
if error.status_code != 304:
logger.warning("Could not stop run %s.", run_id, exc_info=True)
raise HTTPException(
status_code=status.HTTP_502_BAD_GATEWAY,
detail=f"Could not stop container for run {run_id}.",
) from error
except Exception as error: # noqa: BLE001
logger.warning("Could not stop run %s.", run_id, exc_info=True)
raise HTTPException(
status_code=status.HTTP_502_BAD_GATEWAY,
detail=f"Could not stop container for run {run_id}.",
) from error
container.reload()
exit_code = container.attrs["State"]["ExitCode"]
logs = container.logs().decode("utf-8", errors="replace")
logs = runner.append_system_log(logs, stop_message)
if stopped_by_request:
new_status = JobRunStatus.STOPPED
logs = runner.append_system_log(
logs, f"Container stopped (exit {exit_code})."
)
else:
new_status = (
JobRunStatus.SUCCEEDED if exit_code == 0 else JobRunStatus.FAILED
)
logs = runner.append_system_log(
logs, "Stop request arrived after the container had exited."
)
applied = runner.finalize_run(
session,
run,
new_status=new_status,
exit_code=exit_code,
logs=logs,
)
if not applied:
session.rollback()
session.refresh(run)
return run
session.commit()
runner.remove_container(container, run.id)
session.refresh(run)
return run
def get_available_images(access_token: AccessTokenMetadata) -> AvailableImages:
_require_super_admin(access_token)
images, detail = runner.list_registry_images()
return AvailableImages(images=images, detail=detail)
def docker_health(access_token: AccessTokenMetadata) -> DockerHealth:
_require_super_admin(access_token)
reachable, detail = runner.docker_reachable()
return DockerHealth(reachable=reachable, detail=detail)
def registry_health(access_token: AccessTokenMetadata) -> RegistryHealth:
_require_super_admin(access_token)
reachable, detail = runner.registry_reachable()
return RegistryHealth(
reachable=reachable, detail=detail, host=runner.registry_host()
)
@@ -0,0 +1,146 @@
from types import SimpleNamespace
import pytest
from fastapi import HTTPException
from sqlmodel import Session, SQLModel, create_engine
from inse.auth.model import UserRole
from . import runner, service
from .model import JobRun, JobRunStatus, JobTriggeredBy
class FakeContainer:
def __init__(
self, *, status: str, exit_code: int, logs: str, stop_error=None
):
self.status = status
self.attrs = {"State": {"ExitCode": exit_code}}
self._logs = logs
self.stop_calls = 0
self.removed = False
self.stop_error = stop_error
def reload(self) -> None:
pass
def stop(self, timeout: int) -> None:
assert timeout == 2
self.stop_calls += 1
if self.stop_error:
raise self.stop_error
self.status = "exited"
self.attrs["State"]["ExitCode"] = 143
def logs(self, tail=None) -> bytes:
return self._logs.encode()
def remove(self) -> None:
self.removed = True
@pytest.fixture()
def session():
engine = create_engine(
"sqlite:///:memory:", connect_args={"check_same_thread": False}
)
SQLModel.metadata.create_all(engine)
with Session(engine) as database_session:
yield database_session
def _token():
return SimpleNamespace(effective_role=UserRole.SUPER_ADMIN)
def _run(session: Session, status: JobRunStatus = JobRunStatus.RUNNING) -> JobRun:
run = JobRun(
definition_id=1,
container_id="container-id",
status=status,
triggered_by=JobTriggeredBy.MANUAL,
)
session.add(run)
session.commit()
session.refresh(run)
return run
def _use_container(monkeypatch, container: FakeContainer) -> None:
client = SimpleNamespace(
containers=SimpleNamespace(get=lambda container_id: container)
)
monkeypatch.setattr(runner, "get_docker_client", lambda: client)
def test_stop_running_container_records_stopped_and_system_logs(
session, monkeypatch
):
run = _run(session)
container = FakeContainer(status="running", exit_code=0, logs="Progress: 5/20")
_use_container(monkeypatch, container)
result = service.stop_run(session, _token(), run.id)
assert result.status == JobRunStatus.STOPPED
assert result.exit_code == 143
assert container.stop_calls == 1
assert container.removed is True
assert "Progress: 5/20" in result.logs
assert "[system] Stop requested at" in result.logs
assert "[system] Container stopped (exit 143)." in result.logs
def test_late_stop_preserves_successful_container_result(session, monkeypatch):
run = _run(session)
container = FakeContainer(
status="exited",
exit_code=0,
logs="Demo job finished successfully.",
)
_use_container(monkeypatch, container)
result = service.stop_run(session, _token(), run.id)
assert result.status == JobRunStatus.SUCCEEDED
assert result.exit_code == 0
assert container.stop_calls == 0
assert container.removed is True
assert "Demo job finished successfully." in result.logs
assert "Stop request arrived after the container had exited." in result.logs
def test_reconciler_keeps_running_container_after_backend_restart(
session, monkeypatch
):
run = _run(session)
container = FakeContainer(status="running", exit_code=0, logs="Partial output")
_use_container(monkeypatch, container)
runner.reconcile_runs(session)
session.refresh(run)
assert run.status == JobRunStatus.RUNNING
assert run.exit_code is None
assert container.stop_calls == 0
assert container.removed is False
def test_failed_docker_stop_leaves_database_run_running(session, monkeypatch):
run = _run(session)
container = FakeContainer(
status="running",
exit_code=0,
logs="Partial output",
stop_error=RuntimeError("Docker unavailable"),
)
_use_container(monkeypatch, container)
with pytest.raises(HTTPException) as error:
service.stop_run(session, _token(), run.id)
session.refresh(run)
assert run.status == JobRunStatus.RUNNING
assert error.value.status_code == 502
assert run.finished_at is None
assert container.removed is False
@@ -1,43 +0,0 @@
from typing import Annotated, Optional
from fastapi import APIRouter, Body, Path, status
from inse.collaboration_network.schemas import (
CollaborationNetwork,
FilterProperties,
)
from inse.tags import Tags
import inse.collaboration_network.service as collaboration_network_service
router = APIRouter(
prefix="/api/person/network", tags=[Tags.PERSON_NETWORK]
)
@router.post(
"/{raw_user_id}",
summary="Get a person's collaboration network.",
description="Returns a person's collaboration network based on their works and co-authors.",
operation_id="getCollaborationNetwork",
responses={
status.HTTP_200_OK: {
"description": "Successful Response",
"model": CollaborationNetwork,
},
status.HTTP_404_NOT_FOUND: {"description": "Person not found"},
},
)
async def get_collaboration_network(
raw_user_id: Annotated[str, Path(description="The raw user ID of the person.")],
filter_properties: Annotated[
Optional[FilterProperties],
Body(
description="The filter properties for the collaboration network.",
),
] = None,
) -> CollaborationNetwork:
return await collaboration_network_service.get_collaboration_network(
raw_user_id=raw_user_id,
filter_properties=filter_properties,
)
@@ -1,273 +0,0 @@
from enum import Enum
from typing import List, Optional, Set
from pydantic import BaseModel, Field
from inse.models.openalex.work_topic import WorkTopic
from inse.utils import extract_raw_topic_id
class InstitutionInformation(BaseModel):
raw_id: str = Field(
title="Raw Institution ID",
description="The raw institution ID of the institution.",
)
display_name: str = Field(
title="Institution Display Name",
description="The display name of the institution.",
)
def __eq__(self, value: object) -> bool:
if isinstance(value, InstitutionInformation):
return self.raw_id == value.raw_id
return False
def __hash__(self) -> int:
return hash(self.raw_id)
class WorkTopicInformation(BaseModel):
raw_topic_id: str = Field(
title="Topic ID",
description="The ID of the topic.",
)
display_name: str = Field(
title="Topic Name",
description="The name of the topic.",
)
def __eq__(self, value: object) -> bool:
if isinstance(value, WorkTopicInformation):
return self.raw_topic_id == value.raw_topic_id
return False
def __hash__(self) -> int:
return hash(self.raw_topic_id)
@classmethod
def from_topic(cls, topic: WorkTopic) -> "WorkTopicInformation":
"""Creates a WorkTopicInformation instance from a WorkTopic instance.
Args:
topic (WorkTopic): The WorkTopic instance to create the WorkTopicInformation from.
Returns:
WorkTopicInformation: The created WorkTopicInformation instance.
"""
return cls(
raw_topic_id=extract_raw_topic_id(str(topic.id)),
display_name=str(topic.display_name),
)
class CollaborationNetworkNodeType(str, Enum):
AUTHOR = "author"
INSTITUTION = "institution"
WORK = "work"
class FilterInformation(BaseModel):
min_possible_year: int = Field(
title="Minimum Year",
description="The minimum publication year of the works in the collaboration network.",
)
max_possible_year: int = Field(
title="Maximum Year",
description="The maximum publication year of the works in the collaboration network.",
)
institutions: List[InstitutionInformation] = Field(
title="Institutions",
description="The list of institutions associated with the works in the collaboration network.",
)
topics: List[WorkTopicInformation] = Field(
title="Topics",
description="The list of topics associated with the works in the collaboration network.",
)
class WorksFilterProperties(BaseModel):
start_year: int = Field(
default=0,
title="Start Year",
description="The start publication year for the works to include in the collaboration network.",
)
end_year: int = Field(
default=9999,
title="End Year",
description="The end publication year for the works to include in the collaboration network.",
)
allowed_topics: List[str] = Field(
default_factory=list,
title="Allowed Topics",
description="The list of raw topic IDs to include in the collaboration network. If empty, all topics will be included.",
)
min_contributors: int = Field(
default=1,
title="Minimum Contributors",
description="The minimum number of contributors required for a work to be included in the collaboration network.",
)
max_contributors: int = Field(
default=100,
title="Maximum Contributors",
description="The maximum number of contributors allowed for a work to be included in the collaboration network.",
)
class AuthorsFilterProperties(BaseModel):
allowed_institutions: List[str] = Field(
default_factory=list,
title="Allowed Institutions",
description="The list of raw institution IDs to include in the collaboration network. If empty, all institutions will be included.",
)
min_collaborations: int = Field(
default=1,
title="Minimum Collaborations",
description="The minimum number of collaborations required for an author to be included in the collaboration network.",
)
max_collaborations: int = Field(
default=1000,
title="Maximum Collaborations",
description="The maximum number of collaborations allowed for an author to be included in the collaboration network.",
)
class FilterProperties(BaseModel):
filter_by: str = Field(
default="works",
title="Filter By",
description="The type of filter to apply when generating the collaboration network. Can be either 'works' or 'authors'. If 'works', the filter properties in the 'works_filter_properties' field will be used. If 'authors', the filter properties in the 'authors_filter_properties' field will be used.",
)
works_filter_properties: Optional[WorksFilterProperties] = Field(
title="Works Filter Properties",
description="The filter properties to apply when filtering works for the collaboration network. This field is only applicable if the 'filter_by' field is set to 'works'.",
)
authors_filter_properties: Optional[AuthorsFilterProperties] = Field(
title="Authors Filter Properties",
description="The filter properties to apply when filtering authors for the collaboration network. This field is only applicable if the 'filter_by' field is set to 'authors'.",
)
class CollaborationNetworkNode(BaseModel):
raw_id: str = Field(
title="Raw ID",
description="The raw ID of the node. For an author node, this is the raw person ID. For an institution node, this is the raw institution ID. For a work node, this is the raw work ID.",
)
display_name: str = Field(
title="Display Name", description="The display name of the node."
)
category: CollaborationNetworkNodeType = Field(
title="Category",
description="The category of the node, either 'author', 'institution', or 'work'.",
)
def __eq__(self, value: object) -> bool:
if isinstance(value, CollaborationNetworkNode):
return self.raw_id == value.raw_id
return False
def __hash__(self) -> int:
return hash(self.raw_id)
class WorkNetworkNode(CollaborationNetworkNode):
publication_year: Optional[int] = Field(
title="Publication Year",
description="The publication year of the work represented by this node. This field is only applicable if the category of the node is 'work'.",
)
work_topics_information: Optional[Set[WorkTopicInformation]] = Field(
title="Work Topics Information",
description="The list of topic information associated with the work represented by this node. This field is only applicable if the category of the node is 'work'.",
)
def __eq__(self, value: object) -> bool:
if isinstance(value, WorkNetworkNode):
return self.raw_id == value.raw_id
return False
def __hash__(self) -> int:
return hash(self.raw_id)
class AuthorNetworkNode(CollaborationNetworkNode):
def __eq__(self, value: object) -> bool:
if isinstance(value, AuthorNetworkNode):
return self.raw_id == value.raw_id
return False
def __hash__(self) -> int:
return hash(self.raw_id)
class InstitutionNetworkNode(CollaborationNetworkNode):
def __eq__(self, value: object) -> bool:
if isinstance(value, InstitutionNetworkNode):
return self.raw_id == value.raw_id
return False
def __hash__(self) -> int:
return hash(self.raw_id)
class CollaborationNetworkEdge(BaseModel):
raw_source_id: str = Field(
title="Source Raw ID",
description="The raw ID of the source node.",
)
raw_target_id: str = Field(
title="Target Raw ID",
description="The raw ID of the target node.",
)
def __eq__(self, value: object) -> bool:
if isinstance(value, CollaborationNetworkEdge):
return self.same_collaboration(self, value)
return False
def __hash__(self) -> int:
return hash((self.raw_source_id, self.raw_target_id))
@classmethod
def same_collaboration(
cls, edge1: "CollaborationNetworkEdge", edge2: "CollaborationNetworkEdge"
) -> bool:
"""Checks if two edges have the same source and target person IDs, regardless of order.
Args:
edge1 (CollaborationNetworkEdge): The first collaboration edge.
edge2 (CollaborationNetworkEdge): The second collaboration edge.
Returns:
bool: True if the edges have the same source and target person IDs (undirected), False otherwise.
"""
return (
edge1.raw_source_id == edge2.raw_source_id
and edge1.raw_target_id == edge2.raw_target_id
) or (
edge1.raw_source_id == edge2.raw_target_id
and edge1.raw_target_id == edge2.raw_source_id
)
class CollaborationNetwork(BaseModel):
raw_person_id: str = Field(
title="Raw Person ID",
description="The raw person ID of the person whose collaboration network this is.",
)
work_nodes: List[WorkNetworkNode] = Field(
title="Collaboration Network Work Nodes",
description="The work nodes in the collaboration network.",
)
author_nodes: List[AuthorNetworkNode] = Field(
title="Collaboration Network Author Nodes",
description="The author nodes in the collaboration network.",
)
institution_nodes: List[InstitutionNetworkNode] = Field(
title="Collaboration Network Institution Nodes",
description="The institution nodes in the collaboration network.",
)
collaboration_edges: List[CollaborationNetworkEdge] = Field(
title="Collaboration Network Edges",
description="The collaboration edges in the collaboration network. A collaboration edge represents a collaboration between two nodes. A -> W and A -> I",
)
filter_information: FilterInformation = Field(
title="Filter Information",
description="The filter information for the collaboration network, including the minimum and maximum publication years of the works in the collaboration network.",
)
@@ -1,708 +0,0 @@
from collections import defaultdict
import logging
from typing import List, Optional, Set, Tuple
from inse.collaboration_network.schemas import (
AuthorNetworkNode,
AuthorsFilterProperties,
CollaborationNetwork,
CollaborationNetworkEdge,
CollaborationNetworkNodeType,
FilterInformation,
FilterProperties,
InstitutionInformation,
InstitutionNetworkNode,
WorkNetworkNode,
WorkTopicInformation,
WorksFilterProperties,
)
from inse.works import logic as work_logic
from inse.works.model import Work
from inse.utils import (
extract_raw_author_id,
extract_raw_institution_id,
extract_raw_topic_id,
extract_raw_work_id,
)
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__)
logger.setLevel(logging.INFO)
async def get_collaboration_network(
raw_user_id: str,
filter_properties: FilterProperties,
) -> CollaborationNetwork:
"""Generates a collaboration network for a given user ID based on the works associated with that user, and applies filtering to the network based on the specified filter properties, which may include criteria such as publication year range, allowed topics, minimum/maximum number of contributors, and minimum/maximum number of collaborations.
The function returns a collaboration network that includes the works, authors, and institutions that are relevant to the specified user and meet the filtering criteria defined in the filter properties.
Args:
raw_user_id (str): The raw user ID for whom to generate the collaboration network.
filter_properties (FilterProperties): The filter properties for the collaboration network.
Returns:
CollaborationNetwork: The collaboration network for the given user.
"""
raw_user_id = raw_user_id.strip().upper()
work_page = await work_logic.get_all_author_works(author_id=raw_user_id)
works: List[Work] = work_page.results or []
collaboration_network = build_collaboration_network(
raw_user_id=raw_user_id, works=works
)
if filter_properties.filter_by == "works":
if not filter_properties.works_filter_properties:
filter_properties.works_filter_properties = WorksFilterProperties()
return filter_collaboration_network_by_works(
raw_user_id=raw_user_id,
collaboration_network=collaboration_network,
works_filter_properties=filter_properties.works_filter_properties,
)
elif filter_properties.filter_by == "authors":
if not filter_properties.authors_filter_properties:
filter_properties.authors_filter_properties = AuthorsFilterProperties()
return filter_collaboration_network_by_authors(
raw_user_id=raw_user_id,
collaboration_network=collaboration_network,
filter_properties=filter_properties.authors_filter_properties,
)
else:
logger.warning(
f"Invalid filter_by value in filter properties: {filter_properties.filter_by}. Expected 'works' or 'authors'. No additional filtering will be applied."
)
return collaboration_network
def filter_collaboration_network_by_authors(
raw_user_id: str,
collaboration_network: CollaborationNetwork,
filter_properties: AuthorsFilterProperties,
) -> CollaborationNetwork:
"""Filters the given collaboration network based on the specified author filter properties, which may include criteria such as allowed institutions and minimum/maximum number of collaborations.
The function returns a new collaboration network that only includes authors that meet the specified criteria, along with their associated works and institutions.
Args:
raw_user_id (str): The raw user ID for whom to filter the collaboration network.
collaboration_network (CollaborationNetwork): The collaboration network to filter.
filter_properties (AuthorsFilterProperties): The filter properties for the author filtering.
Returns:
CollaborationNetwork: The filtered collaboration network.
"""
logger.debug(
f"Filtering collaboration network for user {raw_user_id} with author filter properties: {filter_properties}"
)
all_author_nodes = set(collaboration_network.author_nodes)
remaining_author_ids = {node.raw_id for node in all_author_nodes}
remaining_institution_nodes = set(collaboration_network.institution_nodes)
logger.debug(f"Remaining author IDs before filtering: {remaining_author_ids}")
# 1. Filter author nodes based on allowed institutions in filter properties
if len(filter_properties.allowed_institutions) > 0:
logger.debug(
f"Filtering author nodes based on allowed institutions: {filter_properties.allowed_institutions}"
)
remaining_author_ids = {
edge.raw_source_id
for edge in collaboration_network.collaboration_edges
if edge.raw_target_id in filter_properties.allowed_institutions
}
remaining_institution_nodes = {
node
for node in collaboration_network.institution_nodes
if node.raw_id in filter_properties.allowed_institutions
}
logger.debug(
f"Remaining author IDs after filtering by allowed institutions: {remaining_author_ids}"
)
# 2. Filter out collaboration edges that are associated with author nodes that have been filtered out
remaining_work_edges = {
edge
for edge in collaboration_network.collaboration_edges
if edge.raw_source_id in remaining_author_ids
and edge.raw_target_id.lower().startswith("w")
}
logger.debug(
f"Remaining work edges after filtering by allowed institutions: {len(remaining_work_edges)}"
)
works_per_author = defaultdict(set)
for edge in remaining_work_edges:
if (
edge.raw_source_id in remaining_author_ids
and edge.raw_target_id.lower().startswith("w")
):
works_per_author[edge.raw_source_id].add(edge.raw_target_id)
logger.debug(
f"Works per author after filtering by allowed institutions: {dict(works_per_author)}"
)
# 3. Filter out author that do not have enough collaborations based on the filter properties
remaining_author_ids = {
author_id
for author_id, work_ids in works_per_author.items()
if filter_properties.min_collaborations
<= len(work_ids)
<= filter_properties.max_collaborations
}
remaining_author_ids.add(raw_user_id) # main author always included
remaining_author_nodes = {
node
for node in collaboration_network.author_nodes
if node.raw_id in remaining_author_ids
}
remaining_institutions_edges = {
edge
for edge in collaboration_network.collaboration_edges
if edge.raw_source_id in remaining_author_ids
and edge.raw_target_id.lower().startswith("i")
}
# 4. Remove institution nodes that are not connected to any of the remaining author nodes
institution_ids_with_remaining_authors = {
edge.raw_target_id
for edge in remaining_institutions_edges
if edge.raw_source_id in remaining_author_ids
}
remaining_institution_nodes = {
node
for node in remaining_institution_nodes
if node.raw_id in institution_ids_with_remaining_authors
}
return CollaborationNetwork(
raw_person_id=raw_user_id,
work_nodes=collaboration_network.work_nodes,
author_nodes=list(remaining_author_nodes),
institution_nodes=list(remaining_institution_nodes),
collaboration_edges=list(remaining_work_edges)
+ list(remaining_institutions_edges),
filter_information=collaboration_network.filter_information,
)
def filter_collaboration_network_by_works(
raw_user_id: str,
collaboration_network: CollaborationNetwork,
works_filter_properties: WorksFilterProperties,
) -> CollaborationNetwork:
"""Filters the given collaboration network based on the specified works filter properties, which may include criteria such as publication year range, allowed topics, and minimum/maximum number of contributors.
The function returns a new collaboration network that only includes works that meet the specified criteria, along with their associated authors and institutions.
Args:
raw_user_id (str): _description_
collaboration_network (CollaborationNetwork): _description_
works_filter_properties (WorksFilterProperties): _description_
Returns:
CollaborationNetwork: The filtered collaboration network.
"""
if not works_filter_properties:
return collaboration_network
all_work_nodes = set(collaboration_network.work_nodes)
valid_work_ids = {node.raw_id for node in all_work_nodes}
# 1. Filter out works that are not in the specified year range or do not have allowed topics, and update valid_work_ids accordingly
valid_work_ids = filter_works_by_year_and_topic(
works=all_work_nodes,
filter_properties=works_filter_properties,
valid_work_ids=valid_work_ids,
)
# 2. Filter out works that do not have enough collaborators based on the filter properties, and update valid_work_ids accordingly
if (
works_filter_properties.min_contributors
or works_filter_properties.max_contributors
):
contributors_per_work = defaultdict(set)
for edge in collaboration_network.collaboration_edges:
if (
edge.raw_target_id.lower().startswith("w")
and edge.raw_target_id in valid_work_ids
):
contributors_per_work[edge.raw_target_id].add(edge.raw_source_id)
valid_work_ids = set()
for work_id, contributors in contributors_per_work.items():
contributors_count = len(contributors)
if has_enough_contributors(
contributors_count=contributors_count,
filter_properties=works_filter_properties,
):
valid_work_ids.add(work_id)
# 3. Filter out collaboration edges that are associated with works that have been filtered out
remaining_work_edges = {
edge
for edge in collaboration_network.collaboration_edges
if edge.raw_target_id in valid_work_ids
and edge.raw_target_id.lower().startswith("w")
}
# 4. Identify author nodes that are still valid based on their association with the remaining valid works
author_ids_with_valid_works = {edge.raw_source_id for edge in remaining_work_edges}
# 5. Identify institution nodes that are still valid based on their association with the remaining valid author nodes
institution_ids_with_valid_authors = {
edge.raw_target_id
for edge in collaboration_network.collaboration_edges
if edge.raw_source_id in author_ids_with_valid_works
and edge.raw_target_id.lower().startswith("i")
}
remaining_collaboration_edges = {
edge
for edge in collaboration_network.collaboration_edges
if (
edge.raw_target_id in valid_work_ids
and edge.raw_target_id.lower().startswith("w")
)
or (
edge.raw_source_id in author_ids_with_valid_works
and edge.raw_target_id.lower().startswith("i")
)
or (
edge.raw_source_id in author_ids_with_valid_works
and edge.raw_target_id in institution_ids_with_valid_authors
)
}
remaining_work_nodes = {
node
for node in collaboration_network.work_nodes
if node.raw_id in valid_work_ids
}
remaining_author_nodes = {
node
for node in collaboration_network.author_nodes
if node.raw_id in author_ids_with_valid_works
}
remaining_institution_nodes = {
node
for node in collaboration_network.institution_nodes
if node.raw_id in institution_ids_with_valid_authors
}
return CollaborationNetwork(
raw_person_id=raw_user_id,
work_nodes=list(remaining_work_nodes),
author_nodes=list(remaining_author_nodes),
institution_nodes=list(remaining_institution_nodes),
collaboration_edges=list(remaining_collaboration_edges),
filter_information=collaboration_network.filter_information,
)
def filter_works_by_year_and_topic(
works: Set[WorkNetworkNode],
filter_properties: WorksFilterProperties,
valid_work_ids: Set[str],
):
"""Determines the set of valid work IDs by filtering the given set of works based on the specified year range and allowed topics defined in the filter properties.
Args:
works (Set[WorkNetworkNode]): The set of works to filter.
filter_properties (WorksFilterProperties): The filter properties containing the year range and allowed topics.
valid_work_ids (Set[str]): The set of valid work IDs to update.
Returns:
Set[str]: The updated set of valid work IDs.
"""
if not any(
[
filter_properties.start_year,
filter_properties.end_year,
filter_properties.allowed_topics,
]
):
return valid_work_ids
for work in works:
if not is_in_year_range(
year=work.publication_year or -1,
works_filter_properties=filter_properties,
) or not has_allowed_topic(work, filter_properties):
valid_work_ids.discard(work.raw_id)
return valid_work_ids
def is_in_year_range(year: int, works_filter_properties: WorksFilterProperties) -> bool:
"""Determines whether a given year falls within the specified year range defined in the filter properties.
Args:
year (int): The year to check.
works_filter_properties (WorksFilterProperties): The filter properties containing the year range.
Returns:
bool: True if the year falls within the specified range, False otherwise.
"""
# no year extracted, excluding work by default
if year == -1:
return False
if works_filter_properties.start_year and year < works_filter_properties.start_year:
return False
if works_filter_properties.end_year and year > works_filter_properties.end_year:
return False
return True
def has_allowed_topic(
work: WorkNetworkNode, filter_properties: WorksFilterProperties
) -> bool:
"""Determines whether a given work has at least one topic that is included in the allowed topics specified in the filter properties.
Args:
work (WorkNetworkNode): The work for which to check the topics.
filter_properties (WorksFilterProperties): The filter properties containing the allowed topics.
Returns:
bool: True if the work has at least one allowed topic, False otherwise.
"""
if len(filter_properties.allowed_topics) == 0:
return True
return any(
topic.raw_topic_id in filter_properties.allowed_topics
for topic in work.work_topics_information or set()
)
def has_enough_contributors(
contributors_count: int, filter_properties: WorksFilterProperties
) -> bool:
"""Determines whether a given number of contributors meets the specified minimum and maximum contributor requirements defined in the filter properties.
Args:
contributors_count (int): The number of contributors to check.
filter_properties (WorksFilterProperties): The filter properties containing the contributor requirements.
Returns:
bool: True if the contributor count meets the requirements, False otherwise.
"""
if filter_properties and contributors_count < filter_properties.min_contributors:
return False
if (
filter_properties.max_contributors
and contributors_count > filter_properties.max_contributors
):
return False
return True
def build_collaboration_network(
raw_user_id: str,
works: List[Work],
) -> CollaborationNetwork:
"""Builds a collaboration network for a given user ID based on the provided list of works.
Args:
raw_user_id (str): The raw ID of the user for whom to build the collaboration network.
works (List[Work]): The list of works for which to build the collaboration network.
Returns:
CollaborationNetwork: The built collaboration network.
"""
min_possible_year = float("inf")
max_possible_year = float("-inf")
work_nodes: Set[WorkNetworkNode] = set()
all_author_nodes: Set[AuthorNetworkNode] = set()
all_institution_nodes: Set[InstitutionNetworkNode] = set()
all_collaboration_edges: Set[CollaborationNetworkEdge] = set()
work_topics_information: Set[WorkTopicInformation] = set()
for work in works:
work_node, author_nodes, institution_nodes, collaboration_edges = process_work(
work=work
)
if not work_node:
continue
min_possible_year = min(
min_possible_year, work_node.publication_year or float("inf")
)
max_possible_year = max(
max_possible_year, work_node.publication_year or float("-inf")
)
work_topics_information.update(work_node.work_topics_information or set())
work_nodes.add(work_node)
all_author_nodes.update(author_nodes)
all_institution_nodes.update(institution_nodes)
all_collaboration_edges.update(collaboration_edges)
return CollaborationNetwork(
raw_person_id=raw_user_id,
work_nodes=list(work_nodes),
author_nodes=list(all_author_nodes),
institution_nodes=list(all_institution_nodes),
collaboration_edges=list(all_collaboration_edges),
filter_information=FilterInformation(
min_possible_year=int(min_possible_year),
max_possible_year=int(max_possible_year),
institutions=sorted(
{
InstitutionInformation(
raw_id=institution.raw_id, display_name=institution.display_name
)
for institution in all_institution_nodes
},
key=lambda inst: inst.display_name,
),
topics=sorted(
work_topics_information, key=lambda topic: topic.display_name
),
),
)
def process_work(
work: Work,
) -> Tuple[
Optional[WorkNetworkNode],
Set[AuthorNetworkNode],
Set[InstitutionNetworkNode],
Set[CollaborationNetworkEdge],
]:
"""Processes a given work to extract the associated work node, author nodes, institution nodes, and collaboration edges for the collaboration network.
Args:
work (Work): The work to process.
Returns:
Tuple[ Optional[WorkNetworkNode], Set[AuthorNetworkNode], Set[InstitutionNetworkNode], Set[CollaborationNetworkEdge], ]: A tuple containing the associated work node, author nodes, institution nodes, and collaboration edges.
"""
year = get_work_year(work)
topics_information = extract_topics_information(work=work)
work_node = create_work_node(
work=work, year=year, work_topics_information=topics_information
)
if not work_node:
return None, set(), set(), set()
authorships = work.authorships
if not authorships:
return work_node, set(), set(), set()
author_nodes: Set[AuthorNetworkNode] = set()
institution_nodes: Set[InstitutionNetworkNode] = set()
collaboration_edges: Set[CollaborationNetworkEdge] = set()
for authorship in authorships:
author_node, institution_nodes, associated_institution_edges = (
process_authorship(authorship=authorship)
)
if not author_node:
continue
work_author_edge = CollaborationNetworkEdge(
raw_source_id=author_node.raw_id,
raw_target_id=work_node.raw_id,
)
author_nodes.add(author_node)
collaboration_edges.add(work_author_edge)
institution_nodes.update(institution_nodes)
collaboration_edges.update(associated_institution_edges)
return (
work_node,
author_nodes,
institution_nodes,
collaboration_edges,
)
def get_work_year(work: Work) -> int:
"""Extracts the publication year from a given work.
Args:
work (Work): The work from which to extract the publication year.
Returns:
int: The publication year of the work, or -1 if it cannot be extracted.
"""
if not work.publication_year:
return -1
try:
return int(work.publication_year)
except ValueError:
return -1
def create_work_node(
work: Work, year: int, work_topics_information: Set[WorkTopicInformation]
) -> Optional[WorkNetworkNode]:
"""Creates a collaboration network node representing a work based on the provided work data, publication year, and topic information.
Args:
work (Work): The work from which to create the collaboration network node.
year (int): The publication year of the work.
work_topics_information (Set[WorkTopicInformation]): The topic information of the work.
Returns:
Optional[WorkNetworkNode]: The collaboration network node representing the work, or None if the work data is invalid.
"""
if not work or not work.id or not work.display_name:
return None
work_id = extract_raw_work_id(work.id)
display_name = work.display_name
return WorkNetworkNode(
raw_id=work_id,
display_name=display_name,
category=CollaborationNetworkNodeType.WORK,
publication_year=year,
work_topics_information=work_topics_information,
)
def extract_topics_information(work: Work) -> Set[WorkTopicInformation]:
"""Extracts the topic information from a given work and returns it as a set of WorkTopicInformation objects.
Args:
work (Work): The work from which to extract topic information.
Returns:
Set[WorkTopicInformation]: A set of WorkTopicInformation objects representing the topics of the work.
"""
topics_information: Set[WorkTopicInformation] = set()
for topic in work.topics or []:
if not topic.id or not topic.display_name:
continue
raw_topic_id = extract_raw_topic_id(topic.id)
topics_information.add(
WorkTopicInformation(
raw_topic_id=raw_topic_id, display_name=topic.display_name
)
)
return topics_information
def process_authorship(
authorship: Authorship,
) -> Tuple[
Optional[AuthorNetworkNode],
Set[InstitutionNetworkNode],
Set[CollaborationNetworkEdge],
]:
"""Processes a given authorship to extract the associated author node, institution nodes, and collaboration edges.
Args:
authorship (Authorship): The authorship data to process.
Returns:
Tuple[ Optional[AuthorNetworkNode], Set[InstitutionNetworkNode], Set[CollaborationNetworkEdge], ]: A tuple containing the associated author node, institution nodes, and collaboration edges.
"""
author = authorship.author
if not author or not author.id or not author.display_name:
return None, set(), set()
author_node = create_author_node(author)
if not author_node:
return None, set(), set()
institution_nodes: Set[InstitutionNetworkNode] = set()
for institution in authorship.institutions or []:
institution_id = extract_raw_institution_id(institution.id or "")
if not institution_id or not institution.display_name:
continue
institution_node = create_institution_node(institution)
if institution_node:
institution_nodes.add(institution_node)
associated_institution_edges = create_associated_institution_edges(
author_node=author_node, institution_nodes=institution_nodes
)
return author_node, institution_nodes, associated_institution_edges
def create_associated_institution_edges(
author_node: AuthorNetworkNode,
institution_nodes: Set[InstitutionNetworkNode],
) -> Set[CollaborationNetworkEdge]:
"""Creates a set of collaboration network edges representing the associations between an author and their affiliated institutions.
Args:
author_node (AuthorNetworkNode): The collaboration network node representing the author.
institution_nodes (Set[InstitutionNetworkNode]): A set of collaboration network nodes representing the institutions affiliated with the author.
Returns:
Set[CollaborationNetworkEdge]: A set of collaboration network edges representing the associations between the author and their affiliated institutions.
"""
return {
CollaborationNetworkEdge(
raw_source_id=author_node.raw_id,
raw_target_id=institution_node.raw_id,
)
for institution_node in institution_nodes
}
def create_author_node(
author: Author | DehydratedAuthor,
) -> Optional[AuthorNetworkNode]:
"""Creates a collaboration network node representing an author based on the provided author data.
Args:
author (Author | DehydratedAuthor): The author data from which to create the collaboration network node.
Returns:
Optional[AuthorNetworkNode]: The collaboration network node representing the author, or None if the author data is invalid.
"""
if not author or not author.id or not author.display_name:
return None
author_id = extract_raw_author_id(author.id)
display_name = author.display_name
return AuthorNetworkNode(
raw_id=author_id,
display_name=display_name,
category=CollaborationNetworkNodeType.AUTHOR,
)
def create_institution_node(
institution: Institution | DehydratedInstitution,
) -> Optional[InstitutionNetworkNode]:
"""Creates a collaboration network node representing an institution based on the provided institution data.
Args:
institution (Institution | DehydratedInstitution): The institution data from which to create the collaboration network node.
Returns:
Optional[InstitutionNetworkNode]: The collaboration network node representing the institution, or None if the institution data is invalid.
"""
if not institution or not institution.id or not institution.display_name:
return None
institution_id = extract_raw_institution_id(institution.id)
display_name = institution.display_name
return InstitutionNetworkNode(
raw_id=institution_id,
display_name=display_name,
category=CollaborationNetworkNodeType.INSTITUTION,
)
@@ -2,18 +2,30 @@ import logging
from typing import Any
from . import model
from inse.exceptions import MissingApiKeyError, ElasticsearchException, NotFoundException
from inse.authors.v2.service import author_currently_belongs_to_institution
from inse.exceptions import NotFoundException
from .search_client import CompanyConnectionsSearchClient
logger = logging.getLogger(__name__)
UDE_OPENALEX_ID = "https://openalex.org/I62318514"
UDE_ROR = "https://ror.org/04mz5ra38"
UDE_DISPLAY_NAME = "University of Duisburg-Essen"
MATCHING_METHOD = "exact_openalex_display_name_to_handelsregister_officer_name"
async def author_has_company_connections_access(
author_id: str,
institution_id: str | None,
) -> bool:
"""Return whether the author belongs to the account institution's active cohort."""
if not institution_id:
return False
return await author_currently_belongs_to_institution(
raw_oa_author_id=author_id,
raw_oa_institution_id=institution_id,
)
async def get_company_connections_by_author_id(
author_id: str,
client: CompanyConnectionsSearchClient | None = None,
@@ -27,16 +39,11 @@ async def get_company_connections_by_author_id(
source = author_hit.get("_source", {})
display_name = _clean(source.get("display_name"))
institution_scope, matching_institutions = _get_ude_institution_scope(source)
is_ude_author = institution_scope is not None
if not is_ude_author or not display_name:
if not display_name:
return model.CompanyConnectionsResponse(
author_id=author_id,
display_name=display_name or None,
is_ude_author=is_ude_author,
institution_scope=institution_scope,
matching_institutions=matching_institutions,
matching_method=None,
company_count=0,
has_more_results=False,
@@ -62,9 +69,6 @@ async def get_company_connections_by_author_id(
return model.CompanyConnectionsResponse(
author_id=author_id,
display_name=display_name,
is_ude_author=True,
institution_scope=institution_scope,
matching_institutions=matching_institutions,
matching_method=MATCHING_METHOD,
company_count=company_count,
has_more_results=has_more_results,
@@ -73,42 +77,26 @@ async def get_company_connections_by_author_id(
)
def _get_ude_institution_scope(source: dict[str, Any]) -> tuple[str | None, list[str]]:
institutions = source.get("last_known_institutions") or []
async def get_company_counts_by_names(
names: list[str],
company_status: str = "all",
client: CompanyConnectionsSearchClient | None = None,
) -> dict[str, int]:
"""Bulk variant of the per-author lookup for the ranking pipeline.
direct_matches: list[str] = []
child_matches: list[str] = []
Returns a mapping ``display_name -> company_count`` for the given names in a
single Elasticsearch aggregation. Names without a match are absent from the
mapping (callers should treat them as 0). ``company_status`` selects which
companies to count: ``all``, only ``active`` (non-deleted), or only ``deleted``.
"""
search_client = client or CompanyConnectionsSearchClient()
cleaned = [name for name in (_clean(n) for n in names) if name]
if not cleaned:
return {}
for institution in institutions:
if not isinstance(institution, dict):
continue
institution_id = _clean(institution.get("id"))
ror = _clean(institution.get("ror"))
name = _clean(institution.get("display_name"))
lineage = institution.get("lineage") or []
label = name or institution_id or ror
is_direct = (
institution_id == UDE_OPENALEX_ID
or ror == UDE_ROR
or name == UDE_DISPLAY_NAME
)
is_child = UDE_OPENALEX_ID in lineage and not is_direct
if is_direct:
direct_matches.append(label)
elif is_child:
child_matches.append(label)
if direct_matches:
return "direct_ude", sorted(set(direct_matches))
if child_matches:
return "child_of_ude", sorted(set(child_matches))
return None, []
return await search_client.count_companies_by_founder_names(
cleaned, company_status=str(company_status)
)
def _parse_total(response: dict[str, Any]) -> tuple[int, str]:
@@ -28,12 +28,13 @@ class CompanyConnection(BaseModel):
officers: list[MatchedOfficer] = Field(default_factory=list)
class CompanyConnectionsAvailability(BaseModel):
available: bool
class CompanyConnectionsResponse(BaseModel):
author_id: str
display_name: str | None = None
is_ude_author: bool
institution_scope: str | None = None
matching_institutions: list[str] = Field(default_factory=list)
matching_method: str | None = None
@@ -58,6 +58,112 @@ class CompanyConnectionsSearchClient:
cluster=ESCluster.NES,
)
async def count_companies_by_founder_names(
self,
founder_names: list[str],
company_status: str = "all",
) -> dict[str, int]:
"""Returns the number of companies they are linked to a author.
``company_status`` selects which companies are counted: ``all``, only
``active`` (non-deleted), or only ``deleted`` (``current_status: removed``).
"""
names = sorted({name for name in founder_names if name})
if not names:
return {}
payload = self.handelsregister_founder_counts_query(names, company_status)
response = await elasticsearch.search(
index=self.handelsregister_index,
body=payload,
cluster=ESCluster.NES,
)
buckets = (
response.get("aggregations", {})
.get("founders", {})
.get("matched", {})
.get("by_name", {})
.get("buckets", [])
)
counts: dict[str, int] = {}
for bucket in buckets:
name = bucket.get("key", "")
if not name:
continue
counts[name] = int(bucket.get("companies", {}).get("doc_count", 0))
return counts
@staticmethod
def handelsregister_founder_counts_query(
founder_names: list[str],
company_status: str = "all",
) -> dict[str, Any]:
"""Aggregation that counts distinct companies per founder name.
The ``matched`` filter keeps only the founders whose name is one of the
candidates, then ``reverse_nested`` steps back to the company level so the
per-name ``doc_count`` is a company count, not a founder-occurrence count.
``company_status`` restricts which companies are counted at the company
level: ``all`` (no restriction), only ``active`` (exclude
``current_status: removed``), or only ``deleted`` (only that status).
"""
query_filters: list[dict[str, Any]] = [
{
"nested": {
"path": "officers",
"query": {
"bool": {
"filter": [
{"term": {"officers.type": "person"}},
{"terms": {"officers.name.keyword": founder_names}},
]
}
},
}
}
]
bool_query: dict[str, Any] = {"filter": query_filters}
if company_status == "active":
bool_query["must_not"] = [{"term": {"current_status": "removed"}}]
elif company_status == "deleted":
query_filters.append({"term": {"current_status": "removed"}})
return {
"size": 0,
"track_total_hits": False,
"query": {"bool": bool_query},
"aggs": {
"founders": {
"nested": {"path": "officers"},
"aggs": {
"matched": {
"filter": {
"terms": {"officers.name.keyword": founder_names},
},
"aggs": {
"by_name": {
"terms": {
"field": "officers.name.keyword",
"size": len(founder_names),
"execution_hint": "map",
},
"aggs": {
# step back to the company (parent) level so
# the count is distinct companies per name
"companies": {"reverse_nested": {}},
},
},
},
},
},
},
},
}
@staticmethod
def handelsregister_officer_name_query(
officer_name: str,
@@ -4,7 +4,12 @@
REST API for possible company connections of OpenAlex authors.
"""
from fastapi import APIRouter
from typing import Annotated
from fastapi import APIRouter, HTTPException, status
from inse.auth.model import AccessTokenMetadata
from inse.auth.service import CurrentUserAccessTokenPayloadDep
from . import logic, model
@@ -14,6 +19,25 @@ router = APIRouter(
)
@router.get(
"/{author_id}/company-connections/availability",
operation_id="getCompanyConnectionsAvailability",
response_model=model.CompanyConnectionsAvailability,
summary="Check whether company connections are available for an author.",
)
async def get_company_connections_availability(
access_token_metadata: Annotated[
AccessTokenMetadata, CurrentUserAccessTokenPayloadDep
],
author_id: str,
) -> model.CompanyConnectionsAvailability:
available = await logic.author_has_company_connections_access(
author_id=author_id,
institution_id=access_token_metadata.effective_institution_id,
)
return model.CompanyConnectionsAvailability(available=available)
@router.get(
"/{author_id}/company-connections",
operation_id="getCompanyConnectionsByAuthor",
@@ -21,5 +45,23 @@ router = APIRouter(
response_model_exclude_none=True,
summary="Get possible company connections by OpenAlex author ID.",
)
async def get_company_connections_by_author(author_id: str):
async def get_company_connections_by_author(
access_token_metadata: Annotated[
AccessTokenMetadata, CurrentUserAccessTokenPayloadDep
],
author_id: str,
):
available = await logic.author_has_company_connections_access(
author_id=author_id,
institution_id=access_token_metadata.effective_institution_id,
)
if not available:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=(
"Company connections are only available for active members "
"of the account institution."
),
)
return await logic.get_company_connections_by_author_id(author_id)
+22 -2
View File
@@ -7,6 +7,7 @@ that can be adjusted via environment variables.
from functools import lru_cache
import logging
from pathlib import Path
from typing import Dict, List, Literal, Optional
from pydantic_settings import BaseSettings, SettingsConfigDict
from dotenv import load_dotenv
@@ -14,7 +15,10 @@ from dotenv import load_dotenv
logger = logging.getLogger(__name__)
load_dotenv()
# Anchor the .env to this file's directory so it loads regardless of the
# process working directory.
ENV_FILE = Path(__file__).resolve().parent / ".env"
load_dotenv(ENV_FILE)
class Settings(BaseSettings):
@@ -43,6 +47,20 @@ class Settings(BaseSettings):
llm_api_key: Optional[str] = None
llm_model: Optional[str] = None
# Background job runner config (Docker-out-of-Docker)
background_jobs_image: str = "docker.nes.uni-due.de/inse/background-jobs:latest"
background_jobs_scheduler_enabled: bool = True
background_jobs_tick_seconds: int = 5
# Pull the job image from the registry before each run so an updated tag
# (e.g. :latest) is picked up. Disable for local image development, where
# a locally built image would otherwise be overwritten by the registry.
background_jobs_pull_before_run: bool = True
# Credentials for pulling the job image from a private registry (e.g. the
# Nexus at docker.nes.uni-due.de). Needed because the runner pulls via the
# Docker SDK inside the service container, which has no `docker login` creds.
background_jobs_registry_username: Optional[str] = None
background_jobs_registry_password: Optional[str] = None
# Sentence Transformers config
sentence_transformers_model_name: str = "intfloat/multilingual-e5-base"
@@ -51,8 +69,10 @@ class Settings(BaseSettings):
elasticsearch_api_key: Optional[str] = None
elasticsearch_inse_url: Optional[str] = None
elasticsearch_inse_api_key: Optional[str] = None
print_es_queries: bool = False
print_es_timings: bool = False
model_config = SettingsConfigDict(env_file=".env")
model_config = SettingsConfigDict(env_file=str(ENV_FILE))
allowed_origins: List[str] = ["http://localhost:4200"]
@@ -0,0 +1,29 @@
from inse.exceptions import NotFoundException
from inse.integrations import elasticsearch
from inse.model import ESIndex
from inse.models.openalex.institution import Institution
async def get_openalex_institution(institution_id: str) -> Institution:
"""Load an institution from OpenAlex using the user's institution ID."""
raw_institution_id = institution_id.strip().removeprefix(
"https://openalex.org/"
)
normalized_id = f"https://openalex.org/{raw_institution_id.upper()}"
response = await elasticsearch.search(
index=ESIndex.OPENALEX_INSTITUTIONS,
query={"term": {"id": normalized_id}},
size=1,
)
hits = response.get("hits", {}).get("hits", [])
if not hits:
raise NotFoundException(
f"Institution with ID '{raw_institution_id}' not found."
)
institution = Institution.from_dict(hits[0].get("_source", {}))
if institution is None:
raise NotFoundException(
f"Institution with ID '{raw_institution_id}' could not be parsed."
)
return institution
+69
View File
@@ -18,6 +18,47 @@ class DashboardStatisticValue(BaseModel):
value: int
class EuProjectStatusStatistics(BaseModel):
institution_id: str
organization_name: str
ongoing: int
upcoming: int
completed: int
class BmbfProjectStatusStatistics(BaseModel):
institution_id: str
organization_name: str
ongoing: int
upcoming: int
completed: int
class DfgProjectStatusStatistics(BaseModel):
institution_id: str
organization_name: str
ongoing: int
upcoming: int
completed: int
class DfgProjectTopic(BaseModel):
id: str
name: str
subfield: str | None = None
field: str | None = None
domain: str | None = None
project_count: int
class DfgProjectTopics(BaseModel):
institution_id: str
organization_name: str
project_count: int
matched_project_count: int
topics: list[DfgProjectTopic]
class TopAuthor(BaseModel):
id: str | None = None
name: str
@@ -28,6 +69,7 @@ class TopAuthorStatistics(BaseModel):
institution_id: str
works: list[TopAuthor]
projects: list[TopAuthor]
eu_projects: list[TopAuthor]
patents: list[TopAuthor]
news: list[TopAuthor]
@@ -38,11 +80,27 @@ class TopicHeatmapValue(BaseModel):
share: float
class TopicHeatmapTopic(BaseModel):
id: str
name: str
total: int
values: list[TopicHeatmapValue]
class TopicHeatmapSubfield(BaseModel):
id: str
name: str
total: int
values: list[TopicHeatmapValue]
topics: list[TopicHeatmapTopic]
class TopicHeatmapField(BaseModel):
id: str
name: str
total: int
values: list[TopicHeatmapValue]
subfields: list[TopicHeatmapSubfield]
class TopicHeatmap(BaseModel):
@@ -50,3 +108,14 @@ class TopicHeatmap(BaseModel):
organization_name: str
years: list[int]
fields: list[TopicHeatmapField]
class TopicWordCloudWord(BaseModel):
id: str
name: str
count: int
class TopicWordCloud(BaseModel):
topic_id: str
words: list[TopicWordCloudWord]
+154
View File
@@ -9,21 +9,32 @@ from inse.database import get_session
from inse.tags import Tags
from .model import (
BmbfProjectStatusStatistics,
DashboardStatisticValue,
DashboardStatistics,
DfgProjectStatusStatistics,
DfgProjectTopics,
EuProjectStatusStatistics,
TopAuthorStatistics,
TopicHeatmap,
TopicWordCloud,
)
from .service import (
get_dashboard_bmbf_project_statuses,
get_dashboard_bmbf_projects,
get_dashboard_dfg_projects,
get_dashboard_dfg_project_statuses,
get_dashboard_dfg_topics,
get_dashboard_eu_projects,
get_dashboard_eu_project_statuses,
get_dashboard_organization,
get_dashboard_patents,
get_dashboard_persons,
get_dashboard_publications,
get_dashboard_statistics,
get_top_authors,
get_topic_heatmap,
get_topic_word_cloud,
)
router = APIRouter(prefix="/api/dashboard", tags=[Tags.DASHBOARD])
@@ -51,6 +62,8 @@ async def dashboard_statistics(
response_model=DashboardStatisticValue,
)
async def dashboard_publications(
from_year: int | None = Query(default=None, ge=1900, le=2100),
to_year: int | None = Query(default=None, ge=1900, le=2100),
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> DashboardStatisticValue:
@@ -58,6 +71,8 @@ async def dashboard_publications(
return await get_dashboard_publications(
organization.openalex_institution_id,
organization.name,
from_year=from_year,
to_year=to_year,
)
@@ -77,12 +92,34 @@ async def dashboard_persons(
)
@router.get(
"/statistics/patents",
operation_id="getDashboardPatents",
response_model=DashboardStatisticValue,
)
async def dashboard_patents(
from_year: int | None = Query(default=None, ge=1900, le=2100),
to_year: int | None = Query(default=None, ge=1900, le=2100),
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> DashboardStatisticValue:
organization = get_dashboard_organization(session, access_token)
return await get_dashboard_patents(
organization.openalex_institution_id,
organization.name,
from_year=from_year,
to_year=to_year,
)
@router.get(
"/statistics/projects/eu",
operation_id="getDashboardEuProjects",
response_model=DashboardStatisticValue,
)
async def dashboard_eu_projects(
from_year: int | None = Query(default=None, ge=1900, le=2100),
to_year: int | None = Query(default=None, ge=1900, le=2100),
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> DashboardStatisticValue:
@@ -90,6 +127,28 @@ async def dashboard_eu_projects(
return await get_dashboard_eu_projects(
organization.openalex_institution_id,
organization.name,
from_year=from_year,
to_year=to_year,
)
@router.get(
"/projects/eu/status",
operation_id="getDashboardEuProjectStatuses",
response_model=EuProjectStatusStatistics,
)
async def dashboard_eu_project_statuses(
from_year: int | None = Query(default=None, ge=1900, le=2100),
to_year: int | None = Query(default=None, ge=1900, le=2100),
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> EuProjectStatusStatistics:
organization = get_dashboard_organization(session, access_token)
return await get_dashboard_eu_project_statuses(
organization.openalex_institution_id,
organization.name,
from_year=from_year,
to_year=to_year,
)
@@ -99,6 +158,8 @@ async def dashboard_eu_projects(
response_model=DashboardStatisticValue,
)
async def dashboard_bmbf_projects(
from_year: int | None = Query(default=None, ge=1900, le=2100),
to_year: int | None = Query(default=None, ge=1900, le=2100),
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> DashboardStatisticValue:
@@ -106,6 +167,28 @@ async def dashboard_bmbf_projects(
return await get_dashboard_bmbf_projects(
organization.openalex_institution_id,
organization.name,
from_year=from_year,
to_year=to_year,
)
@router.get(
"/projects/bmbf/status",
operation_id="getDashboardBmbfProjectStatuses",
response_model=BmbfProjectStatusStatistics,
)
async def dashboard_bmbf_project_statuses(
from_year: int | None = Query(default=None, ge=1900, le=2100),
to_year: int | None = Query(default=None, ge=1900, le=2100),
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> BmbfProjectStatusStatistics:
organization = get_dashboard_organization(session, access_token)
return await get_dashboard_bmbf_project_statuses(
organization.openalex_institution_id,
organization.name,
from_year=from_year,
to_year=to_year,
)
@@ -115,6 +198,8 @@ async def dashboard_bmbf_projects(
response_model=DashboardStatisticValue,
)
async def dashboard_dfg_projects(
from_year: int | None = Query(default=None, ge=1900, le=2100),
to_year: int | None = Query(default=None, ge=1900, le=2100),
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> DashboardStatisticValue:
@@ -122,6 +207,48 @@ async def dashboard_dfg_projects(
return await get_dashboard_dfg_projects(
organization.openalex_institution_id,
organization.name,
from_year=from_year,
to_year=to_year,
)
@router.get(
"/projects/dfg/status",
operation_id="getDashboardDfgProjectStatuses",
response_model=DfgProjectStatusStatistics,
)
async def dashboard_dfg_project_statuses(
from_year: int | None = Query(default=None, ge=1900, le=2100),
to_year: int | None = Query(default=None, ge=1900, le=2100),
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> DfgProjectStatusStatistics:
organization = get_dashboard_organization(session, access_token)
return await get_dashboard_dfg_project_statuses(
organization.openalex_institution_id,
organization.name,
from_year=from_year,
to_year=to_year,
)
@router.get(
"/projects/dfg/topics",
operation_id="getDashboardDfgProjectTopics",
response_model=DfgProjectTopics,
)
async def dashboard_dfg_project_topics(
from_year: int | None = Query(default=None, ge=1900, le=2100),
to_year: int | None = Query(default=None, ge=1900, le=2100),
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> DfgProjectTopics:
organization = get_dashboard_organization(session, access_token)
return await get_dashboard_dfg_topics(
organization.openalex_institution_id,
organization.name,
from_year=from_year,
to_year=to_year,
)
@@ -135,6 +262,8 @@ async def dashboard_top_authors(
default="all_time",
pattern="^(all_time|last_5_years)$",
),
from_year: int | None = Query(default=None, ge=1900, le=2100),
to_year: int | None = Query(default=None, ge=1900, le=2100),
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> TopAuthorStatistics:
@@ -143,6 +272,8 @@ async def dashboard_top_authors(
organization.openalex_institution_id,
organization.name,
works_period=works_period,
from_year=from_year,
to_year=to_year,
)
@@ -166,3 +297,26 @@ async def dashboard_topic_heatmap(
to_year=to_year,
limit=limit,
)
@router.get(
"/topic-wordcloud",
operation_id="getDashboardTopicWordCloud",
response_model=TopicWordCloud,
)
async def dashboard_topic_word_cloud(
topic_id: str = Query(alias="topicId", min_length=1),
from_year: int | None = Query(default=None, ge=1900, le=2100),
to_year: int | None = Query(default=None, ge=1900, le=2100),
limit: int = Query(default=30, ge=1, le=100),
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> TopicWordCloud:
organization = get_dashboard_organization(session, access_token)
return await get_topic_word_cloud(
institution_id=organization.openalex_institution_id,
topic_id=topic_id,
from_year=from_year,
to_year=to_year,
limit=limit,
)
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,40 @@
from unittest.mock import AsyncMock, patch
import pytest
from inse.dashboard.institute_helper import get_openalex_institution
from inse.models.openalex.institution import Institution
@pytest.fixture
def anyio_backend():
return "asyncio"
@pytest.mark.anyio
@pytest.mark.parametrize(
"institution_id",
["I62318514", "https://openalex.org/I62318514"],
)
async def test_get_openalex_institution_accepts_short_and_full_id(
institution_id: str,
):
institution = Institution(
id="https://openalex.org/I62318514",
display_name="University of Duisburg-Essen",
display_name_alternatives=["Universität Duisburg-Essen"],
)
with patch(
"inse.dashboard.institute_helper.elasticsearch.search",
new=AsyncMock(
return_value={"hits": {"hits": [{"_source": institution.to_dict()}]}}
),
) as search:
result = await get_openalex_institution(institution_id)
assert result == institution
search.assert_awaited_once_with(
index="openalex-institutions",
query={"term": {"id": "https://openalex.org/I62318514"}},
size=1,
)
+546 -120
View File
@@ -1,5 +1,6 @@
from unittest.mock import AsyncMock, patch
from datetime import datetime
from types import SimpleNamespace
import pytest
from fastapi import HTTPException
@@ -8,12 +9,15 @@ from sqlmodel import Session, SQLModel, create_engine
from inse import config
from inse.auth.model import AccessToken, Organization, UserRole
from inse.dashboard.service import (
_openalex_work_authors_by_eu_projects,
get_dashboard_organization,
get_dashboard_statistics,
get_top_authors,
get_topic_heatmap,
get_topic_word_cloud,
)
from inse.model import ESCluster, ESIndex
from inse.models.openalex.institution import Institution
ORG_INSTITUTION_ID = "https://openalex.org/I123"
@@ -27,14 +31,42 @@ def anyio_backend():
async def test_dashboard_statistics_counts_organization_data_and_all_projects():
async def search(**kwargs):
index = kwargs["index"]
if index == config.settings.openalex_works_search_index:
return {"hits": {"total": {"value": 120}}}
if index == ESIndex.OPENALEX_AUTHORS:
return {"hits": {"total": {"value": 35}}}
if index == ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD:
return {"aggregations": {"projects": {"value": 10}}}
if index == ESIndex.PROJECTS_BUND_V1:
return {"hits": {"total": {"value": 5}}}
if index == ESIndex.DFG_INSTITUTES_V2:
if "institute_ids" in kwargs["body"].get("aggs", {}):
return {
"aggregations": {
"institute_ids": {"buckets": [{"key": 10210}]}
}
}
return {
"aggregations": {
"projects_nested": {
"project_ids": {
"values": {
"buckets": [
{"key": 101},
{"key": 102},
{"key": 103},
]
}
}
}
}
}
return {"hits": {"total": {"value": 3}}}
with patch(
@@ -43,8 +75,20 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
) as mocked_search, patch(
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
new=AsyncMock(return_value=["Example University", "Example Uni"]),
), patch(
"inse.dashboard.service.get_openalex_institution",
new=AsyncMock(
return_value=Institution(
id=ORG_INSTITUTION_ID,
display_name="Example University",
display_name_alternatives=["Example Universität"],
)
),
):
result = await get_dashboard_statistics(ORG_INSTITUTION_ID, "Example Org")
result = await get_dashboard_statistics(
ORG_INSTITUTION_ID,
"Example Org",
)
assert result.model_dump() == {
"institution_id": ORG_INSTITUTION_ID,
@@ -56,21 +100,35 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
"eu_projects": 10,
"bmbf_projects": 5,
}
calls = mocked_search.await_args_list
assert calls[0].kwargs["index"] == config.settings.openalex_works_search_index
assert calls[0].kwargs["query"]["nested"]["query"]["term"] == {
publication_call = next(
call
for call in mocked_search.await_args_list
if call.kwargs["index"] == config.settings.openalex_works_search_index
)
assert publication_call.kwargs["query"]["nested"]["query"]["term"] == {
"authorships.institutions.id": ORG_INSTITUTION_ID
}
assert calls[1].kwargs["query"]["nested"]["query"]["term"] == {
"affiliations.institution.id": ORG_INSTITUTION_ID
person_call = next(
call
for call in mocked_search.await_args_list
if call.kwargs["index"] == ESIndex.OPENALEX_AUTHORS
)
person_query = person_call.kwargs["query"]
recent_affiliation = person_query["bool"]["should"][0]["bool"]["filter"][1]
assert recent_affiliation["nested"]["path"] == "affiliations"
assert recent_affiliation["nested"]["query"]["bool"]["filter"][0] == {
"term": {"affiliations.institution.id": ORG_INSTITUTION_ID}
}
assert all(call.kwargs["cluster"] == ESCluster.INSE for call in calls[2:])
assert [call.kwargs["index"] for call in calls[2:]] == [
ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD,
ESIndex.PROJECTS_BUND_V1,
ESIndex.PROJECTS_DFG_ALL,
]
assert calls[2].kwargs["body"]["query"] == {
eu_call = next(
call
for call in mocked_search.await_args_list
if call.kwargs["index"] == ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD
)
assert eu_call.kwargs["cluster"] == ESCluster.INSE
assert eu_call.kwargs["body"]["query"] == {
"terms": {
"name.keyword": [
"EXAMPLE ORG",
@@ -79,26 +137,32 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
]
}
}
assert calls[3].kwargs["query"]["bool"]["minimum_should_match"] == 1
assert calls[3].kwargs["query"]["bool"]["should"][0]["match"] == {
bund_call = next(
call
for call in mocked_search.await_args_list
if call.kwargs["index"] == ESIndex.PROJECTS_BUND_V1
)
assert bund_call.kwargs["cluster"] == ESCluster.INSE
assert bund_call.kwargs["query"]["bool"]["minimum_should_match"] == 1
assert bund_call.kwargs["query"]["bool"]["should"][0]["match"] == {
"Zuwendungsempfänger": {
"query": "Example Org",
"operator": "and",
}
}
assert calls[4].kwargs["query"]["bool"]["minimum_should_match"] == 1
assert calls[4].kwargs["query"]["bool"]["should"][0]["bool"]["should"][0][
"match"
] == {
"Antragstellende Institution": {
"query": "Example Org",
"operator": "and",
}
}
dfg_calls = [
call
for call in mocked_search.await_args_list
if call.kwargs["index"] == ESIndex.DFG_INSTITUTES_V2
]
assert len(dfg_calls) == 2
assert all(call.kwargs["cluster"] == ESCluster.INSE for call in dfg_calls)
@pytest.mark.anyio
async def test_top_authors_maps_works_and_dfg_project_aggregations():
async def test_top_authors_maps_works_patents_news_and_eu_projects():
async def search(**kwargs):
if kwargs["index"] == ESIndex.OPENALEX_AUTHORS:
return {
@@ -123,15 +187,38 @@ async def test_top_authors_maps_works_and_dfg_project_aggregations():
]
}
}
if kwargs["index"] == "aktuell_postproc":
return {
"aggregations": {
"authors": {
"buckets": [{"key": "Ada Example", "doc_count": 6}]
"buckets": [
{"key": "Ada Example", "doc_count": 6}
]
}
}
}
if kwargs["index"] == ESIndex.PROJECTS_DFG_ALL:
if kwargs["index"] == ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD:
return {
"hits": {
"hits": [
{
"_source": {
"projectID": "P1",
"qaProcessedDoi": "10.1234/p1",
}
},
{
"_source": {
"projectID": "P2",
"qaProcessedDoi": "https://doi.org/10.1234/p2",
}
},
]
}
}
if kwargs["index"] == ESIndex.DFG_PROJECTS:
return {
"aggregations": {
"people": {
@@ -139,6 +226,50 @@ async def test_top_authors_maps_works_and_dfg_project_aggregations():
}
}
}
if kwargs["index"] == "openalex-works":
return {
"hits": {
"hits": [
{
"_source": {
"doi": "https://doi.org/10.1234/p1",
"authorships": [
{
"author": {
"id": "https://openalex.org/A2",
"display_name": "Grace Example",
},
"institutions": [{"id": ORG_INSTITUTION_ID}],
},
{
"author": {
"id": "https://openalex.org/A1",
"display_name": "Ada Example",
},
"institutions": [{"id": ORG_INSTITUTION_ID}],
},
],
}
},
{
"_source": {
"doi": "https://doi.org/10.1234/p2",
"authorships": [
{
"author": {
"id": "https://openalex.org/A2",
"display_name": "Grace Example",
},
"institutions": [{"id": ORG_INSTITUTION_ID}],
}
],
}
},
]
}
}
return {"aggregations": {"people": {"buckets": []}}}
with patch(
@@ -147,6 +278,17 @@ async def test_top_authors_maps_works_and_dfg_project_aggregations():
) as mocked_search, patch(
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
new=AsyncMock(return_value=["Example University"]),
), patch(
"inse.dashboard.service.get_eu_organization_project_contributions",
new=AsyncMock(
return_value=SimpleNamespace(
elements=[
SimpleNamespace(project_id="P1"),
SimpleNamespace(project_id="P2"),
SimpleNamespace(project_id="P3"),
],
)
),
), patch(
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
new=AsyncMock(
@@ -155,115 +297,135 @@ async def test_top_authors_maps_works_and_dfg_project_aggregations():
]
),
):
result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org")
result = await get_top_authors(
ORG_INSTITUTION_ID,
"Example Org",
)
assert result.works[0].model_dump() == {
"id": "A1",
"name": "Ada Example",
"count": 42,
}
assert result.projects[0].model_dump() == {
"id": "A2",
"name": "Grace Example",
"count": 3,
}
assert result.patents[0].model_dump() == {
"id": "A1",
"name": "Ada Example",
"count": 4,
}
assert [author.model_dump() for author in result.eu_projects] == [
{"id": "A2", "name": "Grace Example", "count": 2},
{"id": "A1", "name": "Ada Example", "count": 1},
]
assert result.news[0].model_dump() == {
"id": "A1",
"name": "Ada Example",
"count": 6,
}
project_calls = [
call
for call in mocked_search.await_args_list
if call.kwargs["index"]
in {ESIndex.PROJECTS_DFG_ALL, ESIndex.PROJECTS_BUND_V1}
in {ESIndex.DFG_PROJECTS, ESIndex.PROJECTS_BUND_V1}
]
assert project_calls == []
eu_calls = [
call
for call in mocked_search.await_args_list
if call.kwargs["index"] == ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD
]
assert len(eu_calls) == 1
eu_body = eu_calls[0].kwargs["body"]
assert set(eu_body["query"]["terms"]["projectID"]) == {
"P1",
"P2",
"P3",
}
assert eu_body["_source"] == ["projectID", "qaProcessedDoi"]
assert "aggs" not in eu_body
works_calls = [
call
for call in mocked_search.await_args_list
if call.kwargs["index"] == "openalex-works"
]
assert len(works_calls) == 1
works_body = works_calls[0].kwargs["body"]
assert works_body["query"]["bool"]["filter"][0]["terms"]["doi"] == [
"https://doi.org/10.1234/p1",
"https://doi.org/10.1234/p2",
]
assert works_body["_source"] == [
"doi",
"authorships.author.id",
"authorships.author.display_name",
"authorships.institutions.id",
]
assert len(project_calls) == 1
assert project_calls[0].kwargs["index"] == ESIndex.PROJECTS_DFG_ALL
assert project_calls[0].kwargs["body"]["query"]["bool"][
"minimum_should_match"
] == 1
assert "Beteiligte Personen" in project_calls[0].kwargs["body"]["aggs"][
"people"
]["terms"]["script"]["source"]
@pytest.mark.anyio
async def test_top_authors_keeps_dfg_project_authors_without_openalex_match():
async def search(**kwargs):
if kwargs["index"] == ESIndex.OPENALEX_AUTHORS:
return {"hits": {"hits": []}}
if kwargs["index"] == ESIndex.PROJECTS_DFG_ALL:
return {
"aggregations": {
"people": {
"buckets": [{"key": "Project Person", "doc_count": 9}]
def test_eu_author_count_groups_multiple_publications_by_project_id():
works_response = {
"hits": {
"hits": [
{
"_source": {
"doi": "https://doi.org/10.1/marcus-a",
"authorships": [
{
"author": {
"id": "https://openalex.org/A5007170803",
"display_name": "Marcus Example",
},
"institutions": [{"id": ORG_INSTITUTION_ID}],
},
{
"author": {
"id": "https://openalex.org/A999",
"display_name": "External Example",
},
"institutions": [{"id": ORG_INSTITUTION_ID}],
},
],
}
}
}
return {"aggregations": {"people": {"buckets": []}}}
with patch(
"inse.dashboard.service.elasticsearch.search",
new=AsyncMock(side_effect=search),
), patch(
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
new=AsyncMock(return_value=["Example University"]),
), patch(
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
new=AsyncMock(return_value=[]),
):
result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org")
assert result.projects[0].model_dump() == {
"id": None,
"name": "Project Person",
"count": 9,
},
{
"_source": {
"doi": "https://doi.org/10.1/marcus-b",
"authorships": [
{
"author": {
"id": "https://openalex.org/A5007170803",
"display_name": "Marcus Example",
},
"institutions": [{"id": ORG_INSTITUTION_ID}],
}
],
}
},
]
}
}
doi_project_ids = {
"https://doi.org/10.1/marcus-a": {"P1"},
"https://doi.org/10.1/marcus-b": {"P1"},
}
result = _openalex_work_authors_by_eu_projects(
works_response,
doi_project_ids,
ORG_INSTITUTION_ID,
{"https://openalex.org/A5007170803"},
)
@pytest.mark.anyio
async def test_top_authors_returns_top_ten_dfg_project_people_by_project_count():
async def search(**kwargs):
if kwargs["index"] == ESIndex.OPENALEX_AUTHORS:
return {"hits": {"hits": []}}
if kwargs["index"] == ESIndex.PROJECTS_DFG_ALL:
return {
"aggregations": {
"people": {
"buckets": [
{"key": f"Project Person {count}", "doc_count": count}
for count in range(1, 12)
]
}
}
}
return {"aggregations": {"people": {"buckets": []}}}
with patch(
"inse.dashboard.service.elasticsearch.search",
new=AsyncMock(side_effect=search),
), patch(
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
new=AsyncMock(return_value=["Example University"]),
), patch(
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
new=AsyncMock(return_value=[]),
):
result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org")
assert [author.count for author in result.projects] == list(range(11, 1, -1))
assert result.projects[0].name == "Project Person 11"
assert len(result.projects) == 10
assert [author.model_dump() for author in result] == [
{"id": "A5007170803", "name": "Marcus Example", "count": 1}
]
@pytest.mark.anyio
async def test_top_authors_combines_dfg_involved_people_case_insensitively():
async def test_top_eu_project_authors_count_filtered_projects_by_stable_author_id():
async def search(**kwargs):
if kwargs["index"] == ESIndex.OPENALEX_AUTHORS:
return {
@@ -273,14 +435,131 @@ async def test_top_authors_combines_dfg_involved_people_case_insensitively():
"_source": {
"id": "https://openalex.org/A1",
"display_name": "Ada Example",
"works_count": 3,
"counts_by_year": [],
}
},
{
"_source": {
"id": "https://openalex.org/A2",
"display_name": "Grace Example",
"works_count": 1,
"counts_by_year": [],
}
}
},
]
}
}
if kwargs["index"] == ESIndex.PROJECTS_DFG_ALL:
if kwargs["index"] == ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD:
assert kwargs["body"]["query"] == {
"terms": {"projectID": ["P1", "P2"]}
}
return {
"hits": {
"hits": [
{
"_source": {
"projectID": "P1",
"qaProcessedDoi": "10.1/P1-A",
}
},
{
"_source": {
"projectID": "P1",
"qaProcessedDoi": "10.1/P1-B",
}
},
{
"_source": {
"projectID": "P2",
"qaProcessedDoi": "10.1/P2",
}
},
{
"_source": {
"projectID": "OUTSIDE",
"qaProcessedDoi": "10.1/OUT",
}
},
]
}
}
if kwargs["index"] == "openalex-works":
assert kwargs["body"]["query"]["bool"]["filter"][0]["terms"]["doi"] == [
"https://doi.org/10.1/p1-a",
"https://doi.org/10.1/p1-b",
"https://doi.org/10.1/p2",
]
return {
"hits": {
"hits": [
{
"_source": {
"doi": "https://doi.org/10.1/p1-a",
"authorships": [
{
"author": {
"id": "https://openalex.org/A1",
"display_name": "Ada Example",
},
"institutions": [{"id": ORG_INSTITUTION_ID}],
},
{
"author": {
"id": "https://openalex.org/A2",
"display_name": "Grace Example",
},
"institutions": [{"id": ORG_INSTITUTION_ID}],
},
],
}
},
{
"_source": {
"doi": "https://doi.org/10.1/p1-b",
"authorships": [
{
"author": {
"id": "https://openalex.org/A1",
"display_name": "Ada Example",
},
"institutions": [{"id": ORG_INSTITUTION_ID}],
}
],
}
},
{
"_source": {
"doi": "https://doi.org/10.1/p2",
"authorships": [
{
"author": {
"id": "https://openalex.org/A1",
"display_name": "Ada Example",
},
"institutions": [{"id": ORG_INSTITUTION_ID}],
}
],
}
},
{
"_source": {
"doi": "https://doi.org/10.1/not-requested",
"authorships": [
{
"author": {
"id": "https://openalex.org/A999",
"display_name": "Outside Author",
}
}
],
}
},
]
}
}
if kwargs["index"] == ESIndex.DFG_PROJECTS:
return {
"aggregations": {
"people": {
@@ -300,15 +579,28 @@ async def test_top_authors_combines_dfg_involved_people_case_insensitively():
), patch(
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
new=AsyncMock(return_value=["Example University"]),
), patch(
"inse.dashboard.service.get_eu_organization_project_contributions",
new=AsyncMock(
return_value=SimpleNamespace(
elements=[
SimpleNamespace(project_id="P1"),
SimpleNamespace(project_id="P2"),
],
)
),
), patch(
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
new=AsyncMock(return_value=[]),
):
result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org")
result = await get_top_authors(
ORG_INSTITUTION_ID,
"Example Org",
)
assert [author.model_dump() for author in result.projects] == [
{"id": "A1", "name": "Ada Example", "count": 5},
{"id": None, "name": "DFG Person", "count": 4},
assert [author.model_dump() for author in result.eu_projects] == [
{"id": "A1", "name": "Ada Example", "count": 2},
{"id": "A2", "name": "Grace Example", "count": 1},
]
@@ -330,6 +622,7 @@ async def test_top_authors_returns_partial_response_when_one_source_fails():
]
}
}
raise RuntimeError("projects unavailable")
with patch(
@@ -338,14 +631,26 @@ async def test_top_authors_returns_partial_response_when_one_source_fails():
), patch(
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
new=AsyncMock(return_value=["Example University"]),
), patch(
"inse.dashboard.service.get_eu_organization_project_contributions",
new=AsyncMock(
return_value=SimpleNamespace(
elements=[
SimpleNamespace(project_id="P1"),
],
)
),
), patch(
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
new=AsyncMock(return_value=[]),
):
result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org")
result = await get_top_authors(
ORG_INSTITUTION_ID,
"Example Org",
)
assert result.works[0].name == "Ada Example"
assert result.projects == []
assert result.eu_projects == []
assert result.patents == []
assert result.news == []
@@ -392,6 +697,9 @@ async def test_top_authors_can_rank_works_by_last_five_years():
), patch(
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
new=AsyncMock(return_value=["Example University"]),
), patch(
"inse.dashboard.service.get_eu_organization_project_contributions",
new=AsyncMock(return_value=SimpleNamespace(elements=[])),
), patch(
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
new=AsyncMock(return_value=[]),
@@ -448,6 +756,42 @@ async def test_topic_heatmap_maps_field_year_counts_and_shares():
]
},
},
"subfields": {
"buckets": [
{
"key": "https://openalex.org/subfields/1702",
"subfield_name": {
"buckets": [
{
"key": "Artificial Intelligence",
"doc_count": 7,
}
]
},
"works": {
"doc_count": 7,
},
"topics": {
"buckets": [
{
"key": "https://openalex.org/T100",
"topic_name": {
"buckets": [
{
"key": "Machine learning",
"doc_count": 6,
}
]
},
"works": {
"doc_count": 6,
},
}
]
},
}
]
},
}
]
}
@@ -490,6 +834,22 @@ async def test_topic_heatmap_maps_field_year_counts_and_shares():
{"year": 2023, "count": 4, "share": 0.4},
{"year": 2024, "count": 8, "share": 0.4},
],
"subfields": [
{
"id": "https://openalex.org/subfields/1702",
"name": "Artificial Intelligence",
"total": 7,
"values": [],
"topics": [
{
"id": "https://openalex.org/T100",
"name": "Machine learning",
"total": 6,
"values": [],
}
],
}
],
}
body = mocked_search.await_args_list[0].kwargs["body"]
assert body["query"]["bool"]["must"][0]["nested"]["query"]["term"] == {
@@ -499,10 +859,28 @@ async def test_topic_heatmap_maps_field_year_counts_and_shares():
body["aggs"]["topics_nested"]["aggs"]["fields"]["terms"]["field"]
== "topics.field.id"
)
assert (
body["aggs"]["topics_nested"]["aggs"]["fields"]["aggs"]["subfields"]["terms"][
"field"
]
== "topics.subfield.id"
)
assert (
body["aggs"]["topics_nested"]["aggs"]["fields"]["aggs"]["subfields"][
"aggs"
]["topics"]["terms"]["field"]
== "topics.id"
)
subfield_aggs = body["aggs"]["topics_nested"]["aggs"]["fields"]["aggs"]
assert "aggs" not in subfield_aggs["subfields"]["aggs"]["works"]
assert (
"aggs"
not in subfield_aggs["subfields"]["aggs"]["topics"]["aggs"]["works"]
)
@pytest.mark.anyio
async def test_topic_heatmap_defaults_to_last_five_years():
async def test_topic_heatmap_defaults_to_all_time():
async def search(**kwargs):
if kwargs["index"] == config.settings.openalex_works_search_index:
return {
@@ -522,13 +900,61 @@ async def test_topic_heatmap_defaults_to_last_five_years():
organization_name="Example Org",
)
current_year = datetime.now().year
assert result.years == list(range(current_year - 4, current_year + 1))
assert result.years == []
body = mocked_search.await_args_list[0].kwargs["body"]
assert body["query"]["bool"]["filter"][0]["range"]["publication_year"] == {
"gte": current_year - 4,
"lte": current_year,
assert body["query"]["bool"]["filter"] == []
@pytest.mark.anyio
async def test_topic_word_cloud_maps_related_topics_and_excludes_selected_topic():
response = {
"aggregations": {
"topics_nested": {
"topics": {
"buckets": [
{
"key": "https://openalex.org/T100",
"topic_name": {"buckets": [{"key": "Selected topic"}]},
"works": {"doc_count": 9},
},
{
"key": "https://openalex.org/T200",
"topic_name": {"buckets": [{"key": "Related topic"}]},
"works": {"doc_count": 6},
},
]
}
}
}
}
with patch(
"inse.dashboard.service.elasticsearch.search",
new=AsyncMock(return_value=response),
) as mocked_search:
result = await get_topic_word_cloud(
institution_id=ORG_INSTITUTION_ID,
topic_id="https://openalex.org/T100",
from_year=2023,
to_year=2024,
)
assert result.model_dump() == {
"topic_id": "https://openalex.org/T100",
"words": [
{
"id": "https://openalex.org/T200",
"name": "Related topic",
"count": 6,
}
],
}
body = mocked_search.await_args.kwargs["body"]
assert body["query"]["bool"]["must"][1]["nested"]["query"]["term"] == {
"topics.id": "https://openalex.org/T100"
}
assert body["query"]["bool"]["filter"] == [
{"range": {"publication_year": {"gte": 2023, "lte": 2024}}}
]
def test_get_dashboard_organization_uses_effective_organization():
+1 -1
View File
@@ -2,7 +2,7 @@ from typing import Annotated
from fastapi import Depends
from sqlalchemy import inspect, text
from sqlmodel import SQLModel, Session, create_engine
from sqlmodel import Session, SQLModel, create_engine
from inse import config
@@ -157,49 +157,6 @@ class InstitutionsSearchClient:
total=total,
)
async def get_authors_by_institution_id(self, raw_institution_id: str) -> List[str]:
"""
Fetches authors associated with an institution.
Note: This query is specifically looking for current affiliations (2026).
"""
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,
)
res = await elasticsearch.search(index="openalex-authors", query=query)
hits = res.get("hits", {}).get("hits", [])
# Extracting display_name directly from the author document source
authors = {
hit["_source"].get("display_name")
for hit in hits
if hit["_source"].get("display_name")
}
return list(authors)
async def search_institutions(
self,
query_text: str,
@@ -0,0 +1,7 @@
from inse.model import Page
from inse.models.openalex.institution import Institution
class InstitutionPageV2(Page[Institution]):
"""A paginated response containing a list of institutions."""
@@ -0,0 +1,73 @@
import logging
from typing import Annotated
import inse.institutions.v2.service as institutions_service
from fastapi import APIRouter, Path, Query
from inse.institutions.v2.model import InstitutionPageV2
from inse.models.openalex.institution import Institution
from inse.router_prefixes import RouterPrefixes
from inse.tags import Tags
logger = logging.getLogger(__name__)
router = APIRouter(prefix=RouterPrefixes.INSTITUTIONS_V2, tags=[Tags.INSTITUTIONS_V2])
@router.get(
"/single/{institution_id}",
operation_id="getInstitutionById2",
summary="Returns an institution based on its ID.",
)
async def get_institution_by_id(
institution_id: Annotated[
str,
Path(description="The ID of the institution to retrieve."),
],
) -> Institution:
return await institutions_service.get_institution_by_id_or_raise(
raw_oa_institution_id=institution_id,
source=[
"id",
"display_name",
"display_name_alternatives",
"works_count",
"cited_by_count",
"geo",
"summary_stats",
],
)
@router.get(
"/multiple/ids",
operation_id="getInstitutionsByIds",
summary="Returns a list of institutions based on their IDs.",
)
async def get_institutions_by_ids(
institution_ids: Annotated[
list[str] | None,
Query(description="A list of institution IDs to retrieve."),
] = None,
) -> InstitutionPageV2:
return await institutions_service.get_institutions_by_ids(
institution_ids=institution_ids or []
)
@router.get(
"/autocomplete/selector",
operation_id="getInstitutionAutocompleteForSelector",
summary="Returns a list of institutions based on a search term for autocomplete functionality.",
)
async def get_institution_autocomplete(
query: Annotated[
str,
Query(
description="A search term to filter institutions by (partial matches allowed)."
),
] = "",
) -> InstitutionPageV2:
return await institutions_service.autocomplete_institutions_for_selector(
query=query
)
@@ -0,0 +1,185 @@
import logging
from inse.exceptions import NotFoundException
from inse.institutions.v2.model import InstitutionPageV2
from inse.integrations import elasticsearch
from inse.model import ESIndex
from inse.models.openalex.institution import Institution
logger = logging.getLogger(__name__)
async def get_institution_by_id(
raw_oa_institution_id: str, source: list[str] | None = None
) -> Institution | None:
"""Retrieves an institution by its ID from the OpenAlex Elasticsearch index.
Args:
raw_oa_institution_id (str): The raw OpenAlex ID of the institution to retrieve.
source (Optional[List[str]], optional): A list of fields to include in the response. Defaults to None.
Returns:
Institution | None: The institution object if found, otherwise None.
"""
response = await elasticsearch.get(
index=ESIndex.OPENALEX_INSTITUTIONS, doc_id=raw_oa_institution_id, source=source
)
if not response.get("found"):
return None
return Institution.from_dict(response.get("_source", {})) # type: ignore
async def get_institution_by_id_or_raise(
raw_oa_institution_id: str, source: list[str] | None = None
) -> Institution:
"""Retrieves an institution by its ID from the OpenAlex Elasticsearch index, raising an exception if not found.
Args:
raw_oa_institution_id (str): The raw OpenAlex ID of the institution to retrieve.
source (Optional[List[str]], optional): A list of fields to include in the response. Defaults to None.
Raises:
NotFoundException: If the institution is not found.
Returns:
Institution: The institution object if found.
"""
institution = await get_institution_by_id(
raw_oa_institution_id=raw_oa_institution_id, source=source
)
if institution is None:
raise NotFoundException(
f"Institution with ID {raw_oa_institution_id} not found."
)
return institution
async def search_institutions(
page: int = 0,
size: int = 10,
query: dict | None = None,
source: list[str] | None = None,
sort: list[dict] | None = None,
body: dict | None = None,
) -> InstitutionPageV2:
"""Searches for institutions in the OpenAlex Elasticsearch index based on the provided parameters.
Args:
page (int, optional): The page number to retrieve. Defaults to 0.
size (int, optional): The number of institutions to retrieve per page. Defaults to 10.
query (Optional[Dict], optional): The search query to filter institutions by. Defaults to None.
source (Optional[List[str]], optional): A list of fields to include in the response. Defaults to None.
sort (Optional[List[Dict]], optional): A list of sorting criteria. Defaults to None.
body (Optional[Dict], optional): The request body for the Elasticsearch search query. Defaults to None.
Returns:
InstitutionPageV2: A page of institutions matching the search criteria.
"""
response = await elasticsearch.search(
ESIndex.OPENALEX_INSTITUTIONS,
query=query,
source=source,
size=size,
offset=size * page,
sort=sort,
body=body,
)
hits_block = response.get("hits", {})
hits = hits_block.get("hits", [])
institutions: list[Institution] = []
for hit in hits:
_source = hit.get("_source", {})
institutions.append(Institution.from_dict(_source)) # type: ignore
return InstitutionPageV2(
elements=institutions, total=len(institutions), page=page, size=size
)
async def get_institutions_by_ids(institution_ids: list[str]) -> InstitutionPageV2:
"""Retrieves institutions based on a list of institution IDs.
Args:
institution_ids (List[str]): A list of institution IDs to retrieve.
Returns:
InstitutionPageV2: A page of institutions matching the provided IDs.
"""
logger.debug(f"Fetching institutions for IDs: {institution_ids}")
if not institution_ids:
return InstitutionPageV2(elements=[], total=0, page=0, size=0)
return await search_institutions(
page=0,
size=len(institution_ids),
query={"terms": {"id": institution_ids}},
source=[
"id",
"display_name",
"display_name_alternatives",
"country_code",
"type",
"ror",
],
)
async def autocomplete_institutions(
query: str, page: int = 0, size: int = 10, source: list[str] | None = None
) -> InstitutionPageV2:
"""Autocompletes institutions based on a search term.
Args:
query (str): The search term to autocomplete institutions with.
page (int, optional): The page number to retrieve. Defaults to 0.
size (int, optional): The number of institutions to retrieve per page. Defaults to 10.
source (Optional[List[str]], optional): A list of fields to include in the response. Defaults to None.
Returns:
InstitutionPageV2: A page of institutions matching the autocomplete criteria.
"""
logger.debug(f"Autocomplete institutions for query: {query}")
if not query:
return InstitutionPageV2(elements=[], total=0, page=0, size=0)
return await search_institutions(
page=page,
size=size,
query={
"bool": {
"should": [
{"match_phrase_prefix": {"display_name": query}},
{"match_phrase_prefix": {"display_name_alternatives": query}},
]
}
},
source=source,
)
async def autocomplete_institutions_for_selector(
query: str, page: int = 0, size: int = 10
) -> InstitutionPageV2:
"""Autocompletes institutions based on a search term for use in a selector component.
Args:
query (str): The search term to filter institutions by (partial matches allowed).
page (int, optional): The page number to retrieve. Defaults to 0.
size (int, optional): The number of institutions to retrieve per page. Defaults to 10.
Returns:
InstitutionPageV2: A page of institutions matching the autocomplete criteria.
"""
return await autocomplete_institutions(
query=query,
page=page,
size=size,
source=[
"id",
"display_name",
"display_name_alternatives",
"country_code",
"type",
"ror",
],
)
@@ -1,5 +1,6 @@
import json
import logging
import time
from typing import Any, Dict, AsyncIterator, List, Optional, Tuple
import httpx
@@ -100,13 +101,20 @@ def _index_to_cluster(index: ESIndex) -> Optional[ESCluster]:
ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD,
ESIndex.PROJECTS_BUND_V1,
ESIndex.PROJECTS_DFG_ALL,
ESIndex.DFG_PROJECTS,
ESIndex.DFG_PROJECTS_V2,
ESIndex.DFG_INSTITUTES_V2,
ESIndex.PROJECTS_DFG_OPENALEX_TOPICS,
}:
return ESCluster.INSE
else:
return None
def _headers(api_key: str, content_type: str = "application/json") -> Dict[str, str]:
return {"Authorization": f"ApiKey {api_key}", "Content-Type": content_type}
def _wrap_exception(e: Exception) -> Exception:
logger.exception(f"Elasticsearch raised an exception: {e}")
if isinstance(e, httpx.HTTPStatusError):
@@ -122,6 +130,63 @@ def _wrap_exception(e: Exception) -> Exception:
return ElasticsearchException(f"Unexpected Elasticsearch error: {e}")
async def _request(
method: str,
cluster: ESCluster,
path: str,
*,
json_body: Optional[Any] = None,
params: Optional[Dict[str, Any]] = None,
content: Optional[bytes] = None,
content_type: str = "application/json",
) -> httpx.Response:
"""Sends an authenticated request to cluster and returns the raw response.
Args:
method: The HTTP method (e.g. "GET", "POST", "PUT", "DELETE").
cluster: The Elasticsearch cluster to send the request to.
path: The path appended to the cluster URL (without leading slash).
json_body: Optional JSON-serialisable request body.
params: Optional query parameters.
content: Optional raw request body (e.g. ndjson); mutually exclusive with json_body.
content_type: The Content-Type header value.
Returns:
httpx.Response: The successful response (status already checked).
"""
elasticsearch_url, api_key = _cluster_credentials(cluster)
client = get_client()
start = time.perf_counter()
try:
response = await client.request(
method,
f"{elasticsearch_url}/{path}",
json=json_body,
params=params,
content=content,
headers=_headers(api_key, content_type=content_type),
)
response.raise_for_status()
if config.settings.print_es_timings:
elapsed_ms = (time.perf_counter() - start) * 1000
logger.debug(
f"Elasticsearch request {method} {path} on cluster '{cluster}' took {elapsed_ms:.1f} ms"
)
return response
except Exception as exc:
if config.settings.print_es_timings:
elapsed_ms = (time.perf_counter() - start) * 1000
logger.debug(
f"Elasticsearch request {method} {path} on cluster '{cluster}' failed after {elapsed_ms:.1f} ms"
)
raise _wrap_exception(exc) from exc
async def search(
index: ESIndex | List[ESIndex] | str | List[str],
query: Optional[Dict] = None,
@@ -129,6 +194,7 @@ async def search(
size: Optional[int] = None,
offset: Optional[int] = None,
sort: Optional[List] = None,
aggs: Optional[Dict] = None,
body: Optional[Dict] = None,
track_total_hits=False,
highlight: Optional[Dict] = None,
@@ -143,6 +209,7 @@ async def search(
size (Optional[int], optional): The maximum number of results to return. Defaults to None.
offset (Optional[int], optional): The number of results to skip. Defaults to None.
sort (Optional[List], optional): The fields to sort by. Defaults to None.
aggs (Optional[Dict], optional): The aggregations to include in the response. Defaults to None.
body (Optional[Dict], optional): The full query body. Defaults to None.
track_total_hits (bool, optional): Whether to track the total number of hits. Defaults to False.
cluster (ElasticsearchCluster, optional): The Elasticsearch cluster to search. Defaults to ElasticsearchCluster.NES.
@@ -170,25 +237,27 @@ async def search(
elif len(clusters) == 1:
cluster = clusters.pop()
elasticsearch_url, api_key = _cluster_credentials(cluster)
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
payload: Dict[str, Any] = {}
if body is not None:
payload = body
if payload.get("size") == 0 and "_source" not in payload:
payload["_source"] = False
else:
if query is not None:
payload["query"] = query
if source is not None:
payload["_source"] = source
elif size == 0:
payload["_source"] = False
if size is not None:
payload["size"] = size
if offset is not None:
payload["from"] = offset
if sort is not None:
payload["sort"] = sort
if aggs is not None:
payload["aggs"] = aggs
if track_total_hits:
payload["track_total_hits"] = True
if highlight is not None:
@@ -196,64 +265,37 @@ async def search(
if len(payload) == 0:
raise ValueError(
"At least one of 'query', 'body', 'source', 'size', 'offset', 'sort' must be provided"
"At least one of 'query', 'body', 'source', 'size', 'offset', 'sort', 'aggs' must be provided"
)
if config.settings.print_es_queries:
logger.debug(
f"Sending search request to Elasticsearch cluster '{cluster}' for {index} with payload: {json.dumps(payload)}"
)
client = get_client()
logger.debug(
f"Sending search request to Elasticsearch cluster '{cluster}' at {elasticsearch_url} for {index} with payload: {json.dumps(payload)}"
)
if isinstance(index, list):
index_str = ",".join(str(idx) for idx in index)
else:
index_str = str(index)
try:
response = await client.post(
f"{elasticsearch_url}/{index_str}/_search", json=payload, headers=headers
)
response.raise_for_status()
return response.json()
except Exception as exc:
raise _wrap_exception(exc) from exc
response = await _request("POST", cluster, f"{index_str}/_search", json_body=payload)
return response.json()
async def open_point_in_time(
index: str, keep_alive: str = "1m", cluster: str = "nes"
) -> str:
"""Opens a point-in-time on the given index and returns its id."""
elasticsearch_url, api_key = _cluster_credentials(cluster)
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
response = await _request("POST", cluster, f"{index}/_pit", params={"keep_alive": keep_alive})
client = get_client()
try:
response = await client.post(
f"{elasticsearch_url}/{index}/_pit",
params={"keep_alive": keep_alive},
headers=headers,
)
response.raise_for_status()
return response.json()["id"]
except Exception as exc:
raise _wrap_exception(exc) from exc
return response.json()["id"]
async def close_point_in_time(pit_id: str, cluster: str = "nes") -> None:
"""Closes a previously opened point-in-time."""
elasticsearch_url, api_key = _cluster_credentials(cluster)
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
client = get_client()
try:
response = await client.request(
"DELETE",
f"{elasticsearch_url}/_pit",
json={"id": pit_id},
headers=headers,
)
response.raise_for_status()
except Exception as exc:
raise _wrap_exception(exc) from exc
await _request("DELETE", cluster, "_pit", json_body={"id": pit_id})
async def scan(
@@ -269,13 +311,9 @@ async def scan(
Unlike ``from``/``size`` pagination, this is not bounded by
``index.max_result_window``, so it can stream result sets larger than 10k.
"""
elasticsearch_url, api_key = _cluster_credentials(cluster)
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
pit_id = await open_point_in_time(index, keep_alive=keep_alive, cluster=cluster)
search_after: Optional[List] = None
try:
client = get_client()
while True:
payload: Dict[str, Any] = {
"size": page_size,
@@ -283,20 +321,12 @@ async def scan(
"pit": {"id": pit_id, "keep_alive": keep_alive},
"sort": [{"_shard_doc": "asc"}],
"track_total_hits": False,
"_source": source if source is not None else False,
}
if source is not None:
payload["_source"] = source
if search_after is not None:
payload["search_after"] = search_after
try:
response = await client.post(
f"{elasticsearch_url}/_search", json=payload, headers=headers
)
response.raise_for_status()
except Exception as exc:
raise _wrap_exception(exc) from exc
response = await _request("POST", cluster, "_search", json_body=payload)
result = response.json()
hits = result.get("hits", {}).get("hits", [])
@@ -328,23 +358,13 @@ async def get(
if isinstance(index, ESIndex):
cluster = _index_to_cluster(index) or cluster
elasticsearch_url, api_key = _cluster_credentials(cluster)
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
params = {}
if source is not None:
params["_source_includes"] = ",".join(source)
client = get_client()
try:
response = await client.get(
f"{elasticsearch_url}/{index}/_doc/{doc_id}", params=params, headers=headers
)
response.raise_for_status()
return response.json()
except Exception as exc:
raise _wrap_exception(exc) from exc
response = await _request("GET", cluster, f"{index}/_doc/{doc_id}", params=params)
return response.json()
async def update(
@@ -353,20 +373,11 @@ async def update(
doc: Dict[str, Any],
cluster: ESCluster = ESCluster.NES,
) -> Dict[str, Any]:
elasticsearch_url, api_key = _cluster_credentials(cluster)
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
response = await _request(
"POST", cluster, f"{index}/_update/{doc_id}", json_body={"doc": doc}
)
client = get_client()
try:
response = await client.post(
f"{elasticsearch_url}/{index}/_update/{doc_id}",
json={"doc": doc},
headers=headers,
)
response.raise_for_status()
return response.json()
except Exception as exc:
raise _wrap_exception(exc) from exc
return response.json()
async def index_doc(
@@ -375,17 +386,95 @@ async def index_doc(
document: Dict[str, Any],
cluster: ESCluster = ESCluster.NES,
) -> Dict[str, Any]:
elasticsearch_url, api_key = _cluster_credentials(cluster)
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
response = await _request(
"PUT", cluster, f"{index}/_doc/{doc_id}", json_body=document
)
return response.json()
async def count(
index: ESIndex | List[ESIndex] | str | List[str],
query: Optional[Dict[str, Any]] = None,
cluster: ESCluster = ESCluster.NES,
) -> int:
"""Performs a count request (_count) on the specified Elasticsearch index.
Args:
index: The index or list of indices to count.
query: Optional query body to filter documents.
cluster: The Elasticsearch cluster to query.
Returns:
int: The number of matching documents.
"""
clusters = set()
if isinstance(index, list):
for idx in index:
if isinstance(idx, ESIndex):
c = _index_to_cluster(idx)
if c is not None:
clusters.add(c)
elif isinstance(index, ESIndex):
c = _index_to_cluster(index)
if c is not None:
clusters.add(c)
if len(clusters) == 1:
cluster = clusters.pop()
if isinstance(index, list):
index_str = ",".join(str(idx) for idx in index)
else:
index_str = str(index)
payload = {"query": query} if query else {}
response = await _request("POST", cluster, f"{index_str}/_count", json_body=payload)
return response.json().get("count", 0)
async def msearch(
searches: List[Tuple[ESIndex | str | List[str], Dict[str, Any]]],
cluster: ESCluster = ESCluster.NES,
) -> List[Dict[str, Any]]:
"""Performs a multi-search request (_msearch) on Elasticsearch.
Args:
searches: A list of tuples, each containing (index, payload_dict).
cluster: The Elasticsearch cluster to execute searches on.
Returns:
List[Dict[str, Any]]: List of response dictionaries for each search in order.
"""
if not searches:
return []
first_idx = searches[0][0]
if isinstance(first_idx, ESIndex):
c = _index_to_cluster(first_idx)
if c is not None:
cluster = c
lines = []
for idx, body in searches:
if isinstance(idx, list):
idx_str = ",".join(str(i) for i in idx)
else:
idx_str = str(idx)
header_obj = {"index": idx_str}
lines.append(json.dumps(header_obj))
lines.append(json.dumps(body))
ndjson_payload = "\n".join(lines) + "\n"
response = await _request(
"POST",
cluster,
"_msearch",
content=ndjson_payload.encode("utf-8"),
content_type="application/x-ndjson",
)
return response.json().get("responses", [])
client = get_client()
try:
response = await client.put(
f"{elasticsearch_url}/{index}/_doc/{doc_id}",
json=document,
headers=headers,
)
response.raise_for_status()
return response.json()
except Exception as exc:
raise _wrap_exception(exc) from exc
+6 -6
View File
@@ -1,9 +1,9 @@
from openai import OpenAI, APIConnectionError
from openai import APIConnectionError
from openai import AsyncOpenAI
from .. import config
from typing import Optional, Dict, Any
import asyncio
def call(
async def call(
system_prompt: str,
user_prompt: str,
model: str = None,
@@ -16,18 +16,18 @@ def call(
if model is None:
model = config.settings.llm_model
response_format = None
if json_schema is not None:
response_format = _get_response_format(schema = json_schema,schema_name=schema_name)
client = OpenAI(
client = AsyncOpenAI(
base_url=config.settings.llm_api_url,
api_key=config.settings.llm_api_key,
timeout=timeout,
)
try:
response = client.chat.completions.create(
response = await client.chat.completions.create(
model=model,
messages=[
{"role": "system", "content": system_prompt},
+1 -1
View File
@@ -82,7 +82,7 @@ async def extract_keywords(query: str, mode: str, limit: int) -> ExtractedKeywor
user_prompt += f"""Input:{text}"""
keywords = llm.call(
keywords = await llm.call(
system_prompt=system_prompt,
user_prompt=user_prompt,
json_schema = ExtractedKeywordsLLM.model_json_schema(),
+55 -25
View File
@@ -1,60 +1,71 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module contains the bootstrapping code
for fastapi that loads the service and the
webapp.
"""
from contextlib import asynccontextmanager, contextmanager
import asyncio
import logging
from contextlib import asynccontextmanager, contextmanager
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse, RedirectResponse
from inse.collaboration_network.router import router as collaboration_network_router
from inse.account_management.router import router as account_management_router
from inse.auth.router import router as auth_router
from inse.auth.service import create_predefined_accounts
from inse.authors.v2.router import router as authors_v2_router
from inse.background_jobs.router import router as background_jobs_router
from inse.background_jobs.runner import scheduler_loop as background_jobs_scheduler_loop
from inse.bookmarks.router import router as bookmarks_router
from inse.company_connections.service import router as company_connections_router
from inse.dashboard.router import router as dashboard_router
from inse.database import create_db_and_tables, get_session
from inse.exceptions import (
NotFoundException,
BadRequestException,
ElasticsearchException,
MissingApiKeyError,
NotFoundException,
UpstreamAPIException,
BadRequestException,
)
from inse.funders.service import router as funders_service_router
from inse.projects.router import router as projects_router
from inse.university_ranking.service import router as university_ranking_router
from inse.institutions.router import router as institutions_router
from inse.institutions.v2.router import router as institutions_v2_router
from inse.keywords.service import router as keywords_service_router
from inse.patents.keywords.service import router as keywords_patents_router
# caching
from inse.middleware.etag_cache import ETagCacheMiddleware
from inse.persons.service import router as persons_service_router
from inse.topics.service import router as topics_service_router
from inse.works.service import router as works_service_router
from inse.news.service import router as news_service_router
from inse.auth.router import router as auth_router
from inse.account_management.router import router as account_management_router
from inse.organization_management.router import router as organization_management_router
from inse.dashboard.router import router as dashboard_router
from inse.bookmarks.router import router as bookmarks_router
from inse.institutions.router import router as institutions_router
from inse.database import create_db_and_tables, get_session
from inse.auth.service import create_predefined_accounts
from . import config
from .service import router as service_router
from inse.patents.keywords.service import router as keywords_patents_router
from inse.patents.org.service import router as org_patents_router
from inse.patents.service import (
institution_patents_router,
)
from inse.patents.service import (
patents_router as patents_all_router,
)
from inse.patents.service import (
router as patents_service_router,
)
from inse.persons.service import router as persons_service_router
from inse.projects.dfg_institutions.router import router as dfg_institutions_router
from inse.projects.bund_institutions.router import router as bund_institutions_router
from inse.projects.dfg_persons.router import router as dfg_persons_router
from inse.projects.eu_organizations.router import router as eu_organizations_router
from inse.projects.router import router as projects_router
from inse.ranking.router import router as ranking_router
from inse.topics.service import router as topics_service_router
from inse.topics.v2.router import router as topics_v2_router
from inse.university_ranking.service import router as university_ranking_router
from inse.works.service import router as works_service_router
from inse.works.v2.router import router as works_v2_router
from . import config
from .service import router as service_router
logger = logging.getLogger(__name__)
### startup
@@ -68,7 +79,17 @@ async def lifespan(app: FastAPI):
create_db_and_tables()
with contextmanager(get_session)() as session:
create_predefined_accounts(session, "../data/predefined_accounts.json")
background_jobs_scheduler_task = None
if settings.background_jobs_scheduler_enabled:
background_jobs_scheduler_task = asyncio.create_task(
background_jobs_scheduler_loop()
)
yield
if background_jobs_scheduler_task is not None:
background_jobs_scheduler_task.cancel()
logger.info("Shutting down the application...")
@@ -80,10 +101,10 @@ app = FastAPI(
servers=settings.servers,
lifespan=lifespan,
)
app.include_router(collaboration_network_router)
app.include_router(institution_patents_router)
app.include_router(org_patents_router)
app.include_router(institutions_router)
app.include_router(bund_institutions_router)
app.include_router(topics_service_router)
app.include_router(works_service_router)
app.include_router(persons_service_router)
@@ -92,6 +113,7 @@ app.include_router(news_service_router)
app.include_router(company_connections_router)
app.include_router(patents_service_router)
app.include_router(university_ranking_router)
app.include_router(ranking_router)
app.include_router(projects_router)
app.include_router(patents_all_router)
app.include_router(keywords_service_router)
@@ -102,14 +124,22 @@ app.include_router(service_router)
app.include_router(auth_router)
app.include_router(account_management_router)
app.include_router(organization_management_router)
app.include_router(works_v2_router)
app.include_router(authors_v2_router)
app.include_router(institutions_v2_router)
app.include_router(topics_v2_router)
app.include_router(dashboard_router)
app.include_router(dfg_institutions_router)
app.include_router(dfg_persons_router)
app.include_router(bookmarks_router)
app.include_router(background_jobs_router)
app.include_router(eu_organizations_router)
app.add_middleware(
ETagCacheMiddleware,
ttl=120, # 2 minutes expiration time
ttl=600, # 10 minutes expiration time
)
app.add_middleware(
CORSMiddleware,
+68 -15
View File
@@ -8,14 +8,25 @@ from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import Response
# Paths excluded from caching entirely (everything concerning auth/identity/mutations)
EXCLUDED_PATHS = (
# Responses whose contents depend on the current account or effective
# organization must never be reused by the browser.
NO_STORE_PATH_PREFIXES = (
"/api/auth/v2",
"/api/accounts",
"/api/background-jobs",
"/api/bookmarks",
"/api/organizations",
)
"/api/dashboard",
"/api/rank/rank-author",
"/api/rank/orientation-profiles",
"/api/works/v2/classification/",
)
NO_STORE_PATH_FRAGMENTS = (
"/company-connections",
"/primary-category-aggregations",
"/collaboration-graph/",
)
# POST is opt-out. Add any endpoint here that MUTATES state (create/update/delete/
# trigger side effects), even if it "usually" returns 200.
EXCLUDED_POST_PATHS = (
@@ -32,7 +43,7 @@ class ETagCacheMiddleware(BaseHTTPMiddleware):
self.ttl = ttl
self.maxsize = maxsize
# Insertion-ordered so we can evict the oldest entry in O(1) when over capacity.
self.cache: "OrderedDict[str, dict]" = OrderedDict()
self.cache: OrderedDict[str, dict] = OrderedDict()
def _get(self, key: str) -> dict | None:
entry = self.cache.get(key)
@@ -85,8 +96,43 @@ class ETagCacheMiddleware(BaseHTTPMiddleware):
def _content_type(self, response: Response) -> str | None:
return response.headers.get("content-type")
def _requires_no_store(self, request: Request) -> bool:
path = request.url.path
return path.startswith(NO_STORE_PATH_PREFIXES) or any(
fragment in path for fragment in NO_STORE_PATH_FRAGMENTS
)
def _set_no_store_headers(self, response: Response) -> None:
response.headers["Cache-Control"] = "private, no-store, max-age=0"
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "0"
self._append_vary_authorization(response.headers)
@staticmethod
def _append_vary_authorization(headers) -> None:
vary_values = [
value.strip()
for value in headers.get("Vary", "").split(",")
if value.strip()
]
if not any(value.lower() == "authorization" for value in vary_values):
vary_values.append("Authorization")
headers["Vary"] = ", ".join(vary_values)
def _cache_response_headers(
self, request: Request, etag: str, content_type: str | None
) -> dict[str, str]:
cache_control = f"max-age={self.ttl}"
headers = {"ETag": etag, "Cache-Control": cache_control}
if request.headers.get("authorization"):
headers["Cache-Control"] = f"private, {cache_control}"
headers["Vary"] = "Authorization"
if content_type:
headers["Content-Type"] = content_type
return headers
def _is_cacheable_request(self, request: Request) -> bool:
if request.url.path.startswith(EXCLUDED_PATHS):
if self._requires_no_store(request):
return False
if request.method == "GET":
return True
@@ -95,6 +141,11 @@ class ETagCacheMiddleware(BaseHTTPMiddleware):
return False
async def dispatch(self, request: Request, call_next):
if self._requires_no_store(request):
response = await call_next(request)
self._set_no_store_headers(response)
return response
if not self._is_cacheable_request(request):
return await call_next(request)
@@ -118,14 +169,18 @@ class ETagCacheMiddleware(BaseHTTPMiddleware):
# Cache hit + not expired
if entry:
if client_etag == entry["etag"]:
headers = {"ETag": entry["etag"]}
if entry.get("content_type"):
headers["Content-Type"] = entry["content_type"]
headers = self._cache_response_headers(
request,
entry["etag"],
entry.get("content_type"),
)
return Response(status_code=304, headers=headers)
headers = {"ETag": entry["etag"], "Cache-Control": f"max-age={self.ttl}"}
if entry.get("content_type"):
headers["Content-Type"] = entry["content_type"]
headers = self._cache_response_headers(
request,
entry["etag"],
entry.get("content_type"),
)
return Response(
content=entry["body"],
status_code=entry["status_code"],
@@ -151,11 +206,9 @@ class ETagCacheMiddleware(BaseHTTPMiddleware):
},
)
headers = {"ETag": etag, "Cache-Control": f"max-age={self.ttl}"}
if content_type:
headers["Content-Type"] = content_type
headers = self._cache_response_headers(request, etag, content_type)
return Response(
content=body,
status_code=response.status_code,
headers=headers,
)
)
@@ -0,0 +1,53 @@
from fastapi import FastAPI
from fastapi.testclient import TestClient
from inse.middleware.etag_cache import ETagCacheMiddleware
def _app_with_counter():
app = FastAPI()
calls = {"get": 0, "post": 0}
@app.get("/api/background-jobs/tasks")
def get_tasks():
calls["get"] += 1
return {"call": calls["get"]}
@app.post("/api/background-jobs/tasks/4/run")
def run_task():
calls["post"] += 1
return {"call": calls["post"]}
app.add_middleware(ETagCacheMiddleware, ttl=120)
return app, calls
def test_background_job_gets_are_never_cached():
app, calls = _app_with_counter()
with TestClient(app) as client:
first = client.get("/api/background-jobs/tasks")
second = client.get(
"/api/background-jobs/tasks",
headers={"If-None-Match": first.headers.get("etag", "")},
)
assert first.status_code == 200
assert second.status_code == 200
assert first.json() == {"call": 1}
assert second.json() == {"call": 2}
assert calls["get"] == 2
def test_background_job_post_side_effects_are_never_replayed_from_cache():
app, calls = _app_with_counter()
with TestClient(app) as client:
first = client.post("/api/background-jobs/tasks/4/run")
second = client.post("/api/background-jobs/tasks/4/run")
assert first.status_code == 200
assert second.status_code == 200
assert first.json() == {"call": 1}
assert second.json() == {"call": 2}
assert calls["post"] == 2
+10 -2
View File
@@ -28,6 +28,8 @@ T = TypeVar("T", bound=BaseModel)
class Page(BaseModel, Generic[T]):
"""A generic page model that represents a paginated response containing elements of type T."""
elements: List[T] = Field(default=[], description="The elements of the page.")
page: int = Field(default=0, description="The page number. (0-based)")
size: int = Field(default=20, description="The page size in elements.")
@@ -60,7 +62,14 @@ class ESIndex(StrEnum):
ORG_PATENTS = "org_patents"
PROJECTS_BUND_V1 = "projects_bund_v1"
PROJECTS_DFG_ALL = "dfg_projects_2.0"
DFG_PROJECTS_V2 = "dfg_projects_2.0"
DFG_INSTITUTES_V2 = "dfg_institutes_2.0"
PROJECTS_DFG_OPENALEX_TOPICS = "projects_dfg_openalex_topics"
AKTUELLES = "aktuell"
AKTUELLES_POSTPROC = "aktuell_postproc"
AKTUELLES_OPENALEX_TOPICS = "aktuell_openalex_topics"
CORDIS_EU_ORGANIZATIONS_WILDCARD = "cordis_eu_*_organizations"
CORDIS_EU_PROJECTS_WILDCARD = "cordis_eu_*_projects"
@@ -114,4 +123,3 @@ class ESIndex(StrEnum):
PROJECTS_CORDIS_EU_H2020_TOPICS = "projects_cordiseu_h2020_openalex_topics"
PROJECTS_CORDIS_EU_HEUROPE_TOPICS = "projects_cordiseu_heurope_openalex_topics"
PATENTS_OPENALEX_KEYWORDS = "patents_openalex_keywords"
@@ -8,8 +8,8 @@
"""
from datetime import date, datetime
from typing import Optional, List, Set, Any
from typing import Optional, List, Set, Any, Dict
from inse.models.openalex.topic import Topic, TopicDomain, TopicField, TopicSubfield
from pydantic import BaseModel, ConfigDict, Field, field_validator
@@ -189,6 +189,10 @@ class BundProjectDetails(BaseModel):
default_factory=list,
description="All institutions associated with the Bund project",
)
oa_topics: Optional[List[Topic]] = Field(
default_factory=list,
description="OpenAlex topics associated with the Bund project",
)
# --- Validators for type coercion ---
@@ -301,7 +305,17 @@ class BundProjectDetails(BaseModel):
if source.get("PT_fullname"):
institutions.add(source["PT_fullname"].strip())
topics_raw = source.get("oa_topics") or []
if not isinstance(source, dict):
return cls.model_validate(source)
oa_topics = None
if isinstance(topics_raw, list) and topics_raw:
sorted_topics_raw = sorted(
(t for t in topics_raw if isinstance(t, dict)),
key=lambda t: t.get("rank") if t.get("rank") is not None else float("inf"),
)
oa_topics = [cls._topic_from_match(t) for t in sorted_topics_raw]
return cls(
id=hit["_id"],
funding_reference=source.get("Förderkennzeichen"),
@@ -334,4 +348,24 @@ class BundProjectDetails(BaseModel):
unix_timestamp=source.get("unix_timestamp"),
associated_persons=sorted(persons),
institutions=sorted(institutions),
oa_topics=oa_topics
)
@staticmethod
def _topic_from_match(match: Dict[str, Any]) -> Topic:
"""Builds a Topic model from a flattened topic_match dict.
"""
domain_name = match.get("domain")
field_name = match.get("field")
subfield_name = match.get("subfield")
domain = TopicDomain(display_name=domain_name) if domain_name else None
field = TopicField(display_name=field_name) if field_name else None
subfield = TopicSubfield(display_name=subfield_name) if subfield_name else None
return Topic(
id=match.get("topic_id"),
display_name=match.get("topic_display_name"),
domain=domain,
field=field,
subfield=subfield,
)
@@ -1,293 +1,435 @@
# coding: utf-8
"""
DFG Project Clean Model
DFG Project Clean Model (v2)
Summary model that consolidates all scattered person and institution fields
from the raw projects_dfg_all index into clean, unified lists.
Enriched, consolidated model built on top of the structured
projects_dfg_v2 API models (DFGProject / DFGPerson / DFGInstitute),
rather than the old flat projects_dfg_all Elasticsearch index.
"""
from typing import Optional, List, Set
from typing import List, Optional
from pydantic import BaseModel, ConfigDict, Field
from inse.models.projects_dfg_v2.project.dfg_project import DFGProject
from inse.models.projects_dfg_v2.project.dfg_project_persons_inner import (
DFGProjectPersonsInner,
)
from inse.models.projects_dfg_v2.project.dfg_project_institutions_inner import (
DFGProjectInstitutionsInner,
)
from inse.models.projects_dfg_v2.project.dfg_project_subprojects_inner import (
DFGProjectSubprojectsInner,
)
from inse.models.projects_dfg_v2.project.dfg_project_publications_inner import (
DFGProjectPublicationsInner,
)
from inse.models.projects_dfg_v2.project.dfg_project_fachgebiete_inner import (
DFGProjectFachgebieteInner,
)
from inse.topics.model import Topic
class DfgProjectPersonRole(BaseModel):
"""A person associated with the project, together with their role."""
model_config = ConfigDict(populate_by_name=True)
person_id: Optional[int] = Field(default=None, description="DFG person ID")
full_name: Optional[str] = Field(default=None, description="Full name of the person")
orcid_id: Optional[str] = Field(
default=None,
description=(
"ORCID iD, if known. Not present on the project's embedded person "
"record (DFGProjectPersonsInner) -- only populated if the caller "
"cross-references the full DFGPerson record via person_id and "
"calls DfgProjectDetails.enrich_orcids afterwards."
),
)
role_key: Optional[str] = Field(
default=None, description="Machine-readable role key (e.g. 'antragsteller')"
)
role_label_de: Optional[str] = Field(default=None, description="Role label (German)")
role_label_en: Optional[str] = Field(default=None, description="Role label (English)")
affiliation_de: Optional[str] = Field(
default=None, description="Person's affiliation at time of project (German)"
)
affiliation_en: Optional[str] = Field(
default=None, description="Person's affiliation at time of project (English)"
)
is_deceased: Optional[bool] = Field(default=None, description="Whether the person is deceased")
is_head: Optional[bool] = Field(
default=None, description="Whether this person is highlighted as the project head"
)
@classmethod
def from_inner(cls, p: DFGProjectPersonsInner) -> "DfgProjectPersonRole":
return cls(
person_id=p.person_id,
full_name=p.full_name,
role_key=p.role_key,
role_label_de=p.role_label_de,
role_label_en=p.role_label_en,
affiliation_de=p.affiliation_de,
affiliation_en=p.affiliation_en,
is_deceased=p.is_deceased,
is_head=p.is_head_display,
)
class DfgProjectInstitutionRole(BaseModel):
"""An institution associated with the project, together with its role."""
model_config = ConfigDict(populate_by_name=True)
institute_id: Optional[int] = Field(default=None, description="DFG institute ID")
name_de: Optional[str] = Field(default=None, description="Institution name (German)")
name_en: Optional[str] = Field(default=None, description="Institution name (English)")
role_key: Optional[str] = Field(default=None, description="Machine-readable role key")
role_label_de: Optional[str] = Field(default=None, description="Role label (German)")
role_label_en: Optional[str] = Field(default=None, description="Role label (English)")
is_dissolved: Optional[bool] = Field(
default=None, description="Whether the institution has since been dissolved"
)
is_head: Optional[bool] = Field(
default=None, description="Whether this institution is highlighted as the lead institution"
)
@classmethod
def from_inner(cls, i: DFGProjectInstitutionsInner) -> "DfgProjectInstitutionRole":
return cls(
institute_id=i.institute_id,
name_de=i.institute_name_de,
name_en=i.institute_name_en,
role_key=i.role_key,
role_label_de=i.role_label_de,
role_label_en=i.role_label_en,
is_dissolved=i.is_dissolved,
is_head=i.is_head_display,
)
class DfgProjectSubprojectSummary(BaseModel):
"""A lightweight reference to a sub-project of this project."""
model_config = ConfigDict(populate_by_name=True)
subproject_id: Optional[int] = None
title_de: Optional[str] = None
title_en: Optional[str] = None
short_title: Optional[str] = None
role_label_de: Optional[str] = Field(
default=None, description="Role of the sub-project lead within the sub-project"
)
person_full_name: Optional[str] = Field(
default=None, description="Sub-project lead, derived from first/last name fields"
)
status_de: Optional[str] = None
funding_start: Optional[int] = None
funding_end: Optional[int] = None
@classmethod
def from_inner(cls, s: DFGProjectSubprojectsInner) -> "DfgProjectSubprojectSummary":
person_full_name = None
if s.person_first_names or s.person_last_name:
person_full_name = " ".join(
part for part in [s.person_first_names, s.person_last_name] if part
).strip() or None
return cls(
subproject_id=s.subproject_id,
title_de=s.title_de,
title_en=s.title_en,
short_title=s.short_title,
role_label_de=s.role_label_de,
person_full_name=person_full_name,
status_de=s.status_de,
funding_start=s.funding_start,
funding_end=s.funding_end,
)
class DfgProjectPublicationSummary(BaseModel):
"""A lightweight reference to a publication resulting from the project."""
model_config = ConfigDict(populate_by_name=True)
publication_id: Optional[int] = None
title: Optional[str] = None
authors_editors: Optional[str] = None
doi: Optional[str] = None
publication_year: Optional[int] = None
@classmethod
def from_inner(cls, p: DFGProjectPublicationsInner) -> "DfgProjectPublicationSummary":
return cls(
publication_id=p.publication_id,
title=p.title,
authors_editors=p.authors_editors,
doi=p.doi,
publication_year=p.publication_year,
)
class DfgProjectSubjectArea(BaseModel):
"""A single subject-area classification entry (DFG 'Fachsystematik')."""
model_config = ConfigDict(populate_by_name=True)
fach: Optional[str] = None
fachgebiet: Optional[str] = None
fachkollegium: Optional[str] = None
wissenschaftsbereich: Optional[str] = None
@classmethod
def from_inner(cls, f: DFGProjectFachgebieteInner) -> "DfgProjectSubjectArea":
return cls(
fach=f.fach,
fachgebiet=f.fachgebiet,
fachkollegium=f.fachkollegium,
wissenschaftsbereich=f.wissenschaftsbereich,
)
class DfgProjectDetails(BaseModel):
"""
Clean summary model for a DFG project, consolidating all person roles
and institution references into unified lists.
Clean, enriched summary model for a DFG project.
"""
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
model_config = ConfigDict(populate_by_name=True, validate_assignment=True)
id: Optional[int] = Field(default=None, description="The DFG project ID")
link: Optional[str] = Field(default=None, description="Canonical DFG link to the project")
page_url: Optional[str] = Field(default=None, description="DFG GEPRIS page URL")
external_link: Optional[str] = Field(
default=None, description="External project website/link, if provided"
)
id: str = Field(description="The ID of the DFG project")
link: Optional[str] = Field(default=None, description="The link to the DFG project")
title: Optional[str] = Field(
default=None, description="The title of the DFG project"
title_de: Optional[str] = Field(default=None, description="Project title (German)")
title_en: Optional[str] = Field(default=None, description="Project title (English)")
description_de: Optional[str] = Field(default=None, description="Project abstract (German)")
description_en: Optional[str] = Field(default=None, description="Project abstract (English)")
final_report_abstract_de: Optional[str] = Field(
default=None, description="Final report abstract (German), if the project has concluded"
)
description: Optional[str] = Field(
default=None, description="The description of the DFG project"
final_report_abstract_en: Optional[str] = Field(
default=None, description="Final report abstract (English), if the project has concluded"
)
project_identifier: Optional[str] = Field(
default=None,
description="The project identifier of the DFG project",
)
project_identifier_de: Optional[str] = Field(default=None, description="DFG project identifier (German)")
project_identifier_en: Optional[str] = Field(default=None, description="DFG project identifier (English)")
funding_start_date: Optional[str] = Field(
default=None, description="The funding start date of the DFG project"
)
funding_end_date: Optional[str] = Field(
default=None, description="The funding end date of the DFG project"
)
funding_start: Optional[int] = Field(default=None, description="Funding start year")
funding_end: Optional[int] = Field(default=None, description="Funding end year")
funding_period_de: Optional[str] = Field(default=None, description="Human-readable funding period (German)")
funding_period_en: Optional[str] = Field(default=None, description="Human-readable funding period (English)")
funding_type_de: Optional[str] = Field(default=None, description="Funding type / programme (German)")
funding_type_en: Optional[str] = Field(default=None, description="Funding type / programme (English)")
funding_type_key: Optional[str] = Field(default=None, description="Machine-readable funding type key")
dfg_procedure: Optional[str] = Field(
default=None, description="The DFG procedure"
)
subject_area: Optional[str] = Field(
default=None,
description="The subject area classification",
)
funding_type: Optional[str] = Field(
default=None, description="The type of funding"
)
international_reference: Optional[str] = Field(
default=None,
description="International reference",
default=None, description="DFG procedure / template type (e.g. Sachbeihilfe, SFB, GRK)"
)
website: Optional[str] = Field(
default=None, description="The project website"
is_transfer_project: Optional[bool] = Field(
default=None, description="Whether this is a transfer project"
)
# Unified person list: all person names from any role
website_html_de: Optional[str] = Field(
default=None, description="Raw project website HTML content (German), as served by DFG"
)
website_html_en: Optional[str] = Field(
default=None, description="Raw project website HTML content (English), as served by DFG"
)
equipment_group: Optional[str] = Field(
default=None,
description="Large-equipment (Großgerät) group, for equipment-funding projects",
)
equipment_name: Optional[str] = Field(
default=None,
description="Large-equipment (Großgerät) name, for equipment-funding projects",
)
subject_area_de: Optional[str] = Field(default=None, description="Subject area, summary text (German)")
subject_area_en: Optional[str] = Field(default=None, description="Subject area, summary text (English)")
subject_classifications: List[DfgProjectSubjectArea] = Field(
default_factory=list,
description="Detailed DFG subject-area classification entries (Fachsystematik)",
)
international_relation_de: Optional[str] = Field(
default=None, description="International reference/cooperation (German)"
)
international_relation_en: Optional[str] = Field(
default=None, description="International reference/cooperation (English)"
)
# Structured, role-aware person and institution lists
persons: List[DfgProjectPersonRole] = Field(
default_factory=list,
description="All persons associated with the project, each with their role",
)
institutions: List[DfgProjectInstitutionRole] = Field(
default_factory=list,
description="All institutions associated with the project, each with their role",
)
# Convenience flat views, derived from the structured lists above
associated_persons: List[str] = Field(
default_factory=list,
description="All persons associated with the DFG project (any role)",
description="Flat, de-duplicated list of all person full names (convenience view)",
)
# Unified institution list: all institutions involved
institutions: List[str] = Field(
associated_institutions: List[str] = Field(
default_factory=list,
description="All institutions associated with the DFG project",
description="Flat, de-duplicated list of all institution names (convenience view)",
)
# Sub-project reference
subproject_of: Optional[str] = Field(
default=None,
description="Parent project this is a sub-project of",
# Parent / sub-project structure
parent_project_id: Optional[int] = Field(default=None, description="Parent project ID, if this is a sub-project")
parent_title_de: Optional[str] = Field(default=None, description="Parent project title (German)")
parent_title_en: Optional[str] = Field(default=None, description="Parent project title (English)")
subprojects: List[DfgProjectSubprojectSummary] = Field(
default_factory=list, description="Sub-projects of this project, if any"
)
publications: List[DfgProjectPublicationSummary] = Field(
default_factory=list, description="Publications resulting from the project"
)
topics: Optional[List[Topic]] = Field(
default_factory=list, description="OpenAlex topics associated with the project ID"
)
@classmethod
def from_dfg_project(cls, project: DFGProject) -> "DfgProjectDetails":
"""
Build a DfgProjectDetails from a fully-typed DFGProject instance
(e.g. as returned by the projects_dfg_v2 API client).
"""
persons = [DfgProjectPersonRole.from_inner(p) for p in (project.persons or [])]
institutions = [
DfgProjectInstitutionRole.from_inner(i) for i in (project.institutions or [])
]
subprojects = [
DfgProjectSubprojectSummary.from_inner(s) for s in (project.subprojects or [])
]
publications = [
DfgProjectPublicationSummary.from_inner(p) for p in (project.publications or [])
]
subject_classifications = [
DfgProjectSubjectArea.from_inner(f) for f in (project.fachgebiete or [])
]
# De-duplicated flat views, order-preserving
seen_persons = set()
associated_persons = []
for p in persons:
if p.full_name and p.full_name not in seen_persons:
seen_persons.add(p.full_name)
associated_persons.append(p.full_name)
seen_institutions = set()
associated_institutions = []
for i in institutions:
name = i.name_de or i.name_en
if name and name not in seen_institutions:
seen_institutions.add(name)
associated_institutions.append(name)
return cls(
id=project.id or project.project_id,
link=project.link,
page_url=project.page_url,
external_link=project.external_link,
title_de=project.title_de,
title_en=project.title_en,
description_de=project.abstract_de,
description_en=project.abstract_en,
final_report_abstract_de=project.final_report_abstract_de,
final_report_abstract_en=project.final_report_abstract_en,
project_identifier_de=project.project_identifier_de,
project_identifier_en=project.project_identifier_en,
funding_start=project.funding_start,
funding_end=project.funding_end,
funding_period_de=project.funding_period_de,
funding_period_en=project.funding_period_en,
funding_type_de=project.funding_type_de,
funding_type_en=project.funding_type_en,
funding_type_key=project.funding_type_key,
dfg_procedure=project.template_type,
is_transfer_project=project.is_transfer_project,
website_html_de=project.website_html_de,
website_html_en=project.website_html_en,
equipment_group=project.equipment_group,
equipment_name=project.equipment_name,
subject_area_de=project.subject_area_de,
subject_area_en=project.subject_area_en,
subject_classifications=subject_classifications,
international_relation_de=project.international_relation_de,
international_relation_en=project.international_relation_en,
persons=persons,
institutions=institutions,
associated_persons=associated_persons,
associated_institutions=associated_institutions,
parent_project_id=project.parent_project_id,
parent_title_de=project.parent_title_de,
parent_title_en=project.parent_title_en,
subprojects=subprojects,
publications=publications,
topics=project.topics,
)
@classmethod
def from_dict(cls, obj: dict) -> "DfgProjectDetails":
"""Convenience constructor from a raw dict (e.g. a JSON API response body)."""
obj = cls._sanitize_raw_project_dict(obj)
return cls.from_dfg_project(DFGProject.from_dict(obj))
@staticmethod
def _sanitize_raw_project_dict(obj: dict) -> dict:
"""
Work around known mismatches between the generated DFGProject model
and the actual shape of API/index data, before handing off to
DFGProject.from_dict (which would otherwise raise a ValidationError
and abort the whole parse).
"""
if isinstance(obj.get("subject_classifications"), list):
obj = dict(obj)
obj.pop("subject_classifications", None)
return obj
@classmethod
def from_elastic_hit(cls, hit: dict) -> "DfgProjectDetails":
"""
Create a DfgProject from an Elasticsearch hit, consolidating all
person and institution fields into unified lists.
Compatibility constructor for callers still reading from an
Elasticsearch hit (e.g. `{"_id": ..., "_source": {...}}`), matching
the old model's from_elastic_hit signature.
"""
source = dict(hit.get("_source", {}))
source = hit.get("_source", {})
if source.get("id") is None and source.get("project_id") is None:
raw_id = hit.get("_id")
if raw_id is not None:
try:
source["id"] = int(raw_id)
except (TypeError, ValueError):
# Non-numeric _id (e.g. a composite/legacy key) - leave
# id unset rather than fail the whole parse.
pass
associated_persons: Set[str] = set()
institutions: Set[str] = set()
return cls.from_dict(source)
# --- Collect all persons and institutions from nested persons array ---
persons_list = source.get("persons", [])
if isinstance(persons_list, list):
for p in persons_list:
if isinstance(p, dict):
full_name = p.get("full_name")
if full_name:
associated_persons.add(full_name.strip())
aff_de = p.get("affiliation_de")
if aff_de:
institutions.add(aff_de.strip())
aff_en = p.get("affiliation_en")
if aff_en:
institutions.add(aff_en.strip())
# --- Collect all persons from every person-related field ---
# Applicant fields
_add_persons(source, associated_persons, "Antragsteller") # semicolon-separated
_add_person(source, associated_persons, "Antragstellerin")
_add_persons(
source, associated_persons, "Antragstellerinnen"
) # semicolon-separated
_add_persons(
source, associated_persons, "Antragstellerinnen / Antragsteller"
) # semicolon-separated
# Co-applicant fields
_add_persons(source, associated_persons, "Mitantragsteller")
_add_person(source, associated_persons, "Mitantragstellerin")
_add_persons(source, associated_persons, "Mitantragstellerinnen")
_add_persons(
source, associated_persons, "Mitantragstellerinnen / Mitantragsteller"
)
# Former applicant fields
_add_persons(source, associated_persons, "Ehemalige Antragsteller")
_add_person(source, associated_persons, "Ehemalige Antragstellerin")
_add_persons(source, associated_persons, "Ehemalige Antragstellerinnen")
_add_persons(
source,
associated_persons,
"Ehemalige Antragstellerinnen / Ehemalige Antragsteller",
)
_add_person(source, associated_persons, "Ehemaliger Antragsteller")
# Speaker / coordinator fields
_add_person(source, associated_persons, "Sprecher")
_add_person(source, associated_persons, "Sprecherin")
_add_persons(source, associated_persons, "Sprecherinnen")
_add_persons(source, associated_persons, "Sprecherinnen / Sprecher")
_add_person(source, associated_persons, "Co-Sprecher")
_add_persons(source, associated_persons, "Co-Sprecherinnen / Co-Sprecher")
# IGK partner speaker fields
_add_person(source, associated_persons, "Sprecher (IGK-Partner)")
_add_person(source, associated_persons, "Sprecherin (IGK-Partner)")
_add_persons(
source,
associated_persons,
"Sprecherinnen (IGK-Partner) / Sprecher (IGK-Partner)",
)
# Leader fields
_add_person(source, associated_persons, "Leiter")
_add_person(source, associated_persons, "Leiterin")
_add_persons(source, associated_persons, "Leiterinnen")
_add_persons(source, associated_persons, "Leiterinnen / Leiter")
# Sub-project leader fields
_add_persons(source, associated_persons, "Teilprojektleiter")
_add_person(source, associated_persons, "Teilprojektleiterin")
_add_persons(source, associated_persons, "Teilprojektleiterinnen")
_add_persons(
source, associated_persons, "Teilprojektleiterinnen / Teilprojektleiter"
)
# Participating scientist fields
_add_persons(source, associated_persons, "beteiligte Wissenschaftler")
_add_person(source, associated_persons, "beteiligte Wissenschaftlerin")
_add_persons(source, associated_persons, "beteiligte Wissenschaftlerinnen")
_add_persons(
source,
associated_persons,
"beteiligte Wissenschaftlerinnen / beteiligte Wissenschaftler",
)
_add_person(source, associated_persons, "beteiligter Wissenschaftler")
# Participating person fields
_add_person(source, associated_persons, "Beteiligte Person")
_add_persons(source, associated_persons, "Beteiligte Personen")
# Host fields (for guest researchers)
_add_person(source, associated_persons, "Gastgeber")
_add_person(source, associated_persons, "Gastgeberin")
_add_persons(source, associated_persons, "Gastgeberinnen")
_add_persons(source, associated_persons, "Gastgeberinnen / Gastgeber")
# Cooperation partner fields
_add_person(source, associated_persons, "Kooperationspartner")
_add_person(source, associated_persons, "Kooperationspartnerin")
_add_persons(source, associated_persons, "Kooperationspartnerinnen")
_add_persons(
source, associated_persons, "Kooperationspartnerinnen / Kooperationspartner"
)
# Co-responsible fields
_add_person(source, associated_persons, "Mitverantwortlich")
_add_person(source, associated_persons, "Mitverantwortlich(e)")
_add_persons(source, associated_persons, "Mitverantwortliche")
# Application partner
_add_person(source, associated_persons, "Anwendungspartner")
# Foreign co-applicant fields
_add_persons(source, associated_persons, "ausländische Mitantragsteller")
_add_person(source, associated_persons, "ausländischer Mitantragsteller")
# Person creator (from nested fields)
if "person_creater_name" in source and source["person_creater_name"]:
associated_persons.add(source["person_creater_name"].strip())
# Deputy (stellvertr) - nested object
stellvertr = source.get("stellvertr")
if stellvertr and isinstance(stellvertr, dict):
for field in ["stellvertreter", "stellvertreterin"]:
if field in stellvertr and stellvertr[field]:
associated_persons.add(stellvertr[field].strip())
# --- Collect all institutions ---
_add_institution(source, institutions, "Antragstellende Institution")
_add_institution(source, institutions, "Mitantragstellende Institution")
_add_institution(source, institutions, "Beteiligte Einrichtung")
_add_institution(source, institutions, "Beteiligte Hochschule")
_add_institution(source, institutions, "Beteiligte Institution")
_add_institution(source, institutions, "IGK-Partnerinstitution")
_add_institution(source, institutions, "Partnerorganisation")
_add_institution(source, institutions, "Unternehmen")
# Foreign institution (nested object)
auslaend = source.get("ausländ")
if auslaend and isinstance(auslaend, dict):
for field in [
"auslaendischeInstitution",
"auslaendischeInstitution2",
"auslaendischesUnternehmen",
"auslaendischesUnternehmen2",
]:
if field in auslaend and auslaend[field]:
institutions.add(auslaend[field].strip())
return cls(
id=hit["_id"],
link=source.get("link") or source.get("page_url"),
title=source.get("title") or source.get("title_de") or source.get("title_en"),
description=source.get("description") or source.get("abstract_de") or source.get("abstract_en"),
project_identifier=source.get("Projektkennung") or source.get("project_identifier_de") or source.get("project_identifier_en"),
funding_start_date=str(source.get("funding_start")) if source.get("funding_start") is not None else None,
funding_end_date=str(source.get("funding_end")) if source.get("funding_end") is not None else None,
dfg_procedure=source.get("DFG-Verfahren") or source.get("template_type"),
subject_area=source.get("Fachliche Zuordnung") or source.get("subject_area_de") or source.get("subject_area_en"),
funding_type=source.get("Förderung") or source.get("funding_type_sort"),
international_reference=source.get("Internationaler Bezug") or source.get("international_relation_de") or source.get("international_relation_en"),
website=source.get("Webseite"),
associated_persons=sorted(associated_persons), # sorted for consistency
institutions=sorted(institutions),
subproject_of=source.get("Teilprojekt zu") or source.get("parent_project_id"),
)
# --- Helper functions for parsing source fields ---
def _add_person(source: dict, persons: Set[str], field: str) -> None:
"""Add a single person value from a field."""
if field in source and source[field]:
value = source[field].strip()
if value:
persons.add(value)
def _add_persons(source: dict, persons: Set[str], field: str) -> None:
"""Add persons from a semicolon-separated field."""
if field in source and source[field]:
for person in source[field].split(";"):
cleaned = person.strip()
if cleaned:
persons.add(cleaned)
def _add_institution(source: dict, institutions: Set[str], field: str) -> None:
"""Add a single institution value from a field."""
if field in source and source[field]:
value = source[field].strip()
if value:
institutions.add(value)
def enrich_orcids(self, persons_by_id: dict) -> None:
"""
Fill in orcid_id on each entry in `self.persons`, given a mapping of
person_id -> DFGPersonPerson (or DFGPerson) for the persons involved
in this project
"""
for person in self.persons:
record = persons_by_id.get(person.person_id)
if record is not None:
person.orcid_id = getattr(record, "orcid_id", None)
@@ -0,0 +1,157 @@
# coding: utf-8
"""
DFG Institutes API
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
The version of the OpenAPI document: 1.0.0
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from datetime import datetime
from pydantic import BaseModel, ConfigDict, StrictBool, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.projects_dfg_v2.institute.dfg_institute_institute import DFGInstituteInstitute
from inse.models.projects_dfg_v2.institute.dfg_institute_projects_inner import DFGInstituteProjectsInner
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class DFGInstitute(BaseModel):
"""
DFGInstitute
""" # noqa: E501
address_city: Optional[StrictStr] = None
address_country_de: Optional[StrictStr] = None
address_country_en: Optional[StrictStr] = None
address_hidden: Optional[StrictBool] = None
address_postal_code_city: Optional[StrictStr] = None
address_street: Optional[StrictStr] = None
aku_id: Optional[StrictInt] = None
fetched_at: Optional[datetime] = None
id: Optional[StrictInt] = None
institute: Optional[DFGInstituteInstitute] = None
institute_category_key: Optional[StrictStr] = None
institute_category_label_de: Optional[StrictStr] = None
institute_category_label_en: Optional[StrictStr] = None
institute_id: Optional[StrictInt] = None
institute_name_de: Optional[StrictStr] = None
institute_name_en: Optional[StrictStr] = None
institute_postal_address: Optional[StrictStr] = None
institute_type_key: Optional[StrictStr] = None
institute_type_label_de: Optional[StrictStr] = None
institute_type_label_en: Optional[StrictStr] = None
is_dissolved: Optional[StrictBool] = None
is_research_device: Optional[StrictBool] = None
link: Optional[StrictStr] = None
page_url: Optional[StrictStr] = None
project_types_order: Optional[StrictStr] = None
projects: Optional[List[DFGInstituteProjectsInner]] = None
root_id: Optional[StrictInt] = None
root_name_de: Optional[StrictStr] = None
root_name_en: Optional[StrictStr] = None
__properties: ClassVar[List[str]] = ["address_city", "address_country_de", "address_country_en", "address_hidden", "address_postal_code_city", "address_street", "aku_id", "fetched_at", "id", "institute", "institute_category_key", "institute_category_label_de", "institute_category_label_en", "institute_id", "institute_name_de", "institute_name_en", "institute_postal_address", "institute_type_key", "institute_type_label_de", "institute_type_label_en", "is_dissolved", "is_research_device", "link", "page_url", "project_types_order", "projects", "root_id", "root_name_de", "root_name_en"]
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 DFGInstitute 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 institute
if self.institute:
_dict['institute'] = self.institute.to_dict()
# override the default output from pydantic by calling `to_dict()` of each item in projects (list)
_items = []
if self.projects:
for _item_projects in self.projects:
if _item_projects:
_items.append(_item_projects.to_dict())
_dict['projects'] = _items
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of DFGInstitute from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"address_city": obj.get("address_city"),
"address_country_de": obj.get("address_country_de"),
"address_country_en": obj.get("address_country_en"),
"address_hidden": obj.get("address_hidden"),
"address_postal_code_city": obj.get("address_postal_code_city"),
"address_street": obj.get("address_street"),
"aku_id": obj.get("aku_id"),
"fetched_at": obj.get("fetched_at"),
"id": obj.get("id"),
"institute": DFGInstituteInstitute.from_dict(obj["institute"]) if obj.get("institute") is not None else None,
"institute_category_key": obj.get("institute_category_key"),
"institute_category_label_de": obj.get("institute_category_label_de"),
"institute_category_label_en": obj.get("institute_category_label_en"),
"institute_id": obj.get("institute_id"),
"institute_name_de": obj.get("institute_name_de"),
"institute_name_en": obj.get("institute_name_en"),
"institute_postal_address": obj.get("institute_postal_address"),
"institute_type_key": obj.get("institute_type_key"),
"institute_type_label_de": obj.get("institute_type_label_de"),
"institute_type_label_en": obj.get("institute_type_label_en"),
"is_dissolved": obj.get("is_dissolved"),
"is_research_device": obj.get("is_research_device"),
"link": obj.get("link"),
"page_url": obj.get("page_url"),
"project_types_order": obj.get("project_types_order"),
"projects": [DFGInstituteProjectsInner.from_dict(_item) for _item in obj["projects"]] if obj.get("projects") is not None else None,
"root_id": obj.get("root_id"),
"root_name_de": obj.get("root_name_de"),
"root_name_en": obj.get("root_name_en")
})
return _obj
@@ -0,0 +1,130 @@
# coding: utf-8
"""
DFG Institutes API
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
The version of the OpenAPI document: 1.0.0
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, StrictBool, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class DFGInstituteInstitute(BaseModel):
"""
DFGInstituteInstitute
""" # noqa: E501
address_city: Optional[StrictStr] = None
address_country_de: Optional[StrictStr] = None
address_country_en: Optional[StrictStr] = None
address_hidden: Optional[StrictBool] = None
address_postal_code_city: Optional[StrictStr] = None
address_street: Optional[StrictStr] = None
aku_id: Optional[StrictInt] = None
institute_category_key: Optional[StrictStr] = None
institute_category_label_de: Optional[StrictStr] = None
institute_category_label_en: Optional[StrictStr] = None
institute_id: Optional[StrictInt] = None
institute_name_de: Optional[StrictStr] = None
institute_name_en: Optional[StrictStr] = None
institute_postal_address: Optional[StrictStr] = None
institute_type_key: Optional[StrictStr] = None
institute_type_label_de: Optional[StrictStr] = None
institute_type_label_en: Optional[StrictStr] = None
is_dissolved: Optional[StrictBool] = None
is_research_device: Optional[StrictBool] = None
root_id: Optional[StrictInt] = None
root_name_de: Optional[StrictStr] = None
root_name_en: Optional[StrictStr] = None
__properties: ClassVar[List[str]] = ["address_city", "address_country_de", "address_country_en", "address_hidden", "address_postal_code_city", "address_street", "aku_id", "institute_category_key", "institute_category_label_de", "institute_category_label_en", "institute_id", "institute_name_de", "institute_name_en", "institute_postal_address", "institute_type_key", "institute_type_label_de", "institute_type_label_en", "is_dissolved", "is_research_device", "root_id", "root_name_de", "root_name_en"]
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 DFGInstituteInstitute 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 DFGInstituteInstitute from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"address_city": obj.get("address_city"),
"address_country_de": obj.get("address_country_de"),
"address_country_en": obj.get("address_country_en"),
"address_hidden": obj.get("address_hidden"),
"address_postal_code_city": obj.get("address_postal_code_city"),
"address_street": obj.get("address_street"),
"aku_id": obj.get("aku_id"),
"institute_category_key": obj.get("institute_category_key"),
"institute_category_label_de": obj.get("institute_category_label_de"),
"institute_category_label_en": obj.get("institute_category_label_en"),
"institute_id": obj.get("institute_id"),
"institute_name_de": obj.get("institute_name_de"),
"institute_name_en": obj.get("institute_name_en"),
"institute_postal_address": obj.get("institute_postal_address"),
"institute_type_key": obj.get("institute_type_key"),
"institute_type_label_de": obj.get("institute_type_label_de"),
"institute_type_label_en": obj.get("institute_type_label_en"),
"is_dissolved": obj.get("is_dissolved"),
"is_research_device": obj.get("is_research_device"),
"root_id": obj.get("root_id"),
"root_name_de": obj.get("root_name_de"),
"root_name_en": obj.get("root_name_en")
})
return _obj
@@ -0,0 +1,120 @@
# coding: utf-8
"""
DFG Institutes API
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
The version of the OpenAPI document: 1.0.0
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, StrictBool, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class DFGInstituteProjectsInner(BaseModel):
"""
DFGInstituteProjectsInner
""" # noqa: E501
funding_end: Optional[StrictInt] = None
funding_period_de: Optional[StrictStr] = None
funding_period_en: Optional[StrictStr] = None
funding_start: Optional[StrictInt] = None
funding_type_de: Optional[StrictStr] = None
funding_type_en: Optional[StrictStr] = None
funding_type_key: Optional[StrictStr] = None
funding_type_sort: Optional[StrictStr] = None
institute_ref_id: Optional[StrictInt] = None
is_transfer_project: Optional[StrictBool] = None
project_id: Optional[StrictInt] = None
sort_criteria: Optional[StrictStr] = None
sort_year: Optional[StrictStr] = None
status_de: Optional[StrictStr] = None
status_en: Optional[StrictStr] = None
title_de: Optional[StrictStr] = None
title_en: Optional[StrictStr] = None
__properties: ClassVar[List[str]] = ["funding_end", "funding_period_de", "funding_period_en", "funding_start", "funding_type_de", "funding_type_en", "funding_type_key", "funding_type_sort", "institute_ref_id", "is_transfer_project", "project_id", "sort_criteria", "sort_year", "status_de", "status_en", "title_de", "title_en"]
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 DFGInstituteProjectsInner 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 DFGInstituteProjectsInner from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"funding_end": obj.get("funding_end"),
"funding_period_de": obj.get("funding_period_de"),
"funding_period_en": obj.get("funding_period_en"),
"funding_start": obj.get("funding_start"),
"funding_type_de": obj.get("funding_type_de"),
"funding_type_en": obj.get("funding_type_en"),
"funding_type_key": obj.get("funding_type_key"),
"funding_type_sort": obj.get("funding_type_sort"),
"institute_ref_id": obj.get("institute_ref_id"),
"is_transfer_project": obj.get("is_transfer_project"),
"project_id": obj.get("project_id"),
"sort_criteria": obj.get("sort_criteria"),
"sort_year": obj.get("sort_year"),
"status_de": obj.get("status_de"),
"status_en": obj.get("status_en"),
"title_de": obj.get("title_de"),
"title_en": obj.get("title_en")
})
return _obj
@@ -0,0 +1,159 @@
# coding: utf-8
"""
DFG Persons API
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
The version of the OpenAPI document: 1.0.0
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from datetime import datetime
from pydantic import BaseModel, ConfigDict, StrictBool, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.projects_dfg_v2.person.dfg_person_awards_inner import DFGPersonAwardsInner
from inse.models.projects_dfg_v2.person.dfg_person_person import DFGPersonPerson
from inse.models.projects_dfg_v2.person.dfg_person_projects_inner import DFGPersonProjectsInner
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class DFGPerson(BaseModel):
"""
DFGPerson
""" # noqa: E501
address_country_de: Optional[StrictStr] = None
address_country_en: Optional[StrictStr] = None
address_hidden: Optional[StrictBool] = None
address_postal_code_city: Optional[StrictStr] = None
address_street: Optional[StrictStr] = None
aku_id: Optional[StrictInt] = None
award_types_order: Optional[StrictStr] = None
awards: Optional[List[DFGPersonAwardsInner]] = None
fetched_at: Optional[datetime] = None
full_name: Optional[StrictStr] = None
id: Optional[StrictInt] = None
institute_id: Optional[StrictInt] = None
institute_name_de: Optional[StrictStr] = None
institute_name_en: Optional[StrictStr] = None
institute_postal_address: Optional[StrictStr] = None
is_deceased: Optional[StrictBool] = None
link: Optional[StrictStr] = None
orcid_id: Optional[StrictStr] = None
page_url: Optional[StrictStr] = None
person: Optional[DFGPersonPerson] = None
person_id: Optional[StrictInt] = None
project_types_order: Optional[StrictStr] = None
projects: Optional[List[DFGPersonProjectsInner]] = None
root_id: Optional[StrictInt] = None
root_name_de: Optional[StrictStr] = None
root_name_en: Optional[StrictStr] = None
__properties: ClassVar[List[str]] = ["address_country_de", "address_country_en", "address_hidden", "address_postal_code_city", "address_street", "aku_id", "award_types_order", "awards", "fetched_at", "full_name", "id", "institute_id", "institute_name_de", "institute_name_en", "institute_postal_address", "is_deceased", "link", "orcid_id", "page_url", "person", "person_id", "project_types_order", "projects", "root_id", "root_name_de", "root_name_en"]
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 DFGPerson 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 awards (list)
_items = []
if self.awards:
for _item_awards in self.awards:
if _item_awards:
_items.append(_item_awards.to_dict())
_dict['awards'] = _items
# override the default output from pydantic by calling `to_dict()` of person
if self.person:
_dict['person'] = self.person.to_dict()
# override the default output from pydantic by calling `to_dict()` of each item in projects (list)
_items = []
if self.projects:
for _item_projects in self.projects:
if _item_projects:
_items.append(_item_projects.to_dict())
_dict['projects'] = _items
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of DFGPerson from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"address_country_de": obj.get("address_country_de"),
"address_country_en": obj.get("address_country_en"),
"address_hidden": obj.get("address_hidden"),
"address_postal_code_city": obj.get("address_postal_code_city"),
"address_street": obj.get("address_street"),
"aku_id": obj.get("aku_id"),
"award_types_order": obj.get("award_types_order"),
"awards": [DFGPersonAwardsInner.from_dict(_item) for _item in obj["awards"]] if obj.get("awards") is not None else None,
"fetched_at": obj.get("fetched_at"),
"full_name": obj.get("full_name"),
"id": obj.get("id"),
"institute_id": obj.get("institute_id"),
"institute_name_de": obj.get("institute_name_de"),
"institute_name_en": obj.get("institute_name_en"),
"institute_postal_address": obj.get("institute_postal_address"),
"is_deceased": obj.get("is_deceased"),
"link": obj.get("link"),
"orcid_id": obj.get("orcid_id"),
"page_url": obj.get("page_url"),
"person": DFGPersonPerson.from_dict(obj["person"]) if obj.get("person") is not None else None,
"person_id": obj.get("person_id"),
"project_types_order": obj.get("project_types_order"),
"projects": [DFGPersonProjectsInner.from_dict(_item) for _item in obj["projects"]] if obj.get("projects") is not None else None,
"root_id": obj.get("root_id"),
"root_name_de": obj.get("root_name_de"),
"root_name_en": obj.get("root_name_en")
})
return _obj

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