chore(work-classifications): add classification summary reports

This commit is contained in:
Roman
2026-07-21 03:33:13 +02:00
parent c368ea8f59
commit 82fe042b2b
5 changed files with 45866 additions and 0 deletions
@@ -0,0 +1,543 @@
{
"author": {
"id": "https://openalex.org/A5034365278",
"display_name": "Dirk Schadendorf",
"card_works_count": 2376,
"cited_by_count": 221896
},
"webapp_publication_list": {
"endpoint": "/api/v2/works/author/A5034365278?page=0&size=50",
"raw_hits_total_value": 2406,
"raw_hits_total_relation": "eq",
"raw_documents_scanned": 2406,
"unique_openalex_work_ids": 2370,
"duplicate_raw_documents": 36,
"work_ids_with_multiple_source_documents": 36
},
"classification_pipeline": {
"minimum_publication_year": 1950,
"eligible_unique_work_ids": 2369,
"pre_threshold_unique_work_ids": 0,
"missing_year_unique_work_ids": 1,
"classified_by_target_id": 2369,
"eligible_but_missing_in_target": 0,
"classified_target_documents_containing_author": 2369,
"classified_by_id_but_author_missing_from_target_document": 0
},
"institution": {
"id": "https://openalex.org/I62318514",
"pipeline_selected_source_works_matching_institution": 422
},
"important_differences": [
"The author card reads openalex-authors.works_count directly.",
"The publication list counts raw hits from openalex-works* and does not deduplicate by work ID.",
"The classification pipeline deduplicates by normalized OpenAlex work ID.",
"The classification pipeline excludes works with publication_year below 1950 or missing.",
"A work can exist in the classification index but be absent from a per-author target-index count if the stored authors array does not contain that author."
],
"examples": {
"eligible_but_missing_in_target": [],
"publication_year_before_threshold": [],
"publication_year_missing": [
{
"work_id": "W4211208194",
"full_work_id": "https://openalex.org/W4211208194",
"title": "",
"publication_year": null,
"type": "article",
"doi": null,
"updated_date": "2025-11-06T04:12:42.849Z",
"source_index": "openalex-works-3",
"variant_count": 1,
"variant_indices": ["openalex-works-3"],
"classified_by_id": false,
"classification_contains_author": false,
"institution_match": true,
"reason": "publication_year_missing"
}
],
"multiple_source_documents_same_id": [
{
"work_id": "W4409451759",
"full_work_id": "https://openalex.org/W4409451759",
"title": "Clinical validation of droplet digital PCR assays in detecting BRAFV600-mutant circulating tumour DNA as a prognostic biomarker in patients with resected stage III melanoma receiving adjuvant therapy (COMBI-AD): a biomarker analysis from a double-blind, randomised phase 3 trial",
"publication_year": 2025,
"type": "article",
"doi": "https://doi.org/10.1016/s1470-2045(25)00139-1",
"updated_date": "2026-01-13T01:12:25.745Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-4", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W4409145101",
"full_work_id": "https://openalex.org/W4409145101",
"title": "Acral lentiginous melanoma shows a poorer response to immune checkpoint inhibition in the non-resectable or metastatic setting – A EUMelaReg real world outcome study",
"publication_year": 2025,
"type": "article",
"doi": "https://doi.org/10.1016/j.ejcskn.2025.100527",
"updated_date": "2026-03-13T14:20:09.374Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-4", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W4405380398",
"full_work_id": "https://openalex.org/W4405380398",
"title": "A comparison of real-world data on adjuvant treatment in patients with stage III BRAF V600 mutated melanoma – Results of systematic literature research",
"publication_year": 2024,
"type": "review",
"doi": "https://doi.org/10.1016/j.ejca.2024.115160",
"updated_date": "2026-03-13T14:20:09.374Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-4", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W4402565731",
"full_work_id": "https://openalex.org/W4402565731",
"title": "LBA43 10-y survival outcomes from the phase III CheckMate 067 trial of nivolumab plus ipilimumab in advanced melanoma",
"publication_year": 2024,
"type": "article",
"doi": "https://doi.org/10.1016/j.annonc.2024.08.2284",
"updated_date": "2026-03-13T14:20:09.374Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-4", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W4402560903",
"full_work_id": "https://openalex.org/W4402560903",
"title": "1078MO Pembrolizumab (pembro) vs placebo as adjuvant therapy for high-risk stage II melanoma: Long-term follow-up, rechallenge, and crossover in KEYNOTE-716",
"publication_year": 2024,
"type": "article",
"doi": "https://doi.org/10.1016/j.annonc.2024.08.1146",
"updated_date": "2026-03-13T14:20:09.374Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-4", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W4391886851",
"full_work_id": "https://openalex.org/W4391886851",
"title": "Biomarker and pharmacodynamic activity of the transforming growth factor‐beta (<scp>TGFβ)</scp> inhibitor <scp>SAR439459</scp> as monotherapy and in combination with cemiplimab in a phase I clinical study in patients with advanced solid tumors",
"publication_year": 2024,
"type": "article",
"doi": "https://doi.org/10.1111/cts.13736",
"updated_date": "2026-03-13T14:20:09.374Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-4", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W4391430347",
"full_work_id": "https://openalex.org/W4391430347",
"title": "Prognostic and predictive value of non-steroidal anti-inflammatory drugs in the EORTC 1325/KEYNOTE-054 phase III trial of pembrolizumab versus placebo in resected high-risk stage III melanoma",
"publication_year": 2024,
"type": "article",
"doi": "https://doi.org/10.1016/j.ejca.2024.113585",
"updated_date": "2026-01-13T01:12:25.745Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-4", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W4362505674",
"full_work_id": "https://openalex.org/W4362505674",
"title": "The Latest Option: Nivolumab and Relatlimab in Advanced Melanoma",
"publication_year": 2023,
"type": "review",
"doi": "https://doi.org/10.1007/s11912-023-01406-4",
"updated_date": "2026-01-13T01:12:25.745Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-3", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": true,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W4353055387",
"full_work_id": "https://openalex.org/W4353055387",
"title": "Health-related quality of life with nivolumab plus relatlimab versus nivolumab monotherapy in patients with previously untreated unresectable or metastatic melanoma: RELATIVITY-047 trial",
"publication_year": 2023,
"type": "article",
"doi": "https://doi.org/10.1016/j.ejca.2023.03.014",
"updated_date": "2026-03-13T14:20:09.374Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-4", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W4282559953",
"full_work_id": "https://openalex.org/W4282559953",
"title": "Innate immune receptor signaling induces transient melanoma dedifferentiation while preserving immunogenicity",
"publication_year": 2022,
"type": "article",
"doi": "https://doi.org/10.1136/jitc-2021-003863",
"updated_date": "2025-11-06T03:46:38.306Z",
"source_index": "openalex-works",
"variant_count": 2,
"variant_indices": ["openalex-works", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": true,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W3157996908",
"full_work_id": "https://openalex.org/W3157996908",
"title": "Computed tomography-guided biopsy of radiologically unclear lesions in advanced skin cancer: A retrospective analysis of 47 cases",
"publication_year": 2021,
"type": "article",
"doi": "https://doi.org/10.1016/j.ejca.2021.03.026",
"updated_date": "2026-01-13T01:12:25.745Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-3", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W3108194869",
"full_work_id": "https://openalex.org/W3108194869",
"title": "Surveillance of patients with conjunctival melanoma in German-speaking countries: A multinational survey of the German dermatologic cooperative oncology group",
"publication_year": 2020,
"type": "letter",
"doi": "https://doi.org/10.1016/j.ejca.2020.10.021",
"updated_date": "2026-01-13T01:12:25.745Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-3", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W2967473922",
"full_work_id": "https://openalex.org/W2967473922",
"title": "Deep neural networks are superior to dermatologists in melanoma image classification",
"publication_year": 2019,
"type": "article",
"doi": "https://doi.org/10.1016/j.ejca.2019.05.023",
"updated_date": "2026-01-13T01:12:25.745Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-3", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W2950219014",
"full_work_id": "https://openalex.org/W2950219014",
"title": "The X-Linked DDX3X RNA Helicase Dictates Translation Reprogramming and Metastasis in Melanoma",
"publication_year": 2019,
"type": "article",
"doi": "https://doi.org/10.1016/j.celrep.2019.05.069",
"updated_date": "2026-01-13T01:12:25.745Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-4", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W2790093035",
"full_work_id": "https://openalex.org/W2790093035",
"title": "Clinical outcome of concomitant vs interrupted BRAF inhibitor therapy during radiotherapy in melanoma patients",
"publication_year": 2018,
"type": "article",
"doi": "https://doi.org/10.1038/bjc.2017.489",
"updated_date": "2026-01-13T01:12:25.745Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-4", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W2773801101",
"full_work_id": "https://openalex.org/W2773801101",
"title": "Eighth American Joint Committee on Cancer (AJCC) melanoma classification: Let us reconsider stage III",
"publication_year": 2017,
"type": "letter",
"doi": "https://doi.org/10.1016/j.ejca.2017.11.023",
"updated_date": "2026-01-13T01:12:25.745Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-3", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W2767826944",
"full_work_id": "https://openalex.org/W2767826944",
"title": "A phase 2 study of ontuxizumab, a monoclonal antibody targeting endosialin, in metastatic melanoma",
"publication_year": 2017,
"type": "article",
"doi": "https://doi.org/10.1007/s10637-017-0530-4",
"updated_date": "2026-01-13T01:12:25.745Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-3", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W2901161788",
"full_work_id": "https://openalex.org/W2901161788",
"title": "7503-114079-1-Sp",
"publication_year": 2016,
"type": "article",
"doi": null,
"updated_date": "2025-11-06T04:12:42.849Z",
"source_index": "openalex-works-2",
"variant_count": 2,
"variant_indices": ["openalex-works-2", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W2308247172",
"full_work_id": "https://openalex.org/W2308247172",
"title": "Integrating first-line treatment options into clinical practice",
"publication_year": 2015,
"type": "review",
"doi": "https://doi.org/10.1097/cmr.0000000000000200",
"updated_date": "2026-01-13T01:12:25.745Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-3", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W2053545055",
"full_work_id": "https://openalex.org/W2053545055",
"title": "Expression of stress ligands of the immunoreceptor NKG2D in melanoma: Regulation and clinical significance",
"publication_year": 2014,
"type": "review",
"doi": "https://doi.org/10.1016/j.ejcb.2014.01.009",
"updated_date": "2026-01-13T01:12:25.745Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-4", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W2112537584",
"full_work_id": "https://openalex.org/W2112537584",
"title": "Adjuvant pegylated interferon α-2b therapy for melanoma",
"publication_year": 2010,
"type": "article",
"doi": "https://doi.org/10.3892/ol_00000042",
"updated_date": "2026-01-13T01:12:25.745Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-4", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W1967863327",
"full_work_id": "https://openalex.org/W1967863327",
"title": "Screening of Human Tumor Antigens for CD4+ T Cell Epitopes by Combination of HLA-Transgenic Mice, Recombinant Adenovirus and Antigen Peptide Libraries",
"publication_year": 2010,
"type": "article",
"doi": "https://doi.org/10.1371/journal.pone.0014137",
"updated_date": "2026-01-13T01:12:25.745Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-3", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W2124806374",
"full_work_id": "https://openalex.org/W2124806374",
"title": "Multiple Melanomas After Treatment for Hodgkin Lymphoma in a Non-Dutch p16-Leiden Mutation Carrier With 2 MC1R High-Risk Variants",
"publication_year": 2007,
"type": "article",
"doi": "https://doi.org/10.1001/archderm.143.4.495",
"updated_date": "2026-01-13T01:12:25.745Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-4", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W2149012823",
"full_work_id": "https://openalex.org/W2149012823",
"title": "P-glycoprotein expression in primary and metastatic malignant melanoma",
"publication_year": 2006,
"type": "article",
"doi": "https://doi.org/10.1111/j.1365-2133.1995.tb08710.x",
"updated_date": "2026-01-13T01:12:25.745Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-4", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W2047303314",
"full_work_id": "https://openalex.org/W2047303314",
"title": "Expression of GAGE family proteins in malignant melanoma",
"publication_year": 2006,
"type": "article",
"doi": "https://doi.org/10.1016/j.canlet.2006.11.022",
"updated_date": "2026-01-13T01:12:25.745Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-3", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W1963965528",
"full_work_id": "https://openalex.org/W1963965528",
"title": "Photoreceptor proteins as cancer‐retina antigens",
"publication_year": 2006,
"type": "article",
"doi": "https://doi.org/10.1002/ijc.22458",
"updated_date": "2026-01-13T01:12:25.745Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-4", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W2404943841",
"full_work_id": "https://openalex.org/W2404943841",
"title": "[Acute juvenile pityriasis rubra pilaris in a 2-year-old child].",
"publication_year": 2004,
"type": "article",
"doi": null,
"updated_date": "2025-11-06T04:12:42.849Z",
"source_index": "openalex-works-3",
"variant_count": 2,
"variant_indices": ["openalex-works-3", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W2037452525",
"full_work_id": "https://openalex.org/W2037452525",
"title": "mRNA expression of tumor‐associated antigens in melanoma tissues and cell lines",
"publication_year": 2002,
"type": "article",
"doi": "https://doi.org/10.1034/j.1600-0625.2002.110402.x",
"updated_date": "2026-01-13T01:12:25.745Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-4", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W1983494843",
"full_work_id": "https://openalex.org/W1983494843",
"title": "Study of Therapy Resistance in Cancer Cells with Functional Proteome Analysis",
"publication_year": 2002,
"type": "review",
"doi": "https://doi.org/10.1515/cclm.2002.037",
"updated_date": "2026-01-13T01:12:25.745Z",
"source_index": "openalex-works-5",
"variant_count": 2,
"variant_indices": ["openalex-works-3", "openalex-works-5"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
},
{
"work_id": "W2598959332",
"full_work_id": "https://openalex.org/W2598959332",
"title": "‘PEG meets Liposome’ – zwei Technologien führen zu einer Substanz mit neuem Profil",
"publication_year": 2001,
"type": "article",
"doi": "https://doi.org/10.1159/000050295",
"updated_date": "2025-11-06T03:46:38.306Z",
"source_index": "openalex-works",
"variant_count": 2,
"variant_indices": ["openalex-works", "openalex-works-2"],
"classified_by_id": true,
"classification_contains_author": true,
"institution_match": false,
"reason": "multiple_source_documents_same_openalex_id"
}
],
"classified_but_author_missing": []
}
}
@@ -0,0 +1,755 @@
#!/usr/bin/env python3
"""Compare the three publication-counting approaches for one OpenAlex author.
The script compares:
1. The author card value from openalex-authors.works_count.
2. The publication-list backend query used by /person/{id}/publications.
3. The classification-pipeline set based on unique OpenAlex work IDs since 1950.
4. Existing documents in work-classifications.
It also writes concrete discrepancy examples to JSON and CSV files.
No credentials are hardcoded. The script reads:
- ELASTICSEARCH_URL
- ELASTICSEARCH_API_KEY
from service/src/main/inse/.env or from the process environment.
python compare_author_publication_counts.py ^ --project-root . ^ --author-id A5034365278 ^ --institution-id I62318514
"""
from __future__ import annotations
import argparse
import csv
import json
import os
import sys
from collections import defaultdict
from pathlib import Path
from typing import Any, Iterable
import requests
DEFAULT_AUTHOR_ID = "A5034365278"
DEFAULT_WORK_YEAR_GTE = 1950
SOURCE_INDEX = "openalex-works*"
AUTHOR_INDEX = "openalex-authors"
TARGET_INDEX = "work-classifications"
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Compare author publication counts across the webapp and classification index."
)
parser.add_argument(
"--author-id",
default=DEFAULT_AUTHOR_ID,
help="OpenAlex author ID, for example A5034365278.",
)
parser.add_argument(
"--project-root",
type=Path,
default=Path.cwd(),
help="Project root containing service/src/main/inse/.env.",
)
parser.add_argument(
"--env-file",
type=Path,
default=None,
help="Explicit .env file. Defaults to service/src/main/inse/.env.",
)
parser.add_argument(
"--institution-id",
default=None,
help=(
"Optional OpenAlex institution ID used to inspect institution-specific works, "
"for example I62318514."
),
)
parser.add_argument(
"--work-year-gte",
type=int,
default=DEFAULT_WORK_YEAR_GTE,
help="Minimum publication year used by the classification pipeline.",
)
parser.add_argument(
"--output-dir",
type=Path,
default=Path("author_publication_comparison"),
help="Directory for JSON and CSV output.",
)
parser.add_argument(
"--example-limit",
type=int,
default=30,
help="Maximum number of examples per discrepancy group.",
)
return parser.parse_args()
def read_env_file(path: Path) -> dict[str, str]:
values: dict[str, str] = {}
if not path.exists():
return values
for raw_line in path.read_text(encoding="utf-8").splitlines():
line = raw_line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, value = line.split("=", 1)
values[key.strip()] = value.strip().strip('"').strip("'")
return values
def load_credentials(args: argparse.Namespace) -> tuple[str, str]:
env_file = args.env_file
if env_file is None:
env_file = args.project_root / "service" / "src" / "main" / "inse" / ".env"
file_values = read_env_file(env_file)
base_url = (
os.getenv("ELASTICSEARCH_URL") or file_values.get("ELASTICSEARCH_URL") or ""
).rstrip("/")
api_key = (
os.getenv("ELASTICSEARCH_API_KEY")
or file_values.get("ELASTICSEARCH_API_KEY")
or ""
).strip()
if not base_url:
raise RuntimeError(
f"ELASTICSEARCH_URL is missing. Set it in the environment or in {env_file}."
)
if not api_key:
raise RuntimeError(
"ELASTICSEARCH_API_KEY is missing. Set it in the environment or in "
f"{env_file}."
)
return base_url, api_key
def full_openalex_id(value: str, prefix: str) -> str:
clean = value.strip().rstrip("/").rsplit("/", 1)[-1]
if not clean.startswith(prefix):
raise ValueError(f"Unexpected OpenAlex ID: {value}")
return f"https://openalex.org/{clean}"
def short_openalex_id(value: Any) -> str | None:
if not isinstance(value, str) or not value.strip():
return None
return value.strip().rstrip("/").rsplit("/", 1)[-1]
class ElasticsearchClient:
def __init__(self, base_url: str, api_key: str) -> None:
self.base_url = base_url.rstrip("/")
self.session = requests.Session()
self.session.headers.update(
{
"Authorization": f"ApiKey {api_key}",
"Content-Type": "application/json",
"Accept": "application/json",
}
)
def request(
self,
method: str,
path: str,
*,
body: dict[str, Any] | None = None,
params: dict[str, Any] | None = None,
timeout: float = 120.0,
) -> dict[str, Any]:
response = self.session.request(
method,
f"{self.base_url}/{path.lstrip('/')}",
json=body,
params=params,
timeout=timeout,
)
if not response.ok:
raise RuntimeError(
f"Elasticsearch {response.status_code} for {path}: "
f"{response.text[:1000]}"
)
if not response.content:
return {}
return response.json()
def get_author(self, short_author_id: str) -> dict[str, Any]:
result = self.request(
"GET",
f"{AUTHOR_INDEX}/_doc/{short_author_id}",
params={"_source": "id,display_name,works_count,cited_by_count"},
)
source = result.get("_source")
if not isinstance(source, dict):
raise RuntimeError(f"Author not found: {short_author_id}")
return source
def search_publication_page(
self,
full_author_id: str,
*,
page: int = 0,
size: int = 50,
) -> dict[str, Any]:
query = author_query(full_author_id)
body = {
"query": query,
"_source": [
"id",
"title",
"type",
"publication_year",
"language",
"cited_by_count",
"authorships.author",
"authorships.institutions.id",
"topics",
],
"from": page * size,
"size": size,
"sort": [{"publication_year": "desc"}],
}
return self.request("POST", f"{SOURCE_INDEX}/_search", body=body)
def scroll_author_works(
self,
full_author_id: str,
*,
page_size: int = 1000,
) -> list[dict[str, Any]]:
body = {
"size": page_size,
"track_total_hits": True,
"query": author_query(full_author_id),
"_source": [
"id",
"doi",
"title",
"display_name",
"publication_year",
"updated_date",
"type",
"authorships.author.id",
"authorships.author.display_name",
"authorships.institutions.id",
"authorships.institutions.display_name",
],
"sort": ["_doc"],
}
result = self.request(
"POST",
f"{SOURCE_INDEX}/_search",
body=body,
params={"scroll": "2m"},
)
scroll_id = result.get("_scroll_id")
hits: list[dict[str, Any]] = []
try:
while True:
page_hits = result.get("hits", {}).get("hits", [])
if not page_hits:
break
hits.extend(hit for hit in page_hits if isinstance(hit, dict))
if not scroll_id:
break
result = self.request(
"POST",
"_search/scroll",
body={"scroll": "2m", "scroll_id": scroll_id},
)
scroll_id = result.get("_scroll_id", scroll_id)
finally:
if scroll_id:
try:
self.request(
"DELETE",
"_search/scroll",
body={"scroll_id": [scroll_id]},
)
except Exception:
pass
return hits
def mget_classifications(
self,
short_work_ids: list[str],
*,
chunk_size: int = 500,
) -> dict[str, dict[str, Any]]:
result: dict[str, dict[str, Any]] = {}
for start in range(0, len(short_work_ids), chunk_size):
chunk = short_work_ids[start : start + chunk_size]
response = self.request(
"POST",
f"{TARGET_INDEX}/_mget",
body={"ids": chunk},
params={
"_source_includes": ",".join(
[
"work_id",
"title",
"publication_year",
"authors.id",
"classification.primary_category",
"classification_meta.prompt_version",
]
)
},
)
for document in response.get("docs", []):
if isinstance(document, dict):
result[str(document.get("_id"))] = document
return result
def count_classifications_by_author(self, full_author_id: str) -> int:
response = self.request(
"POST",
f"{TARGET_INDEX}/_count",
body={
"query": {
"nested": {
"path": "authors",
"query": {"term": {"authors.id": full_author_id}},
}
}
},
)
return int(response.get("count", 0))
def author_query(full_author_id: str) -> dict[str, Any]:
return {
"nested": {
"path": "authorships",
"query": {"term": {"authorships.author.id": full_author_id}},
}
}
def choose_pipeline_hit(
current: dict[str, Any] | None,
candidate: dict[str, Any],
) -> dict[str, Any]:
"""Reproduce classify_ude_works_to_index.py source-version selection."""
if current is None:
return candidate
current_index = current.get("_index")
candidate_index = candidate.get("_index")
if candidate_index == "openalex-works" and current_index != "openalex-works":
return candidate
if current_index == "openalex-works" and candidate_index != "openalex-works":
return current
current_source = current.get("_source")
candidate_source = candidate.get("_source")
current_updated = (
current_source.get("updated_date") if isinstance(current_source, dict) else None
)
candidate_updated = (
candidate_source.get("updated_date")
if isinstance(candidate_source, dict)
else None
)
if isinstance(candidate_updated, str):
if not isinstance(current_updated, str) or candidate_updated > current_updated:
return candidate
return current
def work_record(hit: dict[str, Any]) -> dict[str, Any]:
source = hit.get("_source")
if not isinstance(source, dict):
source = {}
work_id = short_openalex_id(source.get("id") or hit.get("_id"))
return {
"work_id": work_id,
"full_work_id": (f"https://openalex.org/{work_id}" if work_id else None),
"title": source.get("title") or source.get("display_name"),
"publication_year": source.get("publication_year"),
"type": source.get("type"),
"doi": source.get("doi"),
"updated_date": source.get("updated_date"),
"source_index": hit.get("_index"),
}
def author_ids_in_source(source: dict[str, Any]) -> set[str]:
result: set[str] = set()
for authorship in source.get("authorships") or []:
if not isinstance(authorship, dict):
continue
author = authorship.get("author")
if not isinstance(author, dict):
continue
author_id = author.get("id")
if isinstance(author_id, str):
result.add(author_id)
return result
def institution_ids_in_source(source: dict[str, Any]) -> set[str]:
result: set[str] = set()
for authorship in source.get("authorships") or []:
if not isinstance(authorship, dict):
continue
for institution in authorship.get("institutions") or []:
if not isinstance(institution, dict):
continue
institution_id = institution.get("id")
if isinstance(institution_id, str):
result.add(institution_id)
return result
def classification_author_ids(document: dict[str, Any]) -> set[str]:
source = document.get("_source")
if not isinstance(source, dict):
return set()
result: set[str] = set()
for author in source.get("authors") or []:
if isinstance(author, dict) and isinstance(author.get("id"), str):
result.add(author["id"])
return result
def sort_work_records(records: Iterable[dict[str, Any]]) -> list[dict[str, Any]]:
return sorted(
records,
key=lambda item: (
item.get("publication_year") is not None,
item.get("publication_year") or -1,
item.get("work_id") or "",
),
reverse=True,
)
def write_csv(path: Path, rows: list[dict[str, Any]]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
fieldnames = [
"work_id",
"full_work_id",
"title",
"publication_year",
"type",
"doi",
"updated_date",
"source_index",
"variant_count",
"variant_indices",
"classified_by_id",
"classification_contains_author",
"institution_match",
"reason",
]
with path.open("w", encoding="utf-8-sig", newline="") as handle:
writer = csv.DictWriter(handle, fieldnames=fieldnames, extrasaction="ignore")
writer.writeheader()
writer.writerows(rows)
def main() -> int:
args = parse_args()
base_url, api_key = load_credentials(args)
client = ElasticsearchClient(base_url, api_key)
short_author_id = short_openalex_id(args.author_id)
if short_author_id is None:
raise RuntimeError("Author ID is empty.")
full_author_id = full_openalex_id(short_author_id, "A")
full_institution_id: str | None = None
if args.institution_id:
short_institution_id = short_openalex_id(args.institution_id)
if short_institution_id is None:
raise RuntimeError("Institution ID is empty.")
full_institution_id = full_openalex_id(short_institution_id, "I")
output_dir = args.output_dir
output_dir.mkdir(parents=True, exist_ok=True)
print(f"Loading author {short_author_id}...")
author = client.get_author(short_author_id)
print("Reproducing the publication-list query...")
publication_page = client.search_publication_page(
full_author_id,
page=0,
size=50,
)
page_total = publication_page.get("hits", {}).get("total", {})
page_total_value = (
int(page_total.get("value", 0))
if isinstance(page_total, dict)
else int(page_total or 0)
)
page_total_relation = (
page_total.get("relation") if isinstance(page_total, dict) else None
)
print("Scanning all matching source documents...")
raw_hits = client.scroll_author_works(full_author_id)
variants_by_work_id: dict[str, list[dict[str, Any]]] = defaultdict(list)
pipeline_hit_by_work_id: dict[str, dict[str, Any]] = {}
for hit in raw_hits:
source = hit.get("_source")
if not isinstance(source, dict):
continue
work_id = short_openalex_id(source.get("id") or hit.get("_id"))
if not work_id:
continue
variants_by_work_id[work_id].append(hit)
pipeline_hit_by_work_id[work_id] = choose_pipeline_hit(
pipeline_hit_by_work_id.get(work_id),
hit,
)
unique_work_ids = sorted(pipeline_hit_by_work_id)
eligible_work_ids: list[str] = []
pre_threshold_work_ids: list[str] = []
missing_year_work_ids: list[str] = []
for work_id, hit in pipeline_hit_by_work_id.items():
source = hit.get("_source")
if not isinstance(source, dict):
continue
year = source.get("publication_year")
if isinstance(year, bool) or not isinstance(year, int):
missing_year_work_ids.append(work_id)
elif year < args.work_year_gte:
pre_threshold_work_ids.append(work_id)
else:
eligible_work_ids.append(work_id)
print("Loading matching classification documents...")
classification_docs = client.mget_classifications(eligible_work_ids)
classified_author_count = client.count_classifications_by_author(full_author_id)
classified_by_id: list[str] = []
unclassified_eligible: list[str] = []
classified_but_author_missing: list[str] = []
for work_id in eligible_work_ids:
document = classification_docs.get(work_id)
if document and document.get("found"):
classified_by_id.append(work_id)
if full_author_id not in classification_author_ids(document):
classified_but_author_missing.append(work_id)
else:
unclassified_eligible.append(work_id)
duplicate_work_ids = [
work_id
for work_id, variants in variants_by_work_id.items()
if len(variants) > 1
]
institution_matching_work_ids: list[str] = []
if full_institution_id:
for work_id, hit in pipeline_hit_by_work_id.items():
source = hit.get("_source")
if not isinstance(source, dict):
continue
if full_institution_id in institution_ids_in_source(source):
institution_matching_work_ids.append(work_id)
def enrich(work_id: str, reason: str) -> dict[str, Any]:
hit = pipeline_hit_by_work_id[work_id]
record = work_record(hit)
variants = variants_by_work_id.get(work_id, [])
classification = classification_docs.get(work_id)
source = hit.get("_source")
institution_match = None
if full_institution_id and isinstance(source, dict):
institution_match = full_institution_id in institution_ids_in_source(source)
record.update(
{
"variant_count": len(variants),
"variant_indices": sorted(
{
str(variant.get("_index"))
for variant in variants
if variant.get("_index")
}
),
"classified_by_id": bool(
classification and classification.get("found")
),
"classification_contains_author": bool(
classification
and classification.get("found")
and full_author_id in classification_author_ids(classification)
),
"institution_match": institution_match,
"reason": reason,
}
)
return record
unclassified_examples = sort_work_records(
enrich(work_id, "eligible_since_threshold_but_missing_in_target")
for work_id in unclassified_eligible
)
pre_threshold_examples = sort_work_records(
enrich(work_id, f"publication_year_before_{args.work_year_gte}")
for work_id in pre_threshold_work_ids
)
missing_year_examples = sort_work_records(
enrich(work_id, "publication_year_missing") for work_id in missing_year_work_ids
)
duplicate_examples = sort_work_records(
enrich(work_id, "multiple_source_documents_same_openalex_id")
for work_id in duplicate_work_ids
)
author_missing_examples = sort_work_records(
enrich(work_id, "classified_target_document_does_not_contain_author")
for work_id in classified_but_author_missing
)
summary = {
"author": {
"id": full_author_id,
"display_name": author.get("display_name"),
"card_works_count": author.get("works_count"),
"cited_by_count": author.get("cited_by_count"),
},
"webapp_publication_list": {
"endpoint": f"/api/v2/works/author/{short_author_id}?page=0&size=50",
"raw_hits_total_value": page_total_value,
"raw_hits_total_relation": page_total_relation,
"raw_documents_scanned": len(raw_hits),
"unique_openalex_work_ids": len(unique_work_ids),
"duplicate_raw_documents": len(raw_hits) - len(unique_work_ids),
"work_ids_with_multiple_source_documents": len(duplicate_work_ids),
},
"classification_pipeline": {
"minimum_publication_year": args.work_year_gte,
"eligible_unique_work_ids": len(eligible_work_ids),
"pre_threshold_unique_work_ids": len(pre_threshold_work_ids),
"missing_year_unique_work_ids": len(missing_year_work_ids),
"classified_by_target_id": len(classified_by_id),
"eligible_but_missing_in_target": len(unclassified_eligible),
"classified_target_documents_containing_author": classified_author_count,
"classified_by_id_but_author_missing_from_target_document": len(
classified_but_author_missing
),
},
"institution": {
"id": full_institution_id,
"pipeline_selected_source_works_matching_institution": (
len(institution_matching_work_ids) if full_institution_id else None
),
},
"important_differences": [
"The author card reads openalex-authors.works_count directly.",
"The publication list counts raw hits from openalex-works* and does not deduplicate by work ID.",
"The classification pipeline deduplicates by normalized OpenAlex work ID.",
f"The classification pipeline excludes works with publication_year below {args.work_year_gte} or missing.",
"A work can exist in the classification index but be absent from a per-author target-index count if the stored authors array does not contain that author.",
],
"examples": {
"eligible_but_missing_in_target": unclassified_examples[
: args.example_limit
],
"publication_year_before_threshold": pre_threshold_examples[
: args.example_limit
],
"publication_year_missing": missing_year_examples[: args.example_limit],
"multiple_source_documents_same_id": duplicate_examples[
: args.example_limit
],
"classified_but_author_missing": author_missing_examples[
: args.example_limit
],
},
}
json_path = output_dir / f"{short_author_id}_publication_count_comparison.json"
json_path.write_text(
json.dumps(summary, ensure_ascii=False, indent=2),
encoding="utf-8",
)
write_csv(
output_dir / f"{short_author_id}_eligible_but_unclassified.csv",
unclassified_examples,
)
write_csv(
output_dir / f"{short_author_id}_source_duplicates.csv",
duplicate_examples,
)
write_csv(
output_dir / f"{short_author_id}_excluded_by_year.csv",
pre_threshold_examples + missing_year_examples,
)
write_csv(
output_dir / f"{short_author_id}_classified_but_author_missing.csv",
author_missing_examples,
)
print()
print("Comparison")
print("----------")
print(f"Author card works_count: {author.get('works_count')}")
print(
f"Publication page raw total: {page_total_value} ({page_total_relation})"
)
print(f"Publication page unique OpenAlex IDs: {len(unique_work_ids)}")
print(f"Pipeline-eligible unique IDs: {len(eligible_work_ids)}")
print(f"Classified by target document ID: {len(classified_by_id)}")
print(f"Eligible but missing in target: {len(unclassified_eligible)}")
print(f"Target documents containing this author: {classified_author_count}")
print(
f"Raw duplicate documents: {len(raw_hits) - len(unique_work_ids)}"
)
print(
f"Works before {args.work_year_gte}: {len(pre_threshold_work_ids)}"
)
print(f"Works with missing publication year: {len(missing_year_work_ids)}")
print()
print(f"Report: {json_path.resolve()}")
print(f"CSV files: {output_dir.resolve()}")
return 0
if __name__ == "__main__":
try:
raise SystemExit(main())
except KeyboardInterrupt:
print("\nInterrupted.", file=sys.stderr)
raise SystemExit(130)
except Exception as exc:
print(f"Error: {exc}", file=sys.stderr)
raise SystemExit(1)
@@ -0,0 +1,181 @@
{
"summary": {
"created_at": "2026-07-19T23:22:32.712141Z",
"index": "work-classifications",
"read_only": true,
"expected_count": null,
"documents": 183661,
"initial_count": 183661,
"final_count": 183661,
"count_consistent": true,
"expected_count_matches": true,
"index_integrity_valid": true
},
"mapping": {
"valid": true,
"error_count": 0,
"errors": []
},
"documents": {
"schema_valid": 183661,
"schema_invalid": 0,
"field_order_valid": 183661,
"field_order_invalid": 0,
"unique_work_ids": 183661,
"duplicate_work_id_count": 0,
"duplicate_work_ids": {},
"schema_error_counts": {},
"field_order_error_counts": {}
},
"classification": {
"categories": {
"basic_research": {
"count": 83310,
"percentage": 45.36
},
"applied_research": {
"count": 73026,
"percentage": 39.76
},
"non_research": {
"count": 14584,
"percentage": 7.94
},
"experimental_development": {
"count": 12741,
"percentage": 6.94
}
},
"quadrants": {
"pure_applied": {
"count": 85767,
"percentage": 46.7
},
"use_inspired_basic": {
"count": 54366,
"percentage": 29.6
},
"pure_basic": {
"count": 28944,
"percentage": 15.76
},
"not_applicable": {
"count": 14584,
"percentage": 7.94
}
},
"confidence": {
"high": {
"count": 113822,
"percentage": 61.97
},
"medium": {
"count": 68830,
"percentage": 37.48
},
"low": {
"count": 1009,
"percentage": 0.55
}
},
"insufficient_context": {
"false": {
"count": 173892,
"percentage": 94.68
},
"true": {
"count": 9769,
"percentage": 5.32
}
},
"signals_used": {
"topics": 181324,
"title": 179981,
"work_type": 175947,
"venue": 141807,
"abstract": 110404,
"funders": 38567,
"language": 6695,
"year": 85
},
"applied_orientation_score": {
"overall": {
"count": 169077,
"min": 0.0,
"max": 92.0,
"mean": 47.18,
"median": 50.0
},
"by_category": {
"applied_research": {
"count": 73026,
"min": 31.0,
"max": 70.0,
"mean": 62.08,
"median": 60.0
},
"basic_research": {
"count": 83310,
"min": 0.0,
"max": 45.0,
"mean": 28.74,
"median": 35.0
},
"experimental_development": {
"count": 12741,
"min": 75.0,
"max": 92.0,
"mean": 82.34,
"median": 80.0
},
"non_research": {
"count": 0,
"min": null,
"max": null,
"mean": null,
"median": null
}
}
},
"current_rule_consistency": {
"consistent": 183661,
"inconsistent": 0,
"consistent_percentage": 100.0,
"error_counts": {}
},
"stored_validation": {
"states": {
"valid": 183661
},
"valid_state_consistent_with_error_list": 183661,
"valid_state_inconsistent_with_error_list": 0,
"error_occurrences": 0,
"error_counts": {}
}
},
"metadata": {
"missing_title": 120,
"missing_doi": 18865,
"missing_publication_year": 0,
"empty_authors": 0,
"empty_institutions": 47038,
"empty_topics": 2233,
"publication_year": {
"min": 1950,
"max": 2026
},
"classified_at": {
"min": "2026-07-10T18:42:03Z",
"max": "2026-07-19T06:14:05Z"
}
},
"provenance": {
"models": {
"gemma4-e4b": 183661
},
"prompt_versions": {
"frascati_hard_ranges_v2": 141643,
"frascati_v1": 42018
}
}
}
@@ -0,0 +1,44 @@
{
"run_id": "20260718_080350_493424",
"started_at": "2026-07-18T08:03:50Z",
"finished_at": "2026-07-18T11:25:02Z",
"duration_seconds": 12070.563,
"status": "completed",
"error": null,
"parameters": {
"limit": 15000,
"workers": 25,
"model": "gemma4-e4b",
"prompt_version": "frascati_hard_ranges_v2",
"target_index": "work-classifications",
"bulk_batch_size": 200,
"state_storage": "memory_only",
"preflight_only": false
},
"classification": {
"llm_completed": 15000,
"valid": 15000,
"invalid": 0,
"categories": {
"experimental_development": 1037,
"basic_research": 6608,
"applied_research": 6062,
"non_research": 1293
},
"validation_errors": {}
},
"indexing": {
"newly_indexed": 15000,
"bulk_requests": 82,
"bulk_documents_submitted": 15350,
"bulk_failures": 0
},
"token_usage": {
"prompt_tokens": 56119646,
"cached_prompt_tokens": 51428736,
"uncached_prompt_tokens": 4690910,
"completion_tokens": 13741519,
"real_total_usage": 18432429
},
"throughput_indexed_per_hour": 4473.69
}