added organization information to ude verified staff script
This commit is contained in:
@@ -20,8 +20,8 @@ COPY service/src/data/hierarchies/I62318514/hierarchy.json \
|
||||
COPY service/scripts/upload_orgminer_verified_persons_ude/ \
|
||||
./service/scripts/upload_orgminer_verified_persons_ude/
|
||||
|
||||
# Fail the image build if the service verification code is missing a dependency.
|
||||
RUN python -c "import inse.orgminer.logic"
|
||||
# Fail the image build if the service verification/author code is missing a dependency.
|
||||
RUN python -c "import inse.orgminer.logic, inse.authors.v2.service"
|
||||
|
||||
ENTRYPOINT ["python", "/app/service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py", \
|
||||
"--progress-file", "/state/orgminer_verified_persons_ude_progress.json"]
|
||||
|
||||
@@ -26,6 +26,28 @@ completed organization URI. On restart the scan resumes from that URI, skips
|
||||
completed organizations, and safely retries upserts if an interrupted request did
|
||||
not get checkpointed. Use `--progress-file PATH` to keep the checkpoint elsewhere.
|
||||
|
||||
Each document also exposes the organization context explicitly:
|
||||
|
||||
- `faculty`: root hierarchy node, for example `Chemie`
|
||||
- `organization_type`: immediate parent label, for example `Lehrstühle` or
|
||||
`Instituten`
|
||||
- `organization_level`: hierarchy node type code (`leaf`, `chairs`,
|
||||
`institutes`, `faculty`)
|
||||
|
||||
Each person document also carries the person's OpenAlex organizations, loaded
|
||||
from `openalex-authors`:
|
||||
|
||||
- `oa_organization_ids`: deduplicated short OpenAlex organization IDs
|
||||
(`I62318514`), used for filtering and joins
|
||||
- `oa_organization`: deduplicated OpenAlex organization objects with `id`,
|
||||
`openalex_url`, `display_name`, `ror`, `country_code`, `type`, `lineage`,
|
||||
`years`, and `last_known`
|
||||
|
||||
`last_known_institutions` and `affiliations` are merged by institution ID;
|
||||
affiliation years are unioned and institutions without an OpenAlex ID are
|
||||
skipped. Missing author documents do not drop the person; the document is written
|
||||
with empty institution fields and a warning is logged.
|
||||
|
||||
The script processes one organization at a time, so a run needs no concurrency
|
||||
flags.
|
||||
|
||||
@@ -54,3 +76,19 @@ When configured on a background-job task, `--fresh` applies on every run, so the
|
||||
task always restarts from the first source organization. If the checkpoint
|
||||
directory is not a mounted volume, a warning is logged because progress cannot
|
||||
survive the container.
|
||||
|
||||
## Rebuilding after a mapping change
|
||||
|
||||
The script creates the output index with its mapping only when the index does
|
||||
not exist. After changing the document fields, delete the old index first and
|
||||
then run a full upload:
|
||||
|
||||
```bash
|
||||
curl -X DELETE "$ELASTICSEARCH_INSE_URL/orgminer_verified_persons_ude" \
|
||||
-H "Authorization: ApiKey $ELASTICSEARCH_INSE_API_KEY"
|
||||
|
||||
python service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py --fresh
|
||||
```
|
||||
|
||||
`--fresh` also removes the checkpoint so every source organization is processed
|
||||
again.
|
||||
|
||||
+277
@@ -0,0 +1,277 @@
|
||||
"""Tests for the institution projection helpers in the upload script."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
from inse.models.openalex.author import Author
|
||||
from inse.models.openalex.author_affiliations_inner import AuthorAffiliationsInner
|
||||
from inse.models.openalex.dehydrated_institution import DehydratedInstitution
|
||||
|
||||
SCRIPT_PATH = Path(__file__).with_name("upload_orgminer_verified_persons_ude.py")
|
||||
_SPEC = importlib.util.spec_from_file_location(
|
||||
"upload_orgminer_verified_persons_ude", SCRIPT_PATH
|
||||
)
|
||||
assert _SPEC and _SPEC.loader
|
||||
upload = importlib.util.module_from_spec(_SPEC)
|
||||
sys.modules[_SPEC.name] = upload
|
||||
_SPEC.loader.exec_module(upload)
|
||||
|
||||
|
||||
def _institution(
|
||||
institution_id: str | None,
|
||||
display_name: str | None,
|
||||
*,
|
||||
ror: str | None = None,
|
||||
country_code: str | None = None,
|
||||
institution_type: str | None = None,
|
||||
lineage: list[str] | None = None,
|
||||
) -> DehydratedInstitution:
|
||||
return DehydratedInstitution(
|
||||
id=institution_id,
|
||||
display_name=display_name,
|
||||
ror=ror,
|
||||
country_code=country_code,
|
||||
type=institution_type,
|
||||
lineage=lineage,
|
||||
)
|
||||
|
||||
|
||||
def test_extract_merges_last_known_and_historical_institutions() -> None:
|
||||
ude_last_known = _institution(
|
||||
"https://openalex.org/I62318514",
|
||||
"University of Duisburg-Essen",
|
||||
country_code="DE",
|
||||
institution_type="education",
|
||||
lineage=["https://openalex.org/I1", "https://openalex.org/I62318514"],
|
||||
)
|
||||
ude_affiliation = _institution(
|
||||
"I62318514",
|
||||
"University of Duisburg-Essen",
|
||||
ror="https://ror.org/021ft7s37",
|
||||
)
|
||||
previous = _institution(
|
||||
"https://openalex.org/I999",
|
||||
"Previous University",
|
||||
country_code="NL",
|
||||
institution_type="education",
|
||||
)
|
||||
|
||||
author = Author(
|
||||
id="https://openalex.org/A1",
|
||||
last_known_institutions=[ude_last_known],
|
||||
affiliations=[
|
||||
AuthorAffiliationsInner(institution=ude_affiliation, years=[2020, 2021]),
|
||||
AuthorAffiliationsInner(institution=previous, years=[2017, 2018]),
|
||||
AuthorAffiliationsInner(institution=ude_affiliation, years=[2019]),
|
||||
],
|
||||
)
|
||||
|
||||
institutions = upload.extract_openalex_institutions(author)
|
||||
|
||||
assert [item["id"] for item in institutions] == ["I62318514", "I999"]
|
||||
assert institutions[0] == {
|
||||
"id": "I62318514",
|
||||
"openalex_url": "https://openalex.org/I62318514",
|
||||
"display_name": "University of Duisburg-Essen",
|
||||
"ror": "https://ror.org/021ft7s37",
|
||||
"country_code": "DE",
|
||||
"type": "education",
|
||||
"lineage": ["https://openalex.org/I1", "https://openalex.org/I62318514"],
|
||||
"years": [2019, 2020, 2021],
|
||||
"last_known": True,
|
||||
}
|
||||
assert institutions[1]["last_known"] is False
|
||||
assert institutions[1]["years"] == [2017, 2018]
|
||||
assert upload.openalex_institution_ids(institutions) == ["I62318514", "I999"]
|
||||
|
||||
|
||||
def test_extract_skips_institutions_without_an_openalex_id() -> None:
|
||||
author = Author(
|
||||
id="https://openalex.org/A1",
|
||||
last_known_institutions=[
|
||||
_institution(None, "Unknown Institute"),
|
||||
_institution("", "Empty Id Institute"),
|
||||
],
|
||||
affiliations=[
|
||||
AuthorAffiliationsInner(
|
||||
institution=_institution("I123", "Known Institute"),
|
||||
years=[2021],
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
institutions = upload.extract_openalex_institutions(author)
|
||||
|
||||
assert [item["id"] for item in institutions] == ["I123"]
|
||||
assert institutions[0]["last_known"] is False
|
||||
assert institutions[0]["years"] == [2021]
|
||||
|
||||
|
||||
def test_extract_handles_missing_author_and_empty_institutions() -> None:
|
||||
assert upload.extract_openalex_institutions(None) == []
|
||||
assert (
|
||||
upload.extract_openalex_institutions(Author(id="https://openalex.org/A1"))
|
||||
== []
|
||||
)
|
||||
assert upload.openalex_institution_ids([]) == []
|
||||
|
||||
|
||||
def _node(
|
||||
name: str,
|
||||
*,
|
||||
node_type: str,
|
||||
link: str | None = None,
|
||||
children: list[SimpleNamespace] | None = None,
|
||||
) -> SimpleNamespace:
|
||||
return SimpleNamespace(
|
||||
name_de=name,
|
||||
name_en=None,
|
||||
link_de=link,
|
||||
link_en=None,
|
||||
type=node_type,
|
||||
children=children or [],
|
||||
)
|
||||
|
||||
|
||||
def test_organization_details_splits_faculty_type_and_organization() -> None:
|
||||
hierarchy = [
|
||||
_node(
|
||||
"Chemie",
|
||||
node_type="faculty",
|
||||
link="https://example.org/chemie",
|
||||
children=[
|
||||
_node(
|
||||
"Lehrstühle",
|
||||
node_type="chairs",
|
||||
link="https://example.org/chemie/lehrstuehle",
|
||||
children=[
|
||||
_node(
|
||||
"Applied Analytical Chemistry",
|
||||
node_type="leaf",
|
||||
link="https://example.org/chemie/aac",
|
||||
)
|
||||
],
|
||||
)
|
||||
],
|
||||
)
|
||||
]
|
||||
lookup = upload.build_hierarchy_lookup(hierarchy)
|
||||
|
||||
details = upload.organization_details(
|
||||
{"uri": "https://example.org/chemie/aac"}, lookup
|
||||
)
|
||||
|
||||
assert details.faculty == "Chemie"
|
||||
assert details.organization_type == "Lehrstühle"
|
||||
assert details.name == "Applied Analytical Chemistry"
|
||||
assert details.organization_level == "leaf"
|
||||
assert details.hierarchy_path == [
|
||||
"Chemie",
|
||||
"Lehrstühle",
|
||||
"Applied Analytical Chemistry",
|
||||
]
|
||||
|
||||
|
||||
def test_organization_details_uses_immediate_parent_for_deep_paths() -> None:
|
||||
hierarchy = [
|
||||
_node(
|
||||
"Chemie",
|
||||
node_type="faculty",
|
||||
link="https://example.org/chemie",
|
||||
children=[
|
||||
_node(
|
||||
"Instituten",
|
||||
node_type="institutes",
|
||||
link="https://example.org/chemie/institute",
|
||||
children=[
|
||||
_node(
|
||||
"ACTIVE SITES",
|
||||
node_type="leaf",
|
||||
link="https://example.org/chemie/active-sites",
|
||||
children=[
|
||||
_node(
|
||||
"Lehrstühle",
|
||||
node_type="chairs",
|
||||
link="https://example.org/chemie/active-sites/chairs",
|
||||
children=[
|
||||
_node(
|
||||
"Applied Analytical Chemistry",
|
||||
node_type="leaf",
|
||||
link="https://example.org/chemie/active-sites/aac",
|
||||
)
|
||||
],
|
||||
)
|
||||
],
|
||||
)
|
||||
],
|
||||
)
|
||||
],
|
||||
)
|
||||
]
|
||||
lookup = upload.build_hierarchy_lookup(hierarchy)
|
||||
|
||||
details = upload.organization_details(
|
||||
{"uri": "https://example.org/chemie/active-sites/aac"}, lookup
|
||||
)
|
||||
|
||||
assert details.faculty == "Chemie"
|
||||
assert details.organization_type == "Lehrstühle"
|
||||
assert details.name == "Applied Analytical Chemistry"
|
||||
|
||||
|
||||
def test_organization_details_describes_aggregator_nodes() -> None:
|
||||
hierarchy = [
|
||||
_node(
|
||||
"Chemie",
|
||||
node_type="faculty",
|
||||
link="https://example.org/chemie",
|
||||
children=[
|
||||
_node(
|
||||
"Lehrstühle",
|
||||
node_type="chairs",
|
||||
link="https://example.org/chemie/lehrstuehle",
|
||||
)
|
||||
],
|
||||
)
|
||||
]
|
||||
lookup = upload.build_hierarchy_lookup(hierarchy)
|
||||
|
||||
details = upload.organization_details(
|
||||
{"uri": "https://example.org/chemie/lehrstuehle"}, lookup
|
||||
)
|
||||
|
||||
assert details.faculty == "Chemie"
|
||||
assert details.organization_type == "Lehrstühle"
|
||||
assert details.name == "Lehrstühle"
|
||||
assert details.organization_level == "chairs"
|
||||
|
||||
|
||||
def test_extract_merges_lineage_and_metadata_from_multiple_sources() -> None:
|
||||
author = Author(
|
||||
id="https://openalex.org/A1",
|
||||
last_known_institutions=[
|
||||
_institution("I42", "Example University", lineage=["I1"])
|
||||
],
|
||||
affiliations=[
|
||||
AuthorAffiliationsInner(
|
||||
institution=_institution(
|
||||
"I42",
|
||||
"Example University",
|
||||
ror="https://ror.org/example",
|
||||
lineage=["I1", "I42"],
|
||||
),
|
||||
years=[2022],
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
institutions = upload.extract_openalex_institutions(author)
|
||||
|
||||
assert len(institutions) == 1
|
||||
assert institutions[0]["ror"] == "https://ror.org/example"
|
||||
assert institutions[0]["lineage"] == ["I1", "I42"]
|
||||
assert institutions[0]["years"] == [2022]
|
||||
+413
-20
@@ -6,9 +6,10 @@ For every organization in the UDE organization-content index (one at a time):
|
||||
|
||||
1. READ the organization and its staff list from Elasticsearch (INSE)
|
||||
2. VERIFY each staff member against the collaboration graph (OpenAlex)
|
||||
3. BUILD one document per (organization, OpenAlex person)
|
||||
4. UPLOAD the documents to ``orgminer_verified_persons_ude`` (bulk upsert)
|
||||
5. CHECKPOINT the organization as done in a small JSON progress file
|
||||
3. LOOK UP each verified person's OpenAlex institutions by author ID
|
||||
4. BUILD one document per (organization, OpenAlex person)
|
||||
5. UPLOAD the documents to ``orgminer_verified_persons_ude`` (bulk upsert)
|
||||
6. CHECKPOINT the organization as done in a small JSON progress file
|
||||
|
||||
Everything runs sequentially: one organization at a time, one graph query at a
|
||||
time.
|
||||
@@ -54,16 +55,34 @@ SERVICE_DIR = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(SERVICE_DIR / "src" / "main"))
|
||||
|
||||
from inse import config # noqa: E402
|
||||
from inse.authors.v2.service import get_author_by_id, search_authors # noqa: E402
|
||||
from inse.exceptions import NotFoundException # noqa: E402
|
||||
from inse.model import ESIndex # noqa: E402
|
||||
from inse.models.openalex.author import Author # noqa: E402
|
||||
from inse.orgminer import logic # noqa: E402
|
||||
from inse.orgminer.institutions_helper import ( # noqa: E402
|
||||
DEFAULT_INSTITUTION_ID,
|
||||
full_institution_url,
|
||||
normalize_org_uri,
|
||||
strip_openalex_prefix,
|
||||
)
|
||||
|
||||
T = TypeVar("T")
|
||||
Hit = dict[str, Any] # one Elasticsearch search hit
|
||||
HierarchyLookup = dict[str, tuple[str, list[str]]] # uri -> (name, path from root)
|
||||
# uri -> (display name, path from root, hierarchy node type)
|
||||
HierarchyLookup = dict[str, tuple[str, list[str], str | None]]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class OrganizationDetails:
|
||||
"""Explicit organization context for downstream predictions."""
|
||||
|
||||
name: str
|
||||
uri: str | None
|
||||
hierarchy_path: list[str]
|
||||
faculty: str | None
|
||||
organization_type: str | None
|
||||
organization_level: str | None
|
||||
|
||||
|
||||
# =============================================================================
|
||||
@@ -92,6 +111,17 @@ RETRYABLE_STATUS = {429, 502, 503, 504}
|
||||
# Collab-graph queries per organization. Kept at 1: fully sequential.
|
||||
GRAPH_QUERIES_AT_A_TIME = 1
|
||||
|
||||
# Author institution lookups. Batched by ID, with per-person fallbacks for
|
||||
# installations whose author documents use a different `_id` convention.
|
||||
AUTHOR_LOOKUP_BATCH_SIZE = 100
|
||||
AUTHOR_SOURCE_FIELDS = [
|
||||
"id",
|
||||
"display_name",
|
||||
"orcid",
|
||||
"last_known_institutions",
|
||||
"affiliations",
|
||||
]
|
||||
|
||||
PROGRESS_SAVE_INTERVAL_S = 5.0
|
||||
PROGRESS_LOG_INTERVAL_S = 30.0
|
||||
|
||||
@@ -99,10 +129,32 @@ INDEX_MAPPING = {
|
||||
"dynamic": "strict",
|
||||
"properties": {
|
||||
"name": {"type": "text", "fields": {"keyword": {"type": "keyword"}}},
|
||||
"org_name": {"type": "text", "fields": {"keyword": {"type": "keyword"}}},
|
||||
"organization": {"type": "text", "fields": {"keyword": {"type": "keyword"}}},
|
||||
"org_uri": {"type": "keyword"},
|
||||
"org_hierarchy_path": {"type": "keyword"},
|
||||
"faculty": {"type": "keyword"},
|
||||
"organization_type": {"type": "keyword"},
|
||||
"organization_level": {"type": "keyword"},
|
||||
"openalex_id": {"type": "keyword"},
|
||||
"oa_organization_ids": {"type": "keyword"},
|
||||
"oa_organization": {
|
||||
"type": "nested",
|
||||
"dynamic": False,
|
||||
"properties": {
|
||||
"id": {"type": "keyword"},
|
||||
"openalex_url": {"type": "keyword"},
|
||||
"display_name": {
|
||||
"type": "text",
|
||||
"fields": {"keyword": {"type": "keyword"}},
|
||||
},
|
||||
"ror": {"type": "keyword"},
|
||||
"country_code": {"type": "keyword"},
|
||||
"type": {"type": "keyword"},
|
||||
"lineage": {"type": "keyword"},
|
||||
"years": {"type": "integer"},
|
||||
"last_known": {"type": "boolean"},
|
||||
},
|
||||
},
|
||||
# Kept verbatim in _source; staff dicts vary, so don't index them.
|
||||
"staff": {"type": "object", "dynamic": False},
|
||||
"staff_entries": {"type": "object", "dynamic": False},
|
||||
@@ -218,6 +270,10 @@ class Stats:
|
||||
person_docs: int = 0
|
||||
uploaded: int = 0
|
||||
doc_errors: int = 0
|
||||
authors_requested: int = 0
|
||||
authors_found: int = 0
|
||||
authors_missing: int = 0
|
||||
persons_with_institutions: int = 0
|
||||
started: float = field(default_factory=time.monotonic)
|
||||
|
||||
@property
|
||||
@@ -229,6 +285,9 @@ class Stats:
|
||||
f"scanned={self.scanned} orgs_done={self.orgs_done} "
|
||||
f"orgs_failed={self.orgs_failed} person_docs={self.person_docs} "
|
||||
f"uploaded={self.uploaded} doc_errors={self.doc_errors} "
|
||||
f"author_lookups={self.authors_found}/{self.authors_requested} "
|
||||
f"authors_missing={self.authors_missing} "
|
||||
f"persons_with_institutions={self.persons_with_institutions} "
|
||||
f"elapsed={time.monotonic() - self.started:.0f}s"
|
||||
)
|
||||
|
||||
@@ -420,22 +479,128 @@ async def scan_organizations(
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Step 2b: LOOK UP author documents for institution metadata
|
||||
# =============================================================================
|
||||
|
||||
|
||||
def normalize_author_id(value: str | None) -> str | None:
|
||||
"""Return the short OpenAlex author ID, accepting raw and URL forms."""
|
||||
if not value:
|
||||
return None
|
||||
normalized = strip_openalex_prefix(value.strip()).strip()
|
||||
return normalized or None
|
||||
|
||||
|
||||
async def _lookup_single_author(short_id: str) -> Author | None:
|
||||
"""Fetch one author, tolerating the different author-document ID schemes.
|
||||
|
||||
The batch lookup normally finds the document through the ``id`` field.
|
||||
This fallback handles documents that only expose the short ``_id`` (direct
|
||||
get) or that are reachable only through a search on ``_id``.
|
||||
"""
|
||||
try:
|
||||
author = await get_author_by_id(short_id)
|
||||
except NotFoundException:
|
||||
author = None
|
||||
if author is not None:
|
||||
return author
|
||||
|
||||
async def _search_by_id() -> Any:
|
||||
return await search_authors(
|
||||
page=0,
|
||||
size=1,
|
||||
query={
|
||||
"terms": {
|
||||
"_id": [
|
||||
short_id,
|
||||
f"https://openalex.org/{short_id}",
|
||||
]
|
||||
}
|
||||
},
|
||||
source=AUTHOR_SOURCE_FIELDS,
|
||||
)
|
||||
|
||||
page = await retry_async(
|
||||
_search_by_id,
|
||||
description=f"Author search for {short_id}",
|
||||
)
|
||||
return page.elements[0] if page.elements else None
|
||||
|
||||
|
||||
async def fetch_authors_by_ids(openalex_ids: Iterable[str]) -> dict[str, Author]:
|
||||
"""Return ``{short_author_id.casefold(): Author}`` for the requested IDs.
|
||||
|
||||
Uses one batched ``id``-terms query per chunk, then a per-person fallback
|
||||
for documents the batch query did not return. Missing authors are omitted
|
||||
so the caller can still write the person document with empty institutions.
|
||||
"""
|
||||
normalized = sorted(
|
||||
{
|
||||
short_id
|
||||
for value in openalex_ids
|
||||
if (short_id := normalize_author_id(value)) is not None
|
||||
}
|
||||
)
|
||||
if not normalized:
|
||||
return {}
|
||||
|
||||
authors: dict[str, Author] = {}
|
||||
for start in range(0, len(normalized), AUTHOR_LOOKUP_BATCH_SIZE):
|
||||
chunk = normalized[start : start + AUTHOR_LOOKUP_BATCH_SIZE]
|
||||
id_terms: list[str] = []
|
||||
for short_id in chunk:
|
||||
id_terms.extend([short_id, f"https://openalex.org/{short_id}"])
|
||||
|
||||
async def _search_batch() -> Any:
|
||||
return await search_authors(
|
||||
page=0,
|
||||
size=len(chunk),
|
||||
query={"terms": {"id": id_terms}},
|
||||
source=AUTHOR_SOURCE_FIELDS,
|
||||
)
|
||||
|
||||
page = await retry_async(
|
||||
_search_batch,
|
||||
description=f"Batch author lookup ({len(chunk)} ids)",
|
||||
)
|
||||
for author in page.elements:
|
||||
author_id = normalize_author_id(author.id)
|
||||
if author_id:
|
||||
authors[author_id.casefold()] = author
|
||||
|
||||
for short_id in chunk:
|
||||
key = short_id.casefold()
|
||||
if key in authors:
|
||||
continue
|
||||
author = await _lookup_single_author(short_id)
|
||||
if author is not None:
|
||||
authors[key] = author
|
||||
|
||||
return authors
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Step 3: BUILD one document per (organization, OpenAlex person)
|
||||
# =============================================================================
|
||||
|
||||
|
||||
def build_hierarchy_lookup(hierarchy: Iterable[Any]) -> HierarchyLookup:
|
||||
"""Map normalized organization links to (display name, path from the root)."""
|
||||
"""Map normalized links to (display name, path, hierarchy node type)."""
|
||||
lookup: HierarchyLookup = {}
|
||||
|
||||
def visit(node: Any, ancestors: list[str]) -> None:
|
||||
name = getattr(node, "name_de", None) or getattr(node, "name_en", None)
|
||||
path = [*ancestors, name] if name else ancestors
|
||||
node_type = getattr(node, "type", None)
|
||||
if name:
|
||||
for link in (getattr(node, "link_de", None), getattr(node, "link_en", None)):
|
||||
if normalized := normalize_org_uri(link):
|
||||
lookup[normalized] = (name, path)
|
||||
lookup[normalized] = (
|
||||
name,
|
||||
path,
|
||||
node_type if isinstance(node_type, str) else None,
|
||||
)
|
||||
for child in getattr(node, "children", None) or []:
|
||||
visit(child, path)
|
||||
|
||||
@@ -446,11 +611,19 @@ def build_hierarchy_lookup(hierarchy: Iterable[Any]) -> HierarchyLookup:
|
||||
|
||||
def organization_details(
|
||||
source: dict[str, Any], hierarchy_lookup: HierarchyLookup
|
||||
) -> tuple[str, list[str], str | None]:
|
||||
"""Return (org name, hierarchy path, org URI), with fallbacks for the name."""
|
||||
) -> OrganizationDetails:
|
||||
"""Build explicit faculty / type / organization fields for a source org.
|
||||
|
||||
For a leaf such as ``Chemie > Lehrstühle > Applied Analytical Chemistry``
|
||||
this yields ``faculty=Chemie``, ``organization_type=Lehrstühle`` and
|
||||
``organization=Applied Analytical Chemistry``. Deeper paths still use the
|
||||
immediate parent as the type, so ``Chemie > Instituten > ACTIVE SITES >
|
||||
Lehrstühle > Applied Analytical Chemistry`` also yields
|
||||
``organization_type=Lehrstühle``.
|
||||
"""
|
||||
org_uri = source.get("uri")
|
||||
hierarchy_name, hierarchy_path = hierarchy_lookup.get(
|
||||
normalize_org_uri(org_uri) or "", ("", [])
|
||||
hierarchy_name, hierarchy_path, node_type = hierarchy_lookup.get(
|
||||
normalize_org_uri(org_uri) or "", ("", [], None)
|
||||
)
|
||||
org_name = (
|
||||
source.get("org_name")
|
||||
@@ -460,7 +633,35 @@ def organization_details(
|
||||
or org_uri
|
||||
or "Unknown organization"
|
||||
)
|
||||
return str(org_name), hierarchy_path, org_uri
|
||||
org_name = str(org_name)
|
||||
|
||||
organization_name = hierarchy_path[-1] if hierarchy_path else org_name
|
||||
if node_type in {"chairs", "institutes", "faculty"}:
|
||||
# Aggregator/faculty documents describe themselves rather than a child.
|
||||
organization_type = organization_name
|
||||
elif len(hierarchy_path) >= 2:
|
||||
organization_type = hierarchy_path[-2]
|
||||
else:
|
||||
organization_type = None
|
||||
|
||||
faculty = hierarchy_path[0] if hierarchy_path else None
|
||||
if not faculty:
|
||||
fallback_faculty = (
|
||||
source.get("faculty_de")
|
||||
or source.get("faculty_en")
|
||||
or source.get("faculty")
|
||||
)
|
||||
faculty = fallback_faculty.strip() if isinstance(fallback_faculty, str) else None
|
||||
faculty = faculty or None
|
||||
|
||||
return OrganizationDetails(
|
||||
name=org_name,
|
||||
uri=org_uri,
|
||||
hierarchy_path=hierarchy_path,
|
||||
faculty=faculty,
|
||||
organization_type=organization_type,
|
||||
organization_level=node_type,
|
||||
)
|
||||
|
||||
|
||||
def stable_document_id(org_uri: str | None, org_doc_id: str, openalex_id: str) -> str:
|
||||
@@ -473,19 +674,145 @@ def _canonical(value: Any) -> str:
|
||||
return json.dumps(value, sort_keys=True, ensure_ascii=False, default=str)
|
||||
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# OpenAlex institution projection
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
INSTITUTION_METADATA_FIELDS = ("display_name", "ror", "country_code", "type")
|
||||
|
||||
|
||||
def normalize_institution_id(value: Any) -> str | None:
|
||||
"""Return the raw OpenAlex institution ID, accepting short and URL forms."""
|
||||
if not isinstance(value, str):
|
||||
return None
|
||||
normalized = strip_openalex_prefix(value.strip()).strip()
|
||||
return normalized or None
|
||||
|
||||
|
||||
def _merge_text(record: dict[str, Any], key: str, value: Any) -> None:
|
||||
if not isinstance(value, str):
|
||||
return
|
||||
value = value.strip()
|
||||
if value and not record.get(key):
|
||||
record[key] = value
|
||||
|
||||
|
||||
def _merge_lineage(record: dict[str, Any], lineage: Any) -> None:
|
||||
if not isinstance(lineage, list):
|
||||
return
|
||||
merged: list[str] = list(record.get("lineage") or [])
|
||||
for item in lineage:
|
||||
if not isinstance(item, str):
|
||||
continue
|
||||
item = item.strip()
|
||||
if item and item not in merged:
|
||||
merged.append(item)
|
||||
if merged:
|
||||
record["lineage"] = merged
|
||||
|
||||
|
||||
def _merge_years(record: dict[str, Any], years: Any) -> None:
|
||||
if not isinstance(years, list):
|
||||
return
|
||||
merged = {int(year) for year in record.get("years") or []}
|
||||
for year in years:
|
||||
try:
|
||||
merged.add(int(year))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
record["years"] = sorted(merged)
|
||||
|
||||
|
||||
def extract_openalex_institutions(author: Author | None) -> list[dict[str, Any]]:
|
||||
"""Return deduplicated OpenAlex institutions for one author.
|
||||
|
||||
``last_known_institutions`` and ``affiliations[].institution`` are merged
|
||||
by OpenAlex institution ID. Affiliation years are unioned and institutions
|
||||
without an OpenAlex ID are skipped. Last-known institutions come first.
|
||||
"""
|
||||
if author is None:
|
||||
return []
|
||||
|
||||
by_id: dict[str, dict[str, Any]] = {}
|
||||
|
||||
def record_for(institution: Any) -> dict[str, Any] | None:
|
||||
if institution is None:
|
||||
return None
|
||||
short_id = normalize_institution_id(getattr(institution, "id", None))
|
||||
if not short_id:
|
||||
return None
|
||||
|
||||
key = short_id.casefold()
|
||||
record = by_id.get(key)
|
||||
if record is None:
|
||||
record = {
|
||||
"id": short_id,
|
||||
"openalex_url": full_institution_url(short_id),
|
||||
"display_name": None,
|
||||
"ror": None,
|
||||
"country_code": None,
|
||||
"type": None,
|
||||
"lineage": [],
|
||||
"years": [],
|
||||
"last_known": False,
|
||||
}
|
||||
by_id[key] = record
|
||||
|
||||
for field in INSTITUTION_METADATA_FIELDS:
|
||||
_merge_text(record, field, getattr(institution, field, None))
|
||||
_merge_lineage(record, getattr(institution, "lineage", None))
|
||||
return record
|
||||
|
||||
for institution in author.last_known_institutions or []:
|
||||
record = record_for(institution)
|
||||
if record is not None:
|
||||
record["last_known"] = True
|
||||
|
||||
for affiliation in author.affiliations or []:
|
||||
record = record_for(getattr(affiliation, "institution", None))
|
||||
if record is not None:
|
||||
_merge_years(record, getattr(affiliation, "years", None))
|
||||
|
||||
return sorted(
|
||||
by_id.values(),
|
||||
key=lambda item: (
|
||||
not item["last_known"],
|
||||
(item.get("display_name") or "").casefold(),
|
||||
item["id"].casefold(),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def openalex_institution_ids(institutions: Iterable[dict[str, Any]]) -> list[str]:
|
||||
"""Return the deduplicated short institution IDs in stable order."""
|
||||
seen: set[str] = set()
|
||||
ids: list[str] = []
|
||||
for institution in institutions:
|
||||
short_id = normalize_institution_id(institution.get("id"))
|
||||
if not short_id:
|
||||
continue
|
||||
key = short_id.casefold()
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
ids.append(short_id)
|
||||
return ids
|
||||
|
||||
|
||||
def make_person_documents(
|
||||
source: dict[str, Any],
|
||||
source_doc_id: str,
|
||||
verified_entries: list[dict[str, Any]],
|
||||
hierarchy_lookup: HierarchyLookup,
|
||||
verified_at: str,
|
||||
authors_by_id: dict[str, Author],
|
||||
) -> list[tuple[str, Hit]]:
|
||||
"""Turn verified staff entries into [(doc_id, document)], one per OpenAlex person.
|
||||
|
||||
A person may be matched by several staff entries and several collaborators,
|
||||
so entries and evidence are de-duplicated per person first.
|
||||
"""
|
||||
org_name, hierarchy_path, org_uri = organization_details(source, hierarchy_lookup)
|
||||
details = organization_details(source, hierarchy_lookup)
|
||||
|
||||
# openalex_id -> {canonical staff json -> staff dict}
|
||||
staff_by_person: dict[str, dict[str, dict[str, Any]]] = {}
|
||||
@@ -507,12 +834,20 @@ def make_person_documents(
|
||||
for openalex_id, staff_map in staff_by_person.items():
|
||||
staff_entries = list(staff_map.values())
|
||||
primary_staff = staff_entries[0]
|
||||
author_id = normalize_author_id(openalex_id)
|
||||
author = authors_by_id.get(author_id.casefold()) if author_id else None
|
||||
institutions = extract_openalex_institutions(author)
|
||||
document = {
|
||||
"name": primary_staff.get("name"),
|
||||
"org_name": org_name,
|
||||
"org_uri": org_uri,
|
||||
"org_hierarchy_path": hierarchy_path,
|
||||
"organization": details.name,
|
||||
"org_uri": details.uri,
|
||||
"org_hierarchy_path": details.hierarchy_path,
|
||||
"faculty": details.faculty,
|
||||
"organization_type": details.organization_type,
|
||||
"organization_level": details.organization_level,
|
||||
"openalex_id": openalex_id,
|
||||
"oa_organization_ids": openalex_institution_ids(institutions),
|
||||
"oa_organization": institutions,
|
||||
"staff": primary_staff,
|
||||
"staff_entries": staff_entries,
|
||||
"source_index": SOURCE_INDEX,
|
||||
@@ -521,7 +856,7 @@ def make_person_documents(
|
||||
"verification_evidence": list(evidence_by_person[openalex_id].values()),
|
||||
"verified_at": verified_at,
|
||||
}
|
||||
doc_id = stable_document_id(org_uri, source_doc_id, openalex_id)
|
||||
doc_id = stable_document_id(details.uri, source_doc_id, openalex_id)
|
||||
documents.append((doc_id, document))
|
||||
return documents
|
||||
|
||||
@@ -537,7 +872,28 @@ async def ensure_output_index(
|
||||
"""Create the output index with its mapping if it doesn't exist yet."""
|
||||
head = await client.head(f"{url}/{OUTPUT_INDEX}", headers=headers)
|
||||
if head.status_code == 200:
|
||||
logger.info("Output index %r already exists.", OUTPUT_INDEX)
|
||||
mapping_response = await client.get(
|
||||
f"{url}/{OUTPUT_INDEX}/_mapping", headers=headers
|
||||
)
|
||||
mapping_response.raise_for_status()
|
||||
properties = (
|
||||
mapping_response.json()
|
||||
.get(OUTPUT_INDEX, {})
|
||||
.get("mappings", {})
|
||||
.get("properties", {})
|
||||
)
|
||||
missing_fields = [
|
||||
field
|
||||
for field in ("oa_organization_ids", "oa_organization")
|
||||
if field not in properties
|
||||
]
|
||||
if missing_fields:
|
||||
raise SystemExit(
|
||||
f"Output index {OUTPUT_INDEX!r} already exists but is missing "
|
||||
f"{missing_fields}. Delete the index before uploading the new "
|
||||
"schema, or choose a different OUTPUT_INDEX."
|
||||
)
|
||||
logger.info("Output index %r already exists with the current schema.", OUTPUT_INDEX)
|
||||
return
|
||||
if head.status_code != 404:
|
||||
head.raise_for_status()
|
||||
@@ -696,18 +1052,55 @@ async def process_organization(hit: Hit, ctx: Context) -> bool:
|
||||
description=f"Collab-graph verification for {label}",
|
||||
)
|
||||
|
||||
# Step 2b: load OpenAlex author documents for institution metadata.
|
||||
requested_author_ids = {
|
||||
short_id
|
||||
for entry in verified_entries
|
||||
for openalex_id in entry["openalex_ids"]
|
||||
if (short_id := normalize_author_id(openalex_id)) is not None
|
||||
}
|
||||
authors_by_id = await fetch_authors_by_ids(requested_author_ids)
|
||||
found_author_ids = {
|
||||
short_id
|
||||
for short_id in requested_author_ids
|
||||
if short_id.casefold() in authors_by_id
|
||||
}
|
||||
missing_author_ids = requested_author_ids - found_author_ids
|
||||
ctx.stats.authors_requested += len(requested_author_ids)
|
||||
ctx.stats.authors_found += len(found_author_ids)
|
||||
ctx.stats.authors_missing += len(missing_author_ids)
|
||||
if missing_author_ids:
|
||||
logger.warning(
|
||||
"No OpenAlex author document for %d verified person(s) in %s: %s",
|
||||
len(missing_author_ids),
|
||||
label,
|
||||
", ".join(sorted(missing_author_ids)),
|
||||
)
|
||||
|
||||
# Step 3: build one document per OpenAlex person.
|
||||
documents = make_person_documents(
|
||||
source, doc_id, verified_entries, ctx.hierarchy_lookup, ctx.verified_at
|
||||
source,
|
||||
doc_id,
|
||||
verified_entries,
|
||||
ctx.hierarchy_lookup,
|
||||
ctx.verified_at,
|
||||
authors_by_id,
|
||||
)
|
||||
ctx.stats.person_docs += len(documents)
|
||||
ctx.stats.persons_with_institutions += sum(
|
||||
1 for _, document in documents if document.get("oa_organization")
|
||||
)
|
||||
|
||||
if ctx.dry_run:
|
||||
logger.info(
|
||||
"DRY RUN org=%s verified_staff=%d person_org_docs=%d",
|
||||
"DRY RUN org=%s verified_staff=%d person_org_docs=%d "
|
||||
"authors=%d/%d missing=%d",
|
||||
label,
|
||||
len(verified_entries),
|
||||
len(documents),
|
||||
len(found_author_ids),
|
||||
len(requested_author_ids),
|
||||
len(missing_author_ids),
|
||||
)
|
||||
return True
|
||||
|
||||
|
||||
Reference in New Issue
Block a user