Compare commits

..
Author SHA1 Message Date
genja 7ce86d2f19 added eu project calls script to the background jobs
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-12-01 01:55:25 +01:00
genja 59fd8cd17f feat(scripts): add UDE publications topic model training and prediction 2026-11-30 17:19:09 +01:00
genja 93e1148bea feat(scripts): add UDE publications Elasticsearch dataset builder 2026-11-30 17:18:52 +01:00
15 changed files with 3738 additions and 0 deletions
+5
View File
@@ -29,3 +29,8 @@ llm_evaluations/bio_generation/.venv
# Runtime checkpoint for the UDE OrgMiner verified-person uploader.
service/scripts/upload_orgminer_verified_persons_ude/orgminer_verified_persons_ude_progress.json
service/scripts/upload_orgminer_verified_persons_ude/orgminer_verified_persons_ude_progress.json.tmp
# Runtime progress for the UDE publications dataset builder.
service/scripts/ude_publications_dataset/data_all_ude/
# Training cache and generated artifacts for the UDE publications topic model.
service/scripts/ude_publications_hdbscan/.cache/
service/scripts/ude_publications_hdbscan/model/
+132
View File
@@ -0,0 +1,132 @@
# EU Project Calls Fetcher
Fetches Horizon Europe funding opportunities from the European Commission Funding & Tenders API and uploads them into Elasticsearch.
## Install
```bash
pip install requests elasticsearch
```
## Step 1: Fetch Calls
Execute:
```bash
python fetch_calls.py
```
Output:
```text
eu_tenders_raw.json
```
### Query Filters
Only calls matching the following criteria are fetched:
* Status:
* Forthcoming
* Open for Submission
* Type of Grant Call:
* Direct calls for proposals (issued by the EU)
* Programme:
* Horizon Europe (2021–2027)
* Programme Part:
* Global Challenges and European Industrial Competitiveness
The filter corresponds to the url: https://ec.europa.eu/info/funding-tenders/opportunities/portal/screen/opportunities/calls-for-proposals?order=DESC&pageNumber=1&pageSize=50&sortBy=startDate&isExactMatch=true&type=1&status=31094502,31094501&programmePart=43108557,43118846,43118971,43120193,43120821,43121563,43108541&frameworkProgramme=43108390
## Step 2: Upload to Elasticsearch
The uploader reads the connection from the environment (the background job
runner injects `ELASTICSEARCH_INSE_URL` and `ELASTICSEARCH_INSE_API_KEY`).
Override the target index with `EU_PROJECT_CALLS_INDEX`.
Execute:
```bash
python upload_calls.py
```
Use `--fresh` to delete all existing documents in the target index, then refill
it from the fetched calls. The index and its mapping must already exist:
```bash
python upload_calls.py --fresh
```
Input:
```text
eu_tenders_raw.json
```
Output:
```text
Elasticsearch index
```
Default index:
```text
eu_project_calls
```
Documents are keyed by the call identifier, so re-runs overwrite instead of
duplicating.
Upload log:
```text
eu_upload_log.json
```
## Indexed Fields
```text
id
title
link
state
programm
call
work_programm_part
description
type_of_action
type_of_mga
open_date
deadline_date
deadline_model
full_title
agr_number
acronym
keywords
```
## Run as a Background Job
The image at `service/scripts/jobs-image/eu-project-calls` fetches and uploads in
one run:
```bash
docker build -f service/scripts/jobs-image/eu-project-calls/Dockerfile \
-t docker.nes.uni-due.de/inse/jobs/eu-project-calls:latest .
docker push docker.nes.uni-due.de/inse/jobs/eu-project-calls:latest
```
Then create a job in the Jobs UI with that image. The runner injects the
Elasticsearch credentials for registry images. Set the job's **Command** to
`--fresh` to clear and refill the existing index on every run; leave it empty to
upsert into the existing index. The index and its mapping must already exist.
## Data Source
European Commission Funding & Tenders Portal Search API
https://api.tech.ec.europa.eu/search-api/
@@ -0,0 +1,83 @@
import json
import os
import requests
import time
# === CONFIG ===
PAGE_SIZE = 50
OUTPUT_FILE = os.getenv("EU_PROJECT_CALLS_INPUT_FILE", "eu_tenders_raw.json")
url = "https://api.tech.ec.europa.eu/search-api/prod/rest/search"
sort_data = {"order": "DESC", "field": "startDate"}
query_data = {
"bool": {
"must": [
{"terms": {"type": ["1"]}},
{"terms": {"status": ["31094502", "31094501"]}},
{"terms": {"DATASOURCE": ["SEDIA"]}},
{"terms": {"frameworkProgramme": ["43108390"]}},
{"terms": {"programmeDivision": ["43108557", "43118846", "43118971", "43120193", "43120821", "43121563", "43108541"]}},
{"terms": {"language": ["en"]}},
]
}
}
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
"Accept": "application/json, text/plain, */*",
"Cache-Control": "No-Cache",
"X-Requested-With": "XMLHttpRequest",
"Origin": "https://ec.europa.eu",
"Referer": "https://ec.europa.eu/",
}
# === FETCH ===
all_results = []
page = 1
fetch_failed = False
while True:
params = {
"apiKey": "SEDIA",
"text": "***",
"pageSize": PAGE_SIZE,
"pageNumber": page
}
files = {
"sort": ("blob", json.dumps(sort_data), "application/json"),
"query": ("blob", json.dumps(query_data), "application/json"),
"languages": ("blob", json.dumps(["en"]), "application/json"),
}
try:
response = requests.post(url, params=params, files=files, headers=headers, timeout=30)
response.raise_for_status()
data = response.json()
except Exception as e:
print(f"Error on page {page}: {e}")
fetch_failed = True
break
results = data.get("results", [])
total = data.get("totalResults", 0)
all_results.extend(results)
print(f"Page {page}: got {len(results)} results — total so far: {len(all_results)}/{total}")
if len(all_results) >= total or len(results) < PAGE_SIZE:
break
page += 1
time.sleep(0.5)
print(f"\nDone. Total fetched: {len(all_results)}")
# === SAVE ===
with open(OUTPUT_FILE, "w", encoding="utf-8") as f:
json.dump(all_results, f, ensure_ascii=False, indent=2)
print(f"Saved to {OUTPUT_FILE}")
# Fail the job (and skip the upload) instead of reporting a partial fetch as success.
if fetch_failed:
raise SystemExit(1)
@@ -0,0 +1,155 @@
import argparse
import json
import os
import traceback
from datetime import datetime
from elasticsearch import Elasticsearch
# config — the background job runner injects ELASTICSEARCH_INSE_* for registry images.
ES_URL = os.getenv("ELASTICSEARCH_INSE_URL", "http://localhost:9200")
ES_API_KEY = os.getenv("ELASTICSEARCH_INSE_API_KEY")
es = Elasticsearch(
ES_URL,
api_key=ES_API_KEY or None,
request_timeout=60,
max_retries=5,
retry_on_timeout=True,
)
index_name = os.getenv("EU_PROJECT_CALLS_INDEX", "eu_project_calls")
INPUT_FILE = os.getenv("EU_PROJECT_CALLS_INPUT_FILE", "eu_tenders_raw.json")
LOG_FILE = os.getenv("EU_PROJECT_CALLS_LOG_FILE", "eu_upload_log.json")
# helpers
def get(metadata, field):
val = metadata.get(field)
if isinstance(val, list):
return val[0] if val else ""
return val or ""
def get_state(metadata):
val = metadata.get("status")
if isinstance(val, list):
if val[0]== "31094502":
return "open for submission"
if val[0] == "31094501":
return "forthcoming"
if val[0] == "31094503":
return "closed"
return val or ""
def parse_date(date_str):
if not date_str:
return None
try:
return datetime.strptime(date_str[:10], "%Y-%m-%d").strftime("%d.%m.%Y")
except Exception:
return None
def map_result(result):
m = result.get("metadata", {})
return {
"id": get(m, "identifier"),
"title": get(m, "title"),
"link": result.get("url") or get(m, "url"),
"state": get_state(m),
"programm": get(m, "frameworkProgramme"),
"call": get(m, "callIdentifier"),
"work_programm_part": get(m, "programmeDivision"),
"description": get(m, "descriptionByte"),
"type_of_action": get(m, "typesOfAction"),
"type_of_mga": get(m, "typeOfMGAs"),
"open_date": parse_date(get(m, "startDate")),
"deadline_date": parse_date(get(m, "deadlineDate")),
"deadline_model": get(m, "deadlineModel"),
"full_title": get(m, "callTitle"),
"agr_number": get(m, "callccm2Id"),
"acronym": get(m, "projectAcronym"),
"funding": "",
"participation_time": "",
"topic": "",
"agr_number": get(m, "ccm2Id"),
"keywords": m.get("keywords",[])
}
# elastic setup
def clear_index():
# The index and its mapping are managed outside this script; --fresh only
# removes the documents so the index can be refilled.
es.delete_by_query(
index=index_name,
body={"query": {"match_all": {}}},
conflicts="proceed",
refresh=True,
)
print(f"Cleared all documents from INDEX {index_name} (--fresh)...")
# logs
def load_log():
if os.path.exists(LOG_FILE):
with open(LOG_FILE, 'r', encoding='utf-8') as f:
return json.load(f)
log = {"done": [], "failed": []}
with open(LOG_FILE, 'w', encoding='utf-8') as f:
json.dump(log, f)
return log
def save_log(log):
with open(LOG_FILE, 'w', encoding='utf-8') as f:
json.dump(log, f, indent=2)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Upload EU project calls to Elasticsearch.")
parser.add_argument(
"--fresh",
action="store_true",
help="Delete the target index first, then recreate and refill it.",
)
args = parser.parse_args()
print("Starting upload...")
if args.fresh:
clear_index()
with open(INPUT_FILE, 'r', encoding='utf-8') as f:
raw_results = json.load(f)
log = load_log()
if args.fresh:
log = {"done": [], "failed": []}
done_set = set(log["done"])
total = len(raw_results)
uploaded = 0
failed = 0
for i, result in enumerate(raw_results):
try:
doc = map_result(result)
identifier = doc["id"]
if not identifier:
raise ValueError("missing call identifier")
# Keyed on the call identifier so scheduled re-runs overwrite
# instead of duplicating every document.
es.index(index=index_name, id=identifier, body=doc)
log["done"].append(identifier)
done_set.add(identifier)
uploaded += 1
print(f" [{i+1}/{total}] ✓ {identifier}")
except Exception as e:
identifier = result.get("metadata", {}).get("identifier", ["unknown"])[0]
print(f" [{i+1}/{total}] ✗ Failed {identifier}: {e}")
traceback.print_exc()
log["failed"].append(identifier)
failed += 1
# save log every 10 items
if i % 10 == 0:
save_log(log)
save_log(log)
print(f"\nDone. Uploaded: {uploaded} | Failed: {failed}")
+1
View File
@@ -83,6 +83,7 @@ differ only by their `command`.
| 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 |
| UDE OrgMiner Verified Persons | `jobs/orgminer-verified-persons-ude` | `upload_orgminer_verified_persons_ude.py --progress-file /state/orgminer_verified_persons_ude_progress.json` | Writes `orgminer_verified_persons_ude`; image-scoped NES creds; persistent checkpoint |
| EU Project Calls | `jobs/eu-project-calls` | `fetch_calls.py && upload_calls.py` | Horizon Europe calls; writes `eu_project_calls`; `--fresh` clears+refills 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
@@ -0,0 +1,25 @@
# EU project calls fetcher + uploader (Horizon Europe -> eu_project_calls).
# Build from the repo root:
# docker build -f service/scripts/jobs-image/eu-project-calls/Dockerfile \
# -t docker.nes.uni-due.de/inse/jobs/eu-project-calls:latest .
#
# Fetches the EC Funding & Tenders API, then uploads to Elasticsearch. The
# runner injects ELASTICSEARCH_INSE_URL/API_KEY for registry images.
FROM python:3.13-slim
WORKDIR /app
ENV PYTHONUNBUFFERED=1
COPY service/scripts/jobs-image/eu-project-calls/requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Only the scripts: the local raw JSON (15 MB) and upload log stay out of the image.
COPY service/scripts/eu-project-calls/fetch_calls.py \
service/scripts/eu-project-calls/upload_calls.py \
./service/scripts/eu-project-calls/
WORKDIR /app/service/scripts/eu-project-calls
# One run fetches all calls, then uploads them (keyed by call id, so re-runs
# overwrite instead of duplicating). The job's command field is appended here
# and forwarded to the uploader, e.g. --fresh to rebuild the index from scratch.
ENTRYPOINT ["sh", "-c", "python fetch_calls.py && exec python upload_calls.py \"$@\"", "--"]
@@ -0,0 +1,2 @@
requests~=2.32
elasticsearch>=7.17,<8
@@ -0,0 +1,165 @@
# UDE publications dataset (Elasticsearch)
Builds a publication-level dataset of **active UDE persons** and indexes it into
an Elasticsearch index on the INSE cluster — one document per publication.
## What it builds
1. Finds active UDE authors in `openalex-authors` (NES) with
`build_active_institution_membership_query("I62318514")` (affiliation year ≥
current UTC year − 2).
2. Loads `orgminer_verified_persons_ude` (INSE) as a lookup by OpenAlex ID. An
author found there has `verified: true` plus verified organization, faculty,
chair and institute metadata.
3. Splits the active authors into batches (default 50). For each batch it fetches
the publications from `openalex-works*`, builds one document per publication,
bulk-indexes them, and only then records the batch as done.
4. Creates the output index (default `ude_oa_works_dataset`) on the first run.
A fresh run requires the index **not** to exist. On a resumed run the index must
exist; progress files in `--output-dir` identify the run. To start over: delete
the index on INSE **and** pass `--reset-progress`.
## Requirements
Run from the repository root with the service environment:
```bash
python service/scripts/ude_publications_dataset/create_ude_publications_dataset.py
```
Required environment variables (normally in `service/src/main/inse/.env`):
```text
ELASTICSEARCH_URL
ELASTICSEARCH_API_KEY
ELASTICSEARCH_INSE_URL
ELASTICSEARCH_INSE_API_KEY
```
## Usage
Full run:
```bash
python service/scripts/ude_publications_dataset/create_ude_publications_dataset.py
```
Restrict to a minimum year / test with two batches:
```bash
python service/scripts/ude_publications_dataset/create_ude_publications_dataset.py \
--year-from 2015 --max-batches 2
```
Useful options:
```text
--output-dir DIR # default: service/scripts/ude_publications_dataset/data_all_ude
--output-index NAME # default: ude_oa_works_dataset
--year-from 0 # default: all years
--batch-size 50 # authors fetched/indexed per batch and checkpoint
--limit-persons N # use at most N active UDE authors (testing)
--max-batches N # process at most N new batches in this run
--reset-progress # delete local progress (also delete the index first)
```
Interrupted runs (Ctrl+C, crash, network loss) resume by rerunning the same
command: finished batches are skipped, the first unfinished batch is redone.
Redoing is safe because each document has a fixed `_id`.
## Index document
Each document is keyed by its short OpenAlex work ID and contains:
```text
id, doi, title, abstract, genre, type, language, publication_year,
publication_date, cited_by_count,
ude_authors, other_ude_authors, other_authors,
primary_topic_id, primary_topic_name, topics, keywords, keyword_names,
verified_person_ids, organizations, faculties, chairs, institutes,
organization_types, organization_levels, org_hierarchy_paths,
oa_organization_ids, work_institution_ids, work_institution_names,
has_ude_affiliation
```
### Author arrays
Every author of the publication is kept, split into three arrays (authorship
order within each):
- `ude_authors` — authors in the active UDE cohort (verified or not).
- `other_ude_authors` — not in the active cohort, but either found in the
verified-persons index or affiliated with UDE (`I62318514`) on this
publication (verified or not).
- `other_authors` — everyone else.
Each entry is a full author object:
```python
{
"author_id": "A5034736701",
"name": "Florian Ziel",
"raw_name": "F. Ziel",
"orcid": "https://orcid.org/...",
"position": "last",
"is_corresponding": False,
"institutions": [...], # merged from the OpenAlex author document
"institution_ids": ["I62318514"],
"raw_affiliation_strings": ["..."],
"countries": ["DE"],
"verified": True, # found in orgminer_verified_persons_ude
"organizations": ["Umweltökonomik, ..."],
"faculties": ["Wirtschaftswissenschaften"],
"chairs": ["Umweltökonomik, ..."], # "Lehrstühle"/"chairs"
"institutes": [], # "Institut*"/"institutes"
}
```
The three arrays are mapped as plain `object` fields (not `nested`), so large
publications cannot hit Elasticsearch's nested-document limit. The trade-off is
that ES flattens arrays of objects: you can filter by a field value, but not
require two fields to belong to the same array element. Publication-level lists
(`organizations`, `faculties`, `chairs`, `institutes`, `verified_person_ids`, ...)
are unions over the verified authors of the publication.
### Author-level institutions
For every publication, the authors are looked up in `openalex-authors` (NES) with
a `terms` query on their IDs (one batched lookup per batch; the cache is dropped
after the batch to bound memory). From each
author document, `last_known_institutions` and `affiliations[].institution` are
merged by OpenAlex institution ID into `institutions`, following the same
shape as the verified-persons upload:
```python
{
"id": "I62318514",
"openalex_url": "https://openalex.org/I62318514",
"display_name": "University of Duisburg-Essen",
"ror": "https://ror.org/...",
"country_code": "DE",
"type": "education",
"lineage": ["https://openalex.org/I62318514", "..."],
"years": [2019, 2020, 2024], # union of all affiliation years
"last_known": True,
}
```
Last-known institutions come first; `institution_ids` is the deduplicated
short-ID list. This replaces the work-level institution array on each author;
work-level institution IDs/names remain on the publication itself as
`work_institution_ids` / `work_institution_names`. If an author is not found in
the author index, both arrays are empty.
`topics` and `keywords` keep the full OpenAlex objects (`id`, `display_name`,
`score`, plus `subfield`/`field`/`domain` where present), deduplicated by display
name and ordered by score; IDs are shortened. `keyword_names` is the same list
as plain display-name strings. `topics` and `keywords` are plain `object` fields.
## Notes
- The active cohort shifts each January as the year cutoff changes.
- Works already indexed are not rebuilt on a resumed run; verified-index changes
only appear after a full restart.
- There are no LLM keywords, embeddings or pickle outputs.
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,4 @@
pandas>=2.2
httpx>=0.27
python-dotenv>=1.0
pydantic-settings>=2.2
@@ -0,0 +1,501 @@
"""Tests for the UDE publications dataset builder."""
from __future__ import annotations
import asyncio
import importlib.util
import json
import sys
from pathlib import Path
from types import SimpleNamespace
import pytest
SCRIPT_PATH = Path(__file__).with_name("create_ude_publications_dataset.py")
_SPEC = importlib.util.spec_from_file_location(
"create_ude_publications_dataset", SCRIPT_PATH
)
assert _SPEC and _SPEC.loader
dataset = importlib.util.module_from_spec(_SPEC)
sys.modules[_SPEC.name] = dataset
_SPEC.loader.exec_module(dataset)
UDE_IDS = ["A1", "A2"]
def _person(openalex_id: str = "A1", org: str = "Applied Analytical Chemistry"):
person = dataset.PersonAggregate(openalex_id=openalex_id)
person.names = {"Alice" if openalex_id == "A1" else "Carol"}
person.org_names = {org}
person.faculties = {"Chemie"}
person.organization_types = {"Lehrstühle"}
person.organization_levels = {"leaf"}
person.org_hierarchy_paths = {("Chemie", "Lehrstühle", org)}
person.oa_organization_ids = {"I62318514"}
person.group_names = {org}
person.institute_names = {"Institut für Chemie"}
return person
def _work() -> dict:
return {
"id": "https://openalex.org/W1",
"doi": "https://doi.org/10.1/example",
"title": "Test title",
"abstract": "Test abstract",
"type": "article",
"language": "en",
"publication_year": 2024,
"cited_by_count": 3,
"primary_topic": {
"id": "https://openalex.org/T1",
"display_name": "Topic One",
"score": 0.9,
},
"topics": [
{
"id": "https://openalex.org/T1",
"display_name": "Topic One",
"score": 0.9,
"subfield": {
"id": "https://openalex.org/subfields/2505",
"display_name": "Materials Chemistry",
},
},
{"id": "https://openalex.org/T2", "display_name": "Topic Two", "score": 0.8},
],
"keywords": [
{"id": "https://openalex.org/K1", "display_name": "machine learning", "score": 0.9},
{"id": "https://openalex.org/K2", "display_name": "Machine Learning", "score": 0.8},
{"id": "https://openalex.org/K3", "display_name": "sensors", "score": 0.7},
],
"authorships": [
{
"author": {
"id": "https://openalex.org/A1",
"display_name": "Alice",
"orcid": "https://orcid.org/0000-0001-0000-0001",
},
"author_position": "first",
"is_corresponding": True,
"raw_author_name": "A. Alice",
"raw_affiliation_strings": ["University of Duisburg-Essen"],
"countries": ["DE"],
"institutions": [
{
"id": "https://openalex.org/I62318514",
"display_name": "University of Duisburg-Essen",
"type": "education",
"country_code": "DE",
"ror": "https://ror.org/04mz5ra38",
}
],
},
{
"author": {"id": "https://openalex.org/A2", "display_name": "Bob"},
"author_position": "middle",
"institutions": [],
},
{
"author": {"id": "https://openalex.org/A3", "display_name": "Carol"},
"author_position": "last",
"institutions": [],
},
{
"author": {"id": "https://openalex.org/A4", "display_name": "Dave"},
"author_position": "last",
"institutions": [
{
"id": "https://openalex.org/I2",
"display_name": "Other University",
}
],
},
],
}
def _people() -> dict:
return {
"a1": _person("A1"),
"a3": _person("A3", org="Institut für Chemie"),
}
def test_normalize_openalex_id() -> None:
assert dataset.normalize_openalex_id("https://openalex.org/A1") == "A1"
assert dataset.normalize_openalex_id("A1") == "A1"
assert dataset.normalize_openalex_id(None) is None
def test_flatten_named_items_sorts_and_deduplicates() -> None:
items = [
{"display_name": "Beta", "score": 0.4},
{"display_name": "alpha", "score": 0.9},
{"display_name": "Alpha", "score": 0.8},
"gamma",
]
assert dataset.flatten_named_items(items) == ["alpha", "Beta", "gamma"]
def test_named_item_objects_keep_full_objects_and_deduplicate() -> None:
items = [
{"id": "https://openalex.org/K1", "display_name": "Beta", "score": 0.4, "extra": 1},
{"id": "https://openalex.org/K2", "display_name": "alpha", "score": 0.9},
{"id": "https://openalex.org/K3", "display_name": "Alpha", "score": 0.8},
]
objects = dataset.named_item_objects(items)
assert [item["id"] for item in objects] == ["K2", "K1"]
assert objects[1]["extra"] == 1
def test_build_works_query_contains_filters() -> None:
query = dataset.build_works_query(["https://openalex.org/A1"], 2020)
filters = query["bool"]["filter"]
assert {"exists": {"field": "title"}} in filters
assert {"range": {"publication_year": {"gte": 2020}}} in filters
assert query["bool"]["must_not"] == [
{"term": {"is_retracted": True}},
{"term": {"is_paratext": True}},
]
def test_load_ude_persons_uses_active_membership_query(
monkeypatch: pytest.MonkeyPatch,
) -> None:
calls: list[dict] = []
async def fake_scan(**kwargs: object):
calls.append(kwargs)
yield {"_source": {"id": "https://openalex.org/A1"}}
yield {"_source": {"id": "A2"}}
monkeypatch.setattr(dataset.elasticsearch, "scan", fake_scan)
authors = asyncio.run(dataset.load_ude_persons())
assert authors == ["A1", "A2"]
assert calls[0]["index"] == "openalex-authors"
assert calls[0]["cluster"] == "nes"
assert calls[0]["query"] == dataset.build_active_institution_membership_query(
dataset.UDE_INSTITUTION_ID
)
def test_build_document_splits_authors_into_three_arrays() -> None:
row = dataset.build_document(_people(), _work(), UDE_IDS)
assert row is not None
assert [a["author_id"] for a in row["ude_authors"]] == ["A1", "A2"]
assert [a["author_id"] for a in row["other_ude_authors"]] == ["A3"]
assert [a["author_id"] for a in row["other_authors"]] == ["A4"]
alice = row["ude_authors"][0]
assert alice["name"] == "Alice"
assert alice["verified"] is True
assert alice["organizations"] == ["Applied Analytical Chemistry"]
assert alice["faculties"] == ["Chemie"]
assert alice["chairs"] == ["Applied Analytical Chemistry"]
assert alice["institutes"] == ["Institut für Chemie"]
assert alice["institutions"] == [] # no author document in this test
bob = row["ude_authors"][1]
assert bob["verified"] is False
assert bob["organizations"] == []
carol = row["other_ude_authors"][0]
assert carol["verified"] is True
assert carol["organizations"] == ["Institut für Chemie"]
dave = row["other_authors"][0]
assert dave["verified"] is False
assert dave["organizations"] == []
assert "authors" not in row
assert "authors_structured" not in row
assert "researchers" not in row
def test_build_document_other_ude_author_without_verification() -> None:
work = _work()
# Carol drops out of the verified index but keeps her UDE institution.
work["authorships"][2]["institutions"] = [
{"id": "https://openalex.org/I62318514", "display_name": "University of Duisburg-Essen"}
]
row = dataset.build_document({}, work, UDE_IDS)
assert [a["author_id"] for a in row["other_ude_authors"]] == ["A3"]
assert row["other_ude_authors"][0]["verified"] is False
def test_build_document_keeps_publication_metadata() -> None:
row = dataset.build_document(_people(), _work(), UDE_IDS)
assert row["id"] == "https://openalex.org/W1"
assert row["title"] == "Test title"
assert row["abstract"] == "Test abstract"
assert row["publication_year"] == 2024
assert row["cited_by_count"] == 3
assert [topic["id"] for topic in row["topics"]] == ["T1", "T2"]
assert row["topics"][0]["subfield"]["display_name"] == "Materials Chemistry"
assert [keyword["id"] for keyword in row["keywords"]] == ["K1", "K3"]
assert row["keyword_names"] == ["machine learning", "sensors"]
assert row["verified_person_ids"] == ["A1", "A3"]
assert row["organizations"] == ["Applied Analytical Chemistry", "Institut für Chemie"]
assert bool(row["has_ude_affiliation"]) is True
def test_build_document_skips_empty_or_out_of_range_works() -> None:
assert dataset.build_document({}, {"title": None}, UDE_IDS) is None
assert (
dataset.build_document({}, _work(), UDE_IDS, year_from=2025) is None
)
assert dataset.build_document({}, _work(), UDE_IDS, year_from=2024) is not None
def test_build_documents_returns_all_works(monkeypatch: pytest.MonkeyPatch) -> None:
async def no_details(ids): # pragma: no cover - no network in tests
return {}
monkeypatch.setattr(dataset, "fetch_author_details", no_details)
older = _work()
older["id"] = "https://openalex.org/W0"
older["publication_year"] = 2000
documents = asyncio.run(
dataset.build_documents({}, {"W0": older, "W1": _work()}, UDE_IDS)
)
assert {doc_id for doc_id, _ in documents} == {"W0", "W1"}
def test_extract_openalex_institutions_merges_by_id() -> None:
author = dataset.Author.from_dict(
{
"id": "https://openalex.org/A1",
"last_known_institutions": [
{
"id": "https://openalex.org/I1",
"display_name": "UDE",
"ror": "https://ror.org/1",
"type": "education",
"lineage": ["https://openalex.org/I1"],
}
],
"affiliations": [
{
"institution": {
"id": "I1",
"display_name": "Universität Duisburg-Essen",
"country_code": "DE",
},
"years": [2023, 2024, 2023],
},
{
"institution": {"id": "https://openalex.org/I2", "display_name": "Other"},
"years": [1999],
},
],
}
)
institutions = dataset.extract_openalex_institutions(author)
assert [item["id"] for item in institutions] == ["I1", "I2"]
first = institutions[0]
assert first["last_known"] is True
assert first["display_name"] == "UDE"
assert first["country_code"] == "DE"
assert first["years"] == [2023, 2024]
assert first["lineage"] == ["https://openalex.org/I1"]
assert first["openalex_url"] == "https://openalex.org/I1"
assert dataset.openalex_institution_ids(institutions) == ["I1", "I2"]
def test_fetch_author_details_uses_terms_query(monkeypatch: pytest.MonkeyPatch) -> None:
calls: list[dict] = []
async def fake_search(**kwargs: object) -> dict:
calls.append(kwargs)
return {
"hits": {
"hits": [
{
"_source": {
"id": "https://openalex.org/A1",
"last_known_institutions": [
{"id": "https://openalex.org/I1", "display_name": "UDE"}
],
"affiliations": [],
}
}
]
}
}
monkeypatch.setattr(dataset.elasticsearch, "search", fake_search)
authors = asyncio.run(dataset.fetch_author_details(["a1"]))
assert list(authors) == ["a1"]
assert calls[0]["index"] == "openalex-authors"
assert calls[0]["query"] == {"terms": {"id": ["https://openalex.org/A1"]}}
assert calls[0]["source"] == dataset.AUTHOR_SOURCE_FIELDS
assert authors["a1"].last_known_institutions[0].display_name == "UDE"
def test_build_documents_fetches_wanted_authors_once(
monkeypatch: pytest.MonkeyPatch,
) -> None:
queried: list[set[str]] = []
async def fake_fetch(ids):
queried.append(set(ids))
return {
author_id.casefold(): dataset.Author.from_dict(
{"id": f"https://openalex.org/{author_id}"}
)
for author_id in ids
}
monkeypatch.setattr(dataset, "fetch_author_details", fake_fetch)
first = _work()
second = _work()
second["id"] = "https://openalex.org/W2"
asyncio.run(dataset.build_documents({}, {"W1": first, "W2": second}, UDE_IDS))
# Only the UDE cohort is fetched (no verified/UDE-affiliated authors here);
# the shared cache means the second work does not query again.
assert queried == [{"A1", "A2"}]
def test_author_arrays_carry_merged_institution_fields() -> None:
author = dataset.Author.from_dict(
{
"id": "https://openalex.org/A1",
"last_known_institutions": [
{"id": "https://openalex.org/I1", "display_name": "UDE"}
],
"affiliations": [
{
"institution": {"id": "https://openalex.org/I2", "display_name": "Other"},
"years": [2020],
}
],
}
)
row = dataset.build_document(
_people(), _work(), UDE_IDS, {"a1": author}
)
alice = row["ude_authors"][0]
assert [item["id"] for item in alice["institutions"]] == ["I1", "I2"]
assert alice["institution_ids"] == ["I1", "I2"]
assert alice["institutions"][0]["last_known"] is True
assert alice["institutions"][1]["years"] == [2020]
assert "oa_institutions" not in alice
for group in ("other_ude_authors", "other_authors"):
for entry in row[group]:
assert entry["institutions"] == []
assert entry["institution_ids"] == []
def test_add_person_context_accepts_legacy_organization_field() -> None:
record = dataset.PersonAggregate(openalex_id="A1")
dataset._add_person_context(
record,
{
"name": "Alice",
"organization": "Legacy Org",
"faculty": "Chemie",
"organization_type": "Lehrstühle",
"organization_level": "leaf",
"oa_organization_ids": ["I1"],
},
)
assert record.org_names == {"Legacy Org"}
assert record.group_names == {"Legacy Org"}
dataset._add_person_context(record, {"org_name": "New Org"})
assert record.org_names == {"Legacy Org", "New Org"}
def test_batch_hash_is_order_independent() -> None:
assert dataset.batch_hash(["b", "a"]) == dataset.batch_hash(["a", "b"])
def test_source_fingerprint_changes_with_work_fields(
monkeypatch: pytest.MonkeyPatch,
) -> None:
digest = dataset.source_fingerprint(None)
monkeypatch.setattr(
dataset, "WORK_SOURCE_FIELDS", [*dataset.WORK_SOURCE_FIELDS, "new_field"]
)
assert dataset.source_fingerprint(None) != digest
def test_progress_roundtrip_and_year_guard(tmp_path: Path) -> None:
progress = dataset.Progress.load(tmp_path, None, "idx")
progress.record_batch("digest", ["W1", "W2"])
reloaded = dataset.Progress.load(tmp_path, None, "idx")
assert reloaded.completed_batches == {"digest"}
assert reloaded.indexed_ids == {"W1", "W2"}
assert reloaded.has_progress is True
with pytest.raises(SystemExit):
dataset.Progress.load(tmp_path, 2020, "idx")
def test_reset_progress_removes_files(tmp_path: Path) -> None:
progress = dataset.Progress.load(tmp_path, None, "idx")
progress.record_batch("digest", ["W1"])
dataset.reset_progress(tmp_path)
assert not (tmp_path / dataset.PROGRESS_FILENAME).exists()
assert not (tmp_path / dataset.INDEXED_IDS_FILENAME).exists()
def test_create_index_sends_mapping(monkeypatch: pytest.MonkeyPatch) -> None:
calls: list[tuple] = []
async def fake_request(*args: object, **kwargs: object) -> object:
calls.append((args, kwargs))
return SimpleNamespace(json=lambda: {})
monkeypatch.setattr(dataset.elasticsearch, "_request", fake_request)
asyncio.run(dataset.create_index("ude_publications"))
args, kwargs = calls[0]
assert args[0] == "PUT"
assert args[2] == "ude_publications"
assert kwargs["json_body"] == {"mappings": dataset.INDEX_MAPPING}
assert dataset.INDEX_MAPPING["properties"]["ude_authors"]["type"] == "object"
assert (
dataset.AUTHOR_PROPERTIES["institutions"]["type"] == "object"
)
assert "nested" not in json.dumps(dataset.INDEX_MAPPING)
def test_bulk_chunks_writes_ndjson(monkeypatch: pytest.MonkeyPatch) -> None:
chunks = list(dataset.bulk_chunks("idx", [("W1", {"title": "One"}), ("W2", {"title": "Two"})]))
assert len(chunks) == 1
body = "".join(text for _, _, text in chunks[0])
lines = body.splitlines()
assert len(lines) == 4
assert json.loads(lines[0]) == {"index": {"_index": "idx", "_id": "W1"}}
assert json.loads(lines[1]) == {"title": "One"}
assert json.loads(lines[2])["index"]["_id"] == "W2"
def test_bulk_index_reports_failures(monkeypatch: pytest.MonkeyPatch) -> None:
async def fake_send(chunk, semaphore):
return chunk, {
"errors": True,
"items": [{"index": {"status": 400, "error": "bad"}}],
}
monkeypatch.setattr(dataset, "_send_chunk", fake_send)
with pytest.raises(SystemExit, match="Failed to index 1 publications"):
asyncio.run(dataset.bulk_index("idx", [("W1", {})]))
@@ -0,0 +1,123 @@
# UDE publications topic model (BERTopic + HDBSCAN)
Trains a topic model on the `keyword_names` of the
`ude_openalex_works_dataset` index (INSE) and provides a `predict.py` that
returns the organizations and persons of the most similar publications.
## Data model
Authors are the single source of truth:
- `persons` come from `ude_authors` and `other_ude_authors`.
- `institutions` are the OpenAlex institutions referenced by those persons'
profiles (never the work-level institution fields).
- `orgminer_faculties`, `orgminer_chairs`, `orgminer_institutes` come only from
the `ude_authors` entries (verified organization metadata).
## Training
From the repository root:
```bash
python service/scripts/ude_publications_hdbscan/train.py
```
Required environment variables (normally in `service/src/main/inse/.env`):
```text
ELASTICSEARCH_INSE_URL
ELASTICSEARCH_INSE_API_KEY
```
Useful options:
```text
--index NAME # default: ude_openalex_works_dataset
--output-dir DIR # default: service/scripts/ude_publications_hdbscan/model
--embedding-model NAME # default: sentence-transformers/paraphrase-multilingual-mpnet-base-v2
--batch-size 64
--device cpu|cuda|mps
--embedding-shard-size 2000 # resumable embedding shards
--refresh-cache # discard cached embeddings
--limit N # smoke test
--min-cluster-size 10
--min-samples 2 # lower = fewer HDBSCAN noise points
--umap-neighbors 15
--umap-components 10
--reduce-outliers / --no-reduce-outliers # default: on
--outlier-strategy embeddings|c-tf-idf
--outlier-threshold 0.0 # 0 reassigns all outliers
```
The pipeline matches the old trainer: `UMAP` (cosine, 10 components) →
`HDBSCAN` (`eom`, `prediction_data=True`) wrapped in `BERTopic`, with
`CountVectorizer` over the keyword text. HDBSCAN chooses the number of clusters.
After fitting, HDBSCAN noise (`-1`) is reassigned to the nearest topic with
BERTopic's `reduce_outliers` (default strategy `embeddings`), and topic
representations are refreshed. `metadata.json` records the noise count before and
after.
Embeddings are memory-mapped to `embeddings_keywords.npy` in shards; progress is
recorded in `embeddings_progress.json`, so an interrupted run resumes.
## Artifacts
Default output `model/`:
```text
bertopic_model/ # native BERTopic save
embeddings_keywords.npy # row-aligned with training_table.pkl
training_table.pkl # id, title, keyword_text, ude_author_ids, other_ude_author_ids, topic
persons.pkl # author_id -> profile
institutions.pkl # institution_id -> OpenAlex institution
topic_centroids.npy # mean embedding per non-noise topic
topic_ids.json # topic id per centroid row
cluster_summaries.json # topic size + top keywords
metadata.json # index, counts, model/params, artifact names
```
Each person profile contains `author_id`, `name`, `orcid`, `verified`,
`organizations`, `faculties`, `chairs`, `institutes`, `institution_ids`.
## Prediction
```bash
python service/scripts/ude_publications_hdbscan/predict.py --text "cancer therapy"
python service/scripts/ude_publications_hdbscan/predict.py --embedding-file vector.npy
```
Options: `--top-n 15` (per list), `--top-topics 3`, `--device`, `--model-dir`.
Workflow: encode the query (or use the given vector), rank topics by cosine
similarity to the saved centroids, rank the documents in those topics by cosine
similarity to the query, then walk the ranked documents and collect unique
entities until each list reaches `top_n`.
Output:
```json
{
"institutions": [
{"id": "I62318514", "openalex_url": "https://openalex.org/I62318514",
"display_name": "University of Duisburg-Essen", "ror": "...",
"country_code": "DE", "type": "education"}
],
"persons": [
{"author_id": "A...", "name": "...", "orcid": "...", "verified": true,
"organizations": ["..."], "faculties": ["..."], "chairs": ["..."],
"institutes": ["..."], "institution_ids": ["I..."]}
],
"orgminer_faculties": ["..."],
"orgminer_chairs": ["..."],
"orgminer_institutes": ["..."]
}
```
Each list is unique and capped at `top_n`. HDBSCAN noise topic `-1` is not used
for topic selection; if no topic matches, all documents are ranked.
## Tests
```bash
python -m pytest service/scripts/ude_publications_hdbscan/tests -q
```
@@ -0,0 +1,288 @@
#!/usr/bin/env python3
"""Predict organizations and persons for a text or embedding.
Loads the artifacts written by ``train.py`` and returns the most similar
publications' entities:
* ``institutions`` - unique OpenAlex institutions from the persons
* ``persons`` - unique ``ude_authors`` + ``other_ude_authors``
* ``orgminer_faculties`` - unique faculties from ``ude_authors``
* ``orgminer_chairs`` - unique chairs from ``ude_authors``
* ``orgminer_institutes``- unique institutes from ``ude_authors``
Each list is capped at ``top_n`` (default 15).
Usage
-----
python service/scripts/ude_publications_hdbscan/predict.py --text "cancer therapy"
python service/scripts/ude_publications_hdbscan/predict.py --embedding-file vector.npy
"""
from __future__ import annotations
import argparse
import json
import logging
import pickle
from pathlib import Path
from typing import Any
import numpy as np
import pandas as pd
DEFAULT_MODEL_DIR = Path(__file__).resolve().parent / "model"
METADATA_FILENAME = "metadata.json"
TRAINING_TABLE_FILENAME = "training_table.pkl"
PERSONS_FILENAME = "persons.pkl"
INSTITUTIONS_FILENAME = "institutions.pkl"
EMBEDDINGS_FILENAME = "embeddings_keywords.npy"
CENTROIDS_FILENAME = "topic_centroids.npy"
TOPIC_IDS_FILENAME = "topic_ids.json"
logger = logging.getLogger("ude_publications_hdbscan.predict")
# =============================================================================
# Artifacts
# =============================================================================
def load_artifacts(model_dir: Path) -> dict[str, Any]:
metadata = json.loads(
(model_dir / METADATA_FILENAME).read_text(encoding="utf-8")
)
with (model_dir / PERSONS_FILENAME).open("rb") as handle:
persons = pickle.load(handle)
with (model_dir / INSTITUTIONS_FILENAME).open("rb") as handle:
institutions = pickle.load(handle)
return {
"metadata": metadata,
"persons": persons,
"institutions": institutions,
"table": pd.read_pickle(model_dir / TRAINING_TABLE_FILENAME),
"embeddings": np.load(model_dir / EMBEDDINGS_FILENAME),
"centroids": np.load(model_dir / CENTROIDS_FILENAME),
"topic_ids": json.loads(
(model_dir / TOPIC_IDS_FILENAME).read_text(encoding="utf-8")
),
}
def load_encoder(metadata: dict[str, Any], device: str | None = None) -> Any:
from sentence_transformers import SentenceTransformer
return SentenceTransformer(metadata["embedding_model"], device=device)
# =============================================================================
# Scoring
# =============================================================================
def _normalize(matrix: np.ndarray) -> np.ndarray:
matrix = np.asarray(matrix, dtype=np.float32)
if matrix.ndim == 1:
matrix = matrix.reshape(1, -1)
norms = np.linalg.norm(matrix, axis=1, keepdims=True)
norms[norms == 0] = 1.0
return matrix / norms
def cosine_scores(query: np.ndarray, matrix: np.ndarray) -> np.ndarray:
if matrix.size == 0:
return np.empty(0, dtype=np.float32)
return (_normalize(query) @ _normalize(matrix).T)[0]
def select_topics(
query_embedding: np.ndarray,
centroids: np.ndarray,
topic_ids: list[int],
top_topics: int,
) -> list[int]:
if centroids.size == 0 or not topic_ids:
return []
scores = cosine_scores(query_embedding, centroids)
order = np.argsort(scores)[::-1][: max(1, top_topics)]
return [int(topic_ids[index]) for index in order]
def rank_positions(
table: pd.DataFrame,
query_embedding: np.ndarray,
embeddings: np.ndarray,
topics: list[int],
) -> list[int]:
if topics:
positions = np.flatnonzero(table["topic"].isin(topics).to_numpy())
else:
positions = np.arange(len(table))
if positions.size == 0:
positions = np.arange(len(table))
scores = cosine_scores(query_embedding, embeddings[positions])
return positions[np.argsort(scores)[::-1]].tolist()
# =============================================================================
# Entity collection
# =============================================================================
def _dedupe(values: Any) -> list[str]:
if not isinstance(values, list):
return []
return list(dict.fromkeys(value for value in values if isinstance(value, str)))
def collect_predictions(
table: pd.DataFrame,
ranked_positions: list[int],
persons: dict[str, dict[str, Any]],
institutions: dict[str, dict[str, Any]],
top_n: int = 15,
) -> dict[str, list[Any]]:
result: dict[str, list[Any]] = {
"institutions": [],
"persons": [],
"orgminer_faculties": [],
"orgminer_chairs": [],
"orgminer_institutes": [],
}
seen: dict[str, set[str]] = {key: set() for key in result}
orgminer_fields = {
"orgminer_faculties": "faculties",
"orgminer_chairs": "chairs",
"orgminer_institutes": "institutes",
}
def full() -> bool:
return all(len(result[key]) >= top_n for key in result)
for position in ranked_positions:
row = table.iloc[position]
ude_ids = _dedupe(row.get("ude_author_ids"))
other_ids = _dedupe(row.get("other_ude_author_ids"))
for author_id in list(dict.fromkeys([*ude_ids, *other_ids])):
profile = persons.get(author_id.casefold())
if not profile:
continue
key = profile["author_id"].casefold()
if key not in seen["persons"] and len(result["persons"]) < top_n:
result["persons"].append(profile)
seen["persons"].add(key)
if len(result["institutions"]) < top_n:
for institution_id in _dedupe(profile.get("institution_ids")):
institution_key = institution_id.casefold()
institution = institutions.get(institution_key)
if (
institution is not None
and institution_key not in seen["institutions"]
):
result["institutions"].append(institution)
seen["institutions"].add(institution_key)
if len(result["institutions"]) >= top_n:
break
for author_id in ude_ids:
profile = persons.get(author_id.casefold())
if not profile:
continue
for output_key, field in orgminer_fields.items():
for value in _dedupe(profile.get(field)):
value_key = value.casefold()
if (
value_key not in seen[output_key]
and len(result[output_key]) < top_n
):
result[output_key].append(value)
seen[output_key].add(value_key)
if full():
break
return result
# =============================================================================
# Public API
# =============================================================================
def predict(
text: str | None = None,
embedding: Any | None = None,
top_n: int = 15,
top_topics: int = 3,
model_dir: Path = DEFAULT_MODEL_DIR,
device: str | None = None,
artifacts: dict[str, Any] | None = None,
encoder: Any | None = None,
) -> dict[str, list[Any]]:
if (text is None) == (embedding is None):
raise ValueError("Provide exactly one of text or embedding.")
artifacts = artifacts or load_artifacts(model_dir)
if text is not None:
encoder = encoder or load_encoder(artifacts["metadata"], device=device)
query = encoder.encode([text], convert_to_numpy=True)[0]
else:
query = np.asarray(embedding, dtype=np.float32).ravel()
centroids = artifacts["centroids"]
if centroids.size and query.shape[0] != centroids.shape[1]:
raise ValueError(
f"Embedding has dimension {query.shape[0]}, expected "
f"{centroids.shape[1]}."
)
topics = select_topics(
query, centroids, artifacts["topic_ids"], top_topics
)
ranked = rank_positions(
artifacts["table"], query, artifacts["embeddings"], topics
)
return collect_predictions(
artifacts["table"],
ranked,
artifacts["persons"],
artifacts["institutions"],
top_n=top_n,
)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--model-dir", type=Path, default=DEFAULT_MODEL_DIR)
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("--text")
group.add_argument("--embedding-file", type=Path)
parser.add_argument("--top-n", type=int, default=15)
parser.add_argument("--top-topics", type=int, default=3)
parser.add_argument("--device", default=None)
parser.add_argument("--log-level", default="INFO")
return parser.parse_args()
def main() -> int:
args = parse_args()
logging.basicConfig(
level=getattr(logging, args.log_level.upper(), logging.INFO)
)
embedding = None
if args.embedding_file is not None:
embedding = np.load(args.embedding_file)
result = predict(
text=args.text,
embedding=embedding,
top_n=args.top_n,
top_topics=args.top_topics,
model_dir=args.model_dir,
device=args.device,
)
print(json.dumps(result, ensure_ascii=False, indent=2))
return 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,12 @@
bertopic>=0.16
nbformat>=4.2.0
sentence-transformers>=5.5
umap-learn>=0.5
hdbscan>=0.8
scikit-learn>=1.5
nltk>=3.8
numpy>=1.26
pandas>=2.2
httpx>=0.27
python-dotenv>=1.0
pydantic-settings>=2.2
@@ -0,0 +1,717 @@
#!/usr/bin/env python3
"""Train a UMAP/HDBSCAN topic model on UDE publications.
Input is the ``keyword_names`` array of each publication in the
``ude_openalex_works_dataset`` Elasticsearch index. Authors are the single
source of truth for the prediction payload:
* ``persons`` - authors from ``ude_authors`` and ``other_ude_authors``
* ``institutions`` - OpenAlex institutions referenced by those persons
``predict.py`` assigns a query to topics by cosine similarity to the topic
centroids, so only the artifacts it reads are written to ``model/``:
metadata.json, persons.pkl, institutions.pkl, training_table.pkl,
embeddings_keywords.npy, topic_centroids.npy, topic_ids.json
Everything that is only useful for re-running training (the Elasticsearch
dataset and the resumable embedding cache) lives in ``.cache/`` instead.
Usage
-----
From the repository root::
python service/scripts/ude_publications_hdbscan/train.py
The service ``.env`` must provide the INSE Elasticsearch credentials (only
needed when the dataset is actually fetched, not when it is cached).
"""
from __future__ import annotations
import argparse
import functools
import hashlib
import json
import logging
import pickle
import shutil
import sys
from collections.abc import AsyncIterator, Iterable, Iterator
from contextlib import asynccontextmanager
from datetime import UTC, datetime
from pathlib import Path
from typing import Any
import numpy as np
import pandas as pd
SERVICE_DIR = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(SERVICE_DIR / "src" / "main"))
from inse import config # noqa: E402
from inse.integrations import elasticsearch # noqa: E402
from inse.model import ESCluster # noqa: E402
SCRIPT_DIR = Path(__file__).resolve().parent
DEFAULT_INDEX = "ude_openalex_works_dataset"
DEFAULT_EMBEDDING_MODEL = (
"sentence-transformers/paraphrase-multilingual-mpnet-base-v2"
)
DEFAULT_OUTPUT_DIR = SCRIPT_DIR / "model"
DEFAULT_CACHE_DIR = SCRIPT_DIR / ".cache"
PAGE_SIZE = 500
# --- model artifacts (read by predict.py) ---
EMBEDDINGS_FILENAME = "embeddings_keywords.npy"
TRAINING_TABLE_FILENAME = "training_table.pkl"
PERSONS_FILENAME = "persons.pkl"
INSTITUTIONS_FILENAME = "institutions.pkl"
CENTROIDS_FILENAME = "topic_centroids.npy"
TOPIC_IDS_FILENAME = "topic_ids.json"
METADATA_FILENAME = "metadata.json"
# --- cache files (training only, never read by predict.py) ---
DATASET_CACHE_FILENAME = "dataset.pkl"
EMBEDDING_CACHE_FILENAME = "embeddings_cache.npy"
PROGRESS_FILENAME = "embeddings_progress.json"
# Columns predict.py actually reads from the training table.
TABLE_COLUMNS = ["topic", "ude_author_ids", "other_ude_author_ids"]
# Leftovers from older runs that predict.py never loads.
OBSOLETE_ARTIFACTS = (
"bertopic_model",
"cluster_summaries.json",
"embeddings_progress.json",
)
SOURCE_FIELDS = [
"id",
"title",
"keyword_names",
"keywords",
"ude_authors",
"other_ude_authors",
]
PERSON_ORGMINER_FIELDS = ("organizations", "faculties", "chairs", "institutes")
logger = logging.getLogger("ude_publications_hdbscan")
# =============================================================================
# Small helpers
# =============================================================================
def setup_logging(level: str) -> None:
logging.basicConfig(
level=getattr(logging, level.upper(), logging.INFO),
format="%(asctime)s %(levelname)s %(name)s %(message)s",
)
def clean_text(value: Any) -> str | None:
if not isinstance(value, str):
return None
value = value.strip()
return value or None
def normalize_openalex_id(value: Any) -> str | None:
if not isinstance(value, str):
return None
value = value.strip().rstrip("/")
marker = "openalex.org/"
if marker in value:
value = value.split(marker, 1)[1]
value = value.strip()
return value or None
def as_str_list(value: Any) -> list[str]:
if value is None:
return []
if isinstance(value, str):
value = [value]
if not isinstance(value, list):
return []
return [item.strip() for item in value if isinstance(item, str) and item.strip()]
def load_json(path: Path, default: Any) -> Any:
if not path.exists():
return default
try:
return json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
logger.warning("Ignoring unreadable %s.", path)
return default
def save_json_atomic(path: Path, payload: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_suffix(path.suffix + ".tmp")
temporary.write_text(
json.dumps(payload, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
)
temporary.replace(path)
def save_pickle_atomic(path: Path, payload: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_suffix(path.suffix + ".tmp")
with temporary.open("wb") as handle:
pickle.dump(payload, handle, protocol=pickle.HIGHEST_PROTOCOL)
temporary.replace(path)
def texts_hash(texts: Iterable[str]) -> str:
payload = "\0".join(texts).encode("utf-8")
return hashlib.sha256(payload).hexdigest()
def normalize_rows(matrix: np.ndarray) -> np.ndarray:
matrix = np.asarray(matrix, dtype=np.float32)
norms = np.linalg.norm(matrix, axis=1, keepdims=True)
norms[norms == 0] = 1.0
return matrix / norms
@asynccontextmanager
async def closing_scan(**kwargs: Any) -> AsyncIterator[Any]:
generator = elasticsearch.scan(**kwargs)
try:
yield generator
finally:
close = getattr(generator, "aclose", None)
if close is not None:
await close()
# =============================================================================
# Dataset / profiles
# =============================================================================
def keyword_text(source: dict[str, Any]) -> str | None:
"""Join the publication's keyword names into the embedding input."""
names = as_str_list(source.get("keyword_names"))
if not names:
names = [
name
for item in source.get("keywords") or []
if isinstance(item, dict)
for name in [clean_text(item.get("display_name"))]
if name
]
unique = list(dict.fromkeys(name.strip() for name in names if name.strip()))
return ", ".join(unique) or None
def _merge_person(
persons: dict[str, dict[str, Any]], author: dict[str, Any]
) -> str | None:
author_id = normalize_openalex_id(author.get("author_id"))
if not author_id:
return None
key = author_id.casefold()
profile = persons.get(key)
if profile is None:
profile = {
"author_id": author_id,
"name": None,
"orcid": None,
"verified": False,
**{field: set() for field in PERSON_ORGMINER_FIELDS},
"institution_ids": set(),
}
persons[key] = profile
profile["name"] = profile["name"] or clean_text(author.get("name"))
profile["orcid"] = profile["orcid"] or clean_text(author.get("orcid"))
profile["verified"] = profile["verified"] or bool(author.get("verified"))
for field in PERSON_ORGMINER_FIELDS:
profile[field].update(as_str_list(author.get(field)))
profile["institution_ids"].update(
filter(
None,
(
normalize_openalex_id(item)
for item in author.get("institution_ids") or []
),
)
)
return author_id
def _add_institution(
institutions: dict[str, dict[str, Any]], institution: dict[str, Any]
) -> None:
institution_id = normalize_openalex_id(institution.get("id"))
if not institution_id:
return
institutions.setdefault(
institution_id.casefold(),
{
"id": institution_id,
"openalex_url": f"https://openalex.org/{institution_id}",
"display_name": clean_text(institution.get("display_name")),
"ror": clean_text(institution.get("ror")),
"country_code": clean_text(institution.get("country_code")),
"type": clean_text(institution.get("type")),
},
)
def extract_profiles(
source: dict[str, Any],
persons: dict[str, dict[str, Any]],
institutions: dict[str, dict[str, Any]],
) -> tuple[list[str], list[str]]:
"""Add this publication's UDE authors to the profile maps.
Returns ``(ude_author_ids, other_ude_author_ids)``. Institutions are taken
only from these author profiles - never from work-level fields.
"""
groups: list[list[str]] = []
for field in ("ude_authors", "other_ude_authors"):
ids: list[str] = []
seen: set[str] = set()
for author in source.get(field) or []:
if not isinstance(author, dict):
continue
author_id = _merge_person(persons, author)
if not author_id:
continue
if author_id.casefold() not in seen:
seen.add(author_id.casefold())
ids.append(author_id)
for institution in author.get("institutions") or []:
if isinstance(institution, dict):
_add_institution(institutions, institution)
groups.append(ids)
return groups[0], groups[1]
def build_training_row(
source: dict[str, Any],
persons: dict[str, dict[str, Any]],
institutions: dict[str, dict[str, Any]],
) -> dict[str, Any] | None:
text = keyword_text(source)
if not text:
return None
ude_ids, other_ude_ids = extract_profiles(source, persons, institutions)
return {
"id": normalize_openalex_id(source.get("id")),
"keyword_text": text,
"ude_author_ids": ude_ids,
"other_ude_author_ids": other_ude_ids,
}
async def fetch_dataset(index: str, limit: int | None = None) -> tuple[
list[dict[str, Any]],
dict[str, dict[str, Any]],
dict[str, dict[str, Any]],
]:
rows: list[dict[str, Any]] = []
persons: dict[str, dict[str, Any]] = {}
institutions: dict[str, dict[str, Any]] = {}
async with closing_scan(
index=index,
query={"match_all": {}},
source=SOURCE_FIELDS,
page_size=PAGE_SIZE,
keep_alive="10m",
cluster=ESCluster.INSE.value,
) as hits:
async for hit in hits:
row = build_training_row(hit.get("_source") or {}, persons, institutions)
if row is not None:
rows.append(row)
if limit is not None and len(rows) >= limit:
break
# Stable order keeps the embedding cache hash reproducible between runs.
rows.sort(key=lambda row: row["id"] or "")
for profile in persons.values():
for field in PERSON_ORGMINER_FIELDS:
profile[field] = sorted(profile[field], key=str.casefold)
profile["institution_ids"] = sorted(
profile["institution_ids"], key=str.casefold
)
logger.info(
"Fetched %d publications with keywords (%d persons, %d institutions).",
len(rows),
len(persons),
len(institutions),
)
return rows, persons, institutions
def validate_credentials() -> None:
if not config.settings.elasticsearch_inse_url:
raise SystemExit("Missing ELASTICSEARCH_INSE_URL.")
if not config.settings.elasticsearch_inse_api_key:
raise SystemExit("Missing ELASTICSEARCH_INSE_API_KEY.")
def load_dataset(args: argparse.Namespace) -> tuple[
list[dict[str, Any]],
dict[str, dict[str, Any]],
dict[str, dict[str, Any]],
]:
"""Return the dataset from the local cache, or fetch it from Elasticsearch."""
import asyncio
path = args.cache_dir / DATASET_CACHE_FILENAME
key = {"index": args.index, "limit": args.limit}
if path.exists() and not args.refresh_data:
try:
with path.open("rb") as handle:
cached = pickle.load(handle)
if cached.get("key") == key:
logger.info("Using cached dataset from %s.", path)
return cached["rows"], cached["persons"], cached["institutions"]
logger.info("Dataset cache was built for another index/limit; refetching.")
except Exception: # corrupt or incompatible cache
logger.warning("Dataset cache unreadable; refetching.", exc_info=True)
validate_credentials()
rows, persons, institutions = asyncio.run(
fetch_dataset(args.index, limit=args.limit)
)
save_pickle_atomic(
path,
{"key": key, "rows": rows, "persons": persons, "institutions": institutions},
)
return rows, persons, institutions
# =============================================================================
# Embeddings
# =============================================================================
def compute_embeddings(
texts: list[str], args: argparse.Namespace
) -> np.ndarray:
"""Encode texts into a resumable, shard-filled ``.npy`` cache.
The encoder is loaded lazily, so a fully cached run never loads the model.
"""
path = args.cache_dir / EMBEDDING_CACHE_FILENAME
progress_path = args.cache_dir / PROGRESS_FILENAME
progress = load_json(progress_path, {})
shard_size = max(1, args.embedding_shard_size)
shard_count = (len(texts) + shard_size - 1) // shard_size
current_hash = texts_hash(texts)
@functools.cache
def get_encoder() -> Any:
from sentence_transformers import SentenceTransformer
logger.info("Loading embedding model %s.", args.embedding_model)
return SentenceTransformer(args.embedding_model, device=args.device)
can_resume = (
path.exists()
and progress.get("rows") == len(texts)
and progress.get("model") == args.embedding_model
and progress.get("text_hash") == current_hash
and progress.get("shard_size") == shard_size
)
matrix = None
if can_resume:
matrix = np.load(path, mmap_mode="r+")
if matrix.shape != (len(texts), progress.get("dimensions")):
matrix = None
if matrix is not None:
completed = set(progress.get("completed_shards") or [])
logger.info(
"Resuming embeddings: %d/%d shards already encoded.",
len(completed),
shard_count,
)
else:
encoder = get_encoder()
dimensions = encoder.get_sentence_embedding_dimension()
if dimensions is None:
dimensions = encoder.encode(["dimension probe"]).shape[1]
dimensions = int(dimensions)
args.cache_dir.mkdir(parents=True, exist_ok=True)
matrix = np.lib.format.open_memmap(
path, mode="w+", dtype=np.float32, shape=(len(texts), dimensions)
)
completed = set()
progress = {
"rows": len(texts),
"dimensions": dimensions,
"model": args.embedding_model,
"text_hash": current_hash,
"shard_size": shard_size,
"completed_shards": [],
}
save_json_atomic(progress_path, progress)
for start in range(0, len(texts), shard_size):
end = min(start + shard_size, len(texts))
shard_key = f"{start}:{end}"
if shard_key in completed:
continue
matrix[start:end] = get_encoder().encode(
texts[start:end],
batch_size=args.batch_size,
show_progress_bar=False,
convert_to_numpy=True,
)
matrix.flush()
completed.add(shard_key)
progress["completed_shards"] = sorted(completed)
save_json_atomic(progress_path, progress)
logger.info(
"Embeddings shard %s complete (%d/%d).",
shard_key,
len(completed),
shard_count,
)
matrix.flush()
del matrix
return np.load(path)
# =============================================================================
# Clustering (UMAP + HDBSCAN, no BERTopic needed)
# =============================================================================
def cluster_embeddings(embeddings: np.ndarray, args: argparse.Namespace) -> list[int]:
from hdbscan import HDBSCAN
from umap import UMAP
logger.info("Reducing dimensions with UMAP.")
reduced = UMAP(
n_neighbors=args.umap_neighbors,
n_components=args.umap_components,
metric="cosine",
random_state=args.seed,
).fit_transform(embeddings)
logger.info("Clustering with HDBSCAN.")
labels = HDBSCAN(
min_cluster_size=args.min_cluster_size,
min_samples=args.min_samples,
metric="euclidean",
cluster_selection_method="eom",
).fit_predict(reduced)
return [int(label) for label in labels]
def topic_centroids(
embeddings: np.ndarray, topics: list[int]
) -> tuple[np.ndarray, list[int]]:
"""Mean embedding per non-noise topic, used by predict.py for ranking."""
labels = np.asarray(topics)
topic_ids = sorted(int(topic) for topic in set(labels.tolist()) if topic != -1)
if not topic_ids:
return np.empty((0, embeddings.shape[1]), dtype=np.float32), []
centroids = np.vstack(
[embeddings[labels == topic].mean(axis=0) for topic in topic_ids]
).astype(np.float32)
return centroids, topic_ids
def reassign_noise(
embeddings: np.ndarray, topics: list[int], threshold: float
) -> list[int]:
"""Move HDBSCAN noise (-1) documents to the nearest topic centroid.
Uses the same cosine-to-centroid logic as predict.py. With a threshold
of 0 every noise document is reassigned; otherwise only those whose
similarity reaches the threshold.
"""
labels = np.asarray(topics)
noise = np.flatnonzero(labels == -1)
if noise.size == 0:
return topics
centroids, topic_ids = topic_centroids(embeddings, topics)
if not topic_ids:
logger.warning("No clusters found; nothing to reassign noise to.")
return topics
scores = normalize_rows(embeddings[noise]) @ normalize_rows(centroids).T
best = scores.argmax(axis=1)
best_scores = scores[np.arange(noise.size), best]
accept = np.ones(noise.size, dtype=bool) if threshold <= 0 else best_scores >= threshold
ids = np.asarray(topic_ids)
labels[noise[accept]] = ids[best[accept]]
return labels.tolist()
# =============================================================================
# Main
# =============================================================================
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--index", default=DEFAULT_INDEX)
parser.add_argument("--output-dir", type=Path, default=DEFAULT_OUTPUT_DIR)
parser.add_argument(
"--cache-dir",
type=Path,
default=DEFAULT_CACHE_DIR,
help="Training-only cache (dataset + embeddings); not needed by predict.py.",
)
parser.add_argument("--embedding-model", default=DEFAULT_EMBEDDING_MODEL)
parser.add_argument("--batch-size", type=int, default=64)
parser.add_argument("--device", default=None)
parser.add_argument(
"--embedding-shard-size",
type=int,
default=2000,
help="Rows encoded per resumable shard.",
)
parser.add_argument(
"--embedding-dtype",
default="float16",
choices=["float16", "float32"],
help="Precision of the saved embeddings_keywords.npy (default: float16, "
"half the size, no practical effect on cosine ranking).",
)
parser.add_argument(
"--refresh-data",
action="store_true",
help="Ignore the cached dataset and re-fetch from Elasticsearch.",
)
parser.add_argument(
"--refresh-cache",
action="store_true",
help="Discard cached embeddings and re-encode.",
)
parser.add_argument("--limit", type=int, default=None)
parser.add_argument("--min-cluster-size", type=int, default=10)
parser.add_argument(
"--min-samples",
type=int,
default=2,
help="Lower values label fewer points as HDBSCAN noise (default: 2).",
)
parser.add_argument("--umap-neighbors", type=int, default=15)
parser.add_argument("--umap-components", type=int, default=10)
parser.add_argument(
"--seed",
type=int,
default=None,
help="UMAP random seed for reproducible topics (disables UMAP parallelism).",
)
parser.add_argument(
"--reduce-outliers",
action=argparse.BooleanOptionalAction,
default=True,
help="Reassign HDBSCAN noise (-1) documents to the nearest topic "
"centroid after clustering (default: on).",
)
parser.add_argument(
"--outlier-threshold",
type=float,
default=0.0,
help="Minimum cosine similarity for reassignment (0 assigns all outliers).",
)
parser.add_argument("--log-level", default="INFO")
return parser.parse_args()
def main() -> int:
args = parse_args()
setup_logging(args.log_level)
args.output_dir.mkdir(parents=True, exist_ok=True)
args.cache_dir.mkdir(parents=True, exist_ok=True)
if args.refresh_cache:
for name in (EMBEDDING_CACHE_FILENAME, PROGRESS_FILENAME):
(args.cache_dir / name).unlink(missing_ok=True)
rows, persons, institutions = load_dataset(args)
if not rows:
logger.error("No publications with keywords found.")
return 1
texts = [row["keyword_text"] for row in rows]
embeddings = compute_embeddings(texts, args)
topics = cluster_embeddings(embeddings, args)
noise_before = sum(1 for topic in topics if topic == -1)
if args.reduce_outliers and noise_before:
logger.info("Reassigning %d noise documents to nearest centroid.", noise_before)
topics = reassign_noise(embeddings, topics, args.outlier_threshold)
centroids, topic_ids = topic_centroids(embeddings, topics)
# Slim table: only what predict.py needs (no id/title/keyword_text).
training_table = pd.DataFrame(rows).assign(topic=topics)[TABLE_COLUMNS]
training_table.to_pickle(args.output_dir / TRAINING_TABLE_FILENAME)
save_pickle_atomic(args.output_dir / PERSONS_FILENAME, persons)
save_pickle_atomic(args.output_dir / INSTITUTIONS_FILENAME, institutions)
np.save(args.output_dir / EMBEDDINGS_FILENAME, embeddings.astype(args.embedding_dtype))
np.save(args.output_dir / CENTROIDS_FILENAME, centroids)
save_json_atomic(args.output_dir / TOPIC_IDS_FILENAME, topic_ids)
save_json_atomic(
args.output_dir / METADATA_FILENAME,
{
"created_at": datetime.now(UTC).isoformat(),
"index": args.index,
"embedding_model": args.embedding_model, # required by predict.py
"embedding_dtype": args.embedding_dtype,
"documents": len(rows),
"persons": len(persons),
"institutions": len(institutions),
"topics": len(topic_ids),
"noise_before_reduction": noise_before,
"noise_documents": sum(1 for topic in topics if topic == -1),
"reduce_outliers": args.reduce_outliers,
"outlier_threshold": args.outlier_threshold,
"min_cluster_size": args.min_cluster_size,
"min_samples": args.min_samples,
"umap_neighbors": args.umap_neighbors,
"umap_components": args.umap_components,
},
)
# Remove files from older runs that predict.py does not load.
for name in OBSOLETE_ARTIFACTS:
target = args.output_dir / name
if target.is_dir():
shutil.rmtree(target)
else:
target.unlink(missing_ok=True)
(args.output_dir / EMBEDDINGS_FILENAME.replace(".npy", "_progress.json")).unlink(
missing_ok=True
)
logger.info(
"Saved model: %d documents, %d topics, %d persons, %d institutions.",
len(rows),
len(topic_ids),
len(persons),
len(institutions),
)
return 0
if __name__ == "__main__":
raise SystemExit(main())