Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into feature/keywords-analysis
This commit is contained in:
@@ -32,6 +32,10 @@ UDE_NAME = "University of Duisburg-Essen"
|
||||
AFFILIATION_YEAR_GTE = 2025
|
||||
WORK_YEAR_GTE = 1950
|
||||
|
||||
SELECTION_AUTHOR_COHORT = "author-cohort"
|
||||
SELECTION_INSTITUTION_WORKS = "institution-works"
|
||||
SELECTION_MODES = (SELECTION_AUTHOR_COHORT, SELECTION_INSTITUTION_WORKS)
|
||||
|
||||
AUTHOR_PAGE_SIZE = 1000
|
||||
AUTHOR_BATCH_SIZE = 1000
|
||||
WORK_PAGE_SIZE = 2000
|
||||
@@ -854,7 +858,26 @@ def validate(result: dict[str, Any]) -> list[str]:
|
||||
return errors
|
||||
|
||||
|
||||
def ude_affiliation_filter() -> dict[str, Any]:
|
||||
def institution_affiliation_filter(
|
||||
institution_id: str,
|
||||
institution_ror: str | None,
|
||||
institution_name: str,
|
||||
affiliation_year_gte: int,
|
||||
) -> dict[str, Any]:
|
||||
institution_matches: list[dict[str, Any]] = [
|
||||
{"term": {"affiliations.institution.id": institution_id}},
|
||||
{
|
||||
"match_phrase": {
|
||||
"affiliations.institution.display_name": institution_name
|
||||
}
|
||||
},
|
||||
]
|
||||
if institution_ror:
|
||||
institution_matches.insert(
|
||||
1,
|
||||
{"term": {"affiliations.institution.ror": institution_ror}},
|
||||
)
|
||||
|
||||
return {
|
||||
"nested": {
|
||||
"path": "affiliations",
|
||||
@@ -863,21 +886,13 @@ def ude_affiliation_filter() -> dict[str, Any]:
|
||||
"filter": [
|
||||
{
|
||||
"bool": {
|
||||
"should": [
|
||||
{"term": {"affiliations.institution.id": UDE_ID}},
|
||||
{"term": {"affiliations.institution.ror": UDE_ROR}},
|
||||
{
|
||||
"match_phrase": {
|
||||
"affiliations.institution.display_name": UDE_NAME
|
||||
}
|
||||
},
|
||||
],
|
||||
"should": institution_matches,
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
},
|
||||
{
|
||||
"range": {
|
||||
"affiliations.years": {"gte": AFFILIATION_YEAR_GTE}
|
||||
"affiliations.years": {"gte": affiliation_year_gte}
|
||||
}
|
||||
},
|
||||
]
|
||||
@@ -887,12 +902,21 @@ def ude_affiliation_filter() -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def author_query(group: str, after: list[Any] | None) -> dict[str, Any]:
|
||||
def author_query(
|
||||
group: str,
|
||||
after: list[Any] | None,
|
||||
institution_id: str = UDE_ID,
|
||||
institution_ror: str | None = UDE_ROR,
|
||||
institution_name: str = UDE_NAME,
|
||||
affiliation_year_gte: int = AFFILIATION_YEAR_GTE,
|
||||
) -> dict[str, Any]:
|
||||
last_known = {
|
||||
"nested": {
|
||||
"path": "last_known_institutions",
|
||||
"query": {
|
||||
"match_phrase": {"last_known_institutions.display_name": UDE_NAME}
|
||||
"match_phrase": {
|
||||
"last_known_institutions.display_name": institution_name
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -903,11 +927,30 @@ def author_query(group: str, after: list[Any] | None) -> dict[str, Any]:
|
||||
}
|
||||
}
|
||||
query = (
|
||||
{"bool": {"filter": [last_known, ude_affiliation_filter()]}}
|
||||
{
|
||||
"bool": {
|
||||
"filter": [
|
||||
last_known,
|
||||
institution_affiliation_filter(
|
||||
institution_id,
|
||||
institution_ror,
|
||||
institution_name,
|
||||
affiliation_year_gte,
|
||||
),
|
||||
]
|
||||
}
|
||||
}
|
||||
if group == "known"
|
||||
else {
|
||||
"bool": {
|
||||
"filter": [ude_affiliation_filter()],
|
||||
"filter": [
|
||||
institution_affiliation_filter(
|
||||
institution_id,
|
||||
institution_ror,
|
||||
institution_name,
|
||||
affiliation_year_gte,
|
||||
)
|
||||
],
|
||||
"must_not": [last_known_exists],
|
||||
}
|
||||
}
|
||||
@@ -924,7 +967,22 @@ def author_query(group: str, after: list[Any] | None) -> dict[str, Any]:
|
||||
return body
|
||||
|
||||
|
||||
def work_query(author_ids: list[str], after: list[Any] | None) -> dict[str, Any]:
|
||||
def work_query(
|
||||
author_ids: list[str],
|
||||
after: list[Any] | None,
|
||||
work_year_gte: int | None = WORK_YEAR_GTE,
|
||||
) -> dict[str, Any]:
|
||||
filters: list[dict[str, Any]] = [
|
||||
{
|
||||
"nested": {
|
||||
"path": "authorships",
|
||||
"query": {"terms": {"authorships.author.id": author_ids}},
|
||||
}
|
||||
}
|
||||
]
|
||||
if work_year_gte is not None:
|
||||
filters.insert(0, {"range": {"publication_year": {"gte": work_year_gte}}})
|
||||
|
||||
body: dict[str, Any] = {
|
||||
"size": WORK_PAGE_SIZE,
|
||||
"track_total_hits": False,
|
||||
@@ -964,15 +1022,7 @@ def work_query(author_ids: list[str], after: list[Any] | None) -> dict[str, Any]
|
||||
],
|
||||
"query": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{"range": {"publication_year": {"gte": WORK_YEAR_GTE}}},
|
||||
{
|
||||
"nested": {
|
||||
"path": "authorships",
|
||||
"query": {"terms": {"authorships.author.id": author_ids}},
|
||||
}
|
||||
},
|
||||
]
|
||||
"filter": filters
|
||||
}
|
||||
},
|
||||
"sort": [{"id": "asc"}],
|
||||
@@ -982,6 +1032,36 @@ def work_query(author_ids: list[str], after: list[Any] | None) -> dict[str, Any]
|
||||
return body
|
||||
|
||||
|
||||
def institution_work_query(
|
||||
institution_id: str,
|
||||
after: list[Any] | None,
|
||||
) -> dict[str, Any]:
|
||||
"""Select all works attributed to an institution, like Publikationsliste."""
|
||||
body = work_query([], after)
|
||||
body["query"] = {
|
||||
"bool": {
|
||||
"must": [
|
||||
{
|
||||
"nested": {
|
||||
"path": "authorships",
|
||||
"query": {
|
||||
"nested": {
|
||||
"path": "authorships.institutions",
|
||||
"query": {
|
||||
"terms": {
|
||||
"authorships.institutions.id": [institution_id]
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
return body
|
||||
|
||||
|
||||
def choose_work_hit(
|
||||
current: dict[str, Any] | None,
|
||||
candidate: dict[str, Any],
|
||||
@@ -1510,14 +1590,30 @@ def classify(
|
||||
raise StopPipeline(f"LLM unavailable for {work_id}: {error}")
|
||||
|
||||
|
||||
def collect_authors(es: ES) -> list[str]:
|
||||
def collect_authors(
|
||||
es: ES,
|
||||
institution_id: str = UDE_ID,
|
||||
institution_ror: str | None = UDE_ROR,
|
||||
institution_name: str = UDE_NAME,
|
||||
affiliation_year_gte: int = AFFILIATION_YEAR_GTE,
|
||||
) -> list[str]:
|
||||
ids: set[str] = set()
|
||||
for group in ("known", "empty"):
|
||||
after = None
|
||||
total = None
|
||||
read = 0
|
||||
while True:
|
||||
result = es.search(AUTHORS_INDEX, author_query(group, after))
|
||||
result = es.search(
|
||||
AUTHORS_INDEX,
|
||||
author_query(
|
||||
group,
|
||||
after,
|
||||
institution_id,
|
||||
institution_ror,
|
||||
institution_name,
|
||||
affiliation_year_gte,
|
||||
),
|
||||
)
|
||||
hits = result.get("hits", {}).get("hits", [])
|
||||
if total is None:
|
||||
value = result.get("hits", {}).get("total", 0)
|
||||
@@ -1535,7 +1631,7 @@ def collect_authors(es: ES) -> list[str]:
|
||||
raise StopPipeline("Missing author search_after")
|
||||
print(f"Authors {group}: {read}/{total}")
|
||||
result = sorted(ids)
|
||||
print(f"Final UDE author count: {len(result)}")
|
||||
print(f"Final institution author count: {len(result)}")
|
||||
return result
|
||||
|
||||
|
||||
@@ -1726,6 +1822,12 @@ def run(
|
||||
limit: int | None,
|
||||
workers: int,
|
||||
report: dict[str, Any],
|
||||
selection_mode: str = SELECTION_AUTHOR_COHORT,
|
||||
institution_id: str = UDE_ID,
|
||||
institution_ror: str | None = UDE_ROR,
|
||||
institution_name: str = UDE_NAME,
|
||||
affiliation_year_gte: int = AFFILIATION_YEAR_GTE,
|
||||
work_year_gte: int | None = WORK_YEAR_GTE,
|
||||
preflight_only: bool = False,
|
||||
) -> None:
|
||||
if not ES_API_KEY.strip():
|
||||
@@ -1749,17 +1851,34 @@ def run(
|
||||
api_key=LLM_API_KEY,
|
||||
timeout=REQUEST_TIMEOUT,
|
||||
)
|
||||
authors = collect_authors(es)
|
||||
|
||||
count = 0
|
||||
warm = False
|
||||
batches = (len(authors) + AUTHOR_BATCH_SIZE - 1) // AUTHOR_BATCH_SIZE
|
||||
|
||||
for start in range(0, len(authors), AUTHOR_BATCH_SIZE):
|
||||
if selection_mode == SELECTION_INSTITUTION_WORKS:
|
||||
work_batches: list[tuple[str, list[str] | None]] = [
|
||||
(f"Institution works: {institution_id}", None)
|
||||
]
|
||||
else:
|
||||
authors = collect_authors(
|
||||
es,
|
||||
institution_id,
|
||||
institution_ror,
|
||||
institution_name,
|
||||
affiliation_year_gte,
|
||||
)
|
||||
batch_count = (len(authors) + AUTHOR_BATCH_SIZE - 1) // AUTHOR_BATCH_SIZE
|
||||
work_batches = [
|
||||
(
|
||||
f"Author batch {start // AUTHOR_BATCH_SIZE + 1}/{batch_count}",
|
||||
authors[start : start + AUTHOR_BATCH_SIZE],
|
||||
)
|
||||
for start in range(0, len(authors), AUTHOR_BATCH_SIZE)
|
||||
]
|
||||
|
||||
for batch_label, author_ids in work_batches:
|
||||
if limit is not None and count >= limit:
|
||||
break
|
||||
batch = authors[start : start + AUTHOR_BATCH_SIZE]
|
||||
print(f"\nAuthor batch {start // AUTHOR_BATCH_SIZE + 1}/{batches}")
|
||||
print(f"\n{batch_label}")
|
||||
after = None
|
||||
page = 0
|
||||
|
||||
@@ -1767,7 +1886,12 @@ def run(
|
||||
if limit is not None and count >= limit:
|
||||
break
|
||||
|
||||
result = es.search(WORKS_INDEX, work_query(batch, after))
|
||||
query = (
|
||||
institution_work_query(institution_id, after)
|
||||
if author_ids is None
|
||||
else work_query(author_ids, after, work_year_gte)
|
||||
)
|
||||
result = es.search(WORKS_INDEX, query)
|
||||
hits = result.get("hits", {}).get("hits", [])
|
||||
if not hits:
|
||||
break
|
||||
@@ -1843,15 +1967,67 @@ def main() -> None:
|
||||
parser.add_argument("--limit", type=int)
|
||||
parser.add_argument("--workers", type=int, default=MAX_WORKERS)
|
||||
parser.add_argument("--preflight-only", action="store_true")
|
||||
parser.add_argument(
|
||||
"--selection-mode",
|
||||
choices=SELECTION_MODES,
|
||||
default=SELECTION_AUTHOR_COHORT,
|
||||
help=(
|
||||
"author-cohort selects works by current affiliated authors; "
|
||||
"institution-works selects every work attributed to --institution-id"
|
||||
),
|
||||
)
|
||||
parser.add_argument("--institution-id", default=UDE_ID)
|
||||
parser.add_argument("--institution-ror", default=UDE_ROR)
|
||||
parser.add_argument("--institution-name", default=UDE_NAME)
|
||||
parser.add_argument(
|
||||
"--affiliation-year-gte", type=int, default=AFFILIATION_YEAR_GTE
|
||||
)
|
||||
parser.add_argument("--work-year-gte", type=int, default=WORK_YEAR_GTE)
|
||||
parser.add_argument(
|
||||
"--all-work-years",
|
||||
action="store_true",
|
||||
help=(
|
||||
"disable the publication-year filter in author-cohort mode, "
|
||||
"including works without publication_year"
|
||||
),
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.limit is not None and args.limit < 1:
|
||||
raise SystemExit("--limit must be at least 1")
|
||||
if args.workers < 1:
|
||||
raise SystemExit("--workers must be at least 1")
|
||||
if args.affiliation_year_gte < 0:
|
||||
raise SystemExit("--affiliation-year-gte must not be negative")
|
||||
if args.work_year_gte < 0:
|
||||
raise SystemExit("--work-year-gte must not be negative")
|
||||
|
||||
work_year_gte = None if args.all_work_years else args.work_year_gte
|
||||
|
||||
institution_id = args.institution_id.strip()
|
||||
if not institution_id:
|
||||
raise SystemExit("--institution-id must not be empty")
|
||||
if not institution_id.startswith("https://openalex.org/"):
|
||||
institution_id = f"https://openalex.org/{bare_id(institution_id)}"
|
||||
|
||||
institution_ror = nullable_text(args.institution_ror)
|
||||
institution_name = args.institution_name.strip()
|
||||
if args.selection_mode == SELECTION_AUTHOR_COHORT and not institution_name:
|
||||
raise SystemExit("--institution-name is required for author-cohort")
|
||||
|
||||
report = new_run_report(args.limit, args.workers)
|
||||
report["parameters"]["preflight_only"] = args.preflight_only
|
||||
report["parameters"].update(
|
||||
{
|
||||
"selection_mode": args.selection_mode,
|
||||
"institution_id": institution_id,
|
||||
"institution_ror": institution_ror,
|
||||
"institution_name": institution_name,
|
||||
"affiliation_year_gte": args.affiliation_year_gte,
|
||||
"work_year_gte": work_year_gte,
|
||||
"all_work_years": args.all_work_years,
|
||||
}
|
||||
)
|
||||
exit_code = 0
|
||||
|
||||
try:
|
||||
@@ -1859,6 +2035,12 @@ def main() -> None:
|
||||
args.limit,
|
||||
args.workers,
|
||||
report,
|
||||
selection_mode=args.selection_mode,
|
||||
institution_id=institution_id,
|
||||
institution_ror=institution_ror,
|
||||
institution_name=institution_name,
|
||||
affiliation_year_gte=args.affiliation_year_gte,
|
||||
work_year_gte=work_year_gte,
|
||||
preflight_only=args.preflight_only,
|
||||
)
|
||||
report["status"] = "completed"
|
||||
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
{
|
||||
"run_id": "20260722_021910_049378",
|
||||
"started_at": "2026-07-22T02:19:10Z",
|
||||
"finished_at": "2026-07-22T09:26:37Z",
|
||||
"duration_seconds": 25645.781,
|
||||
"status": "completed",
|
||||
"error": null,
|
||||
"parameters": {
|
||||
"limit": null,
|
||||
"workers": 25,
|
||||
"model": "gemma4-e4b",
|
||||
"prompt_version": "frascati_hard_ranges_v2",
|
||||
"target_index": "work-classifications",
|
||||
"bulk_batch_size": 200,
|
||||
"state_storage": "memory_only",
|
||||
"preflight_only": false,
|
||||
"selection_mode": "institution-works",
|
||||
"institution_id": "https://openalex.org/I62318514",
|
||||
"institution_ror": "https://ror.org/04mz5ra38",
|
||||
"institution_name": "University of Duisburg-Essen",
|
||||
"affiliation_year_gte": 2025,
|
||||
"work_year_gte": 1950
|
||||
},
|
||||
"classification": {
|
||||
"llm_completed": 32189,
|
||||
"valid": 32189,
|
||||
"invalid": 0,
|
||||
"categories": {
|
||||
"applied_research": 10001,
|
||||
"basic_research": 17089,
|
||||
"experimental_development": 1813,
|
||||
"non_research": 3286
|
||||
},
|
||||
"validation_errors": {}
|
||||
},
|
||||
"indexing": {
|
||||
"newly_indexed": 32189,
|
||||
"bulk_requests": 183,
|
||||
"bulk_documents_submitted": 32589,
|
||||
"bulk_failures": 0
|
||||
},
|
||||
"token_usage": {
|
||||
"prompt_tokens": 119788565,
|
||||
"cached_prompt_tokens": 110500800,
|
||||
"uncached_prompt_tokens": 9287765,
|
||||
"completion_tokens": 29352270,
|
||||
"real_total_usage": 38640035
|
||||
},
|
||||
"throughput_indexed_per_hour": 4518.5
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
from openai import OpenAI, APIConnectionError
|
||||
from openai import APIConnectionError
|
||||
from openai import AsyncOpenAI
|
||||
from .. import config
|
||||
from typing import Optional, Dict, Any
|
||||
import asyncio
|
||||
def call(
|
||||
async def call(
|
||||
system_prompt: str,
|
||||
user_prompt: str,
|
||||
model: str = None,
|
||||
@@ -16,18 +16,18 @@ def call(
|
||||
|
||||
if model is None:
|
||||
model = config.settings.llm_model
|
||||
|
||||
|
||||
response_format = None
|
||||
if json_schema is not None:
|
||||
response_format = _get_response_format(schema = json_schema,schema_name=schema_name)
|
||||
|
||||
client = OpenAI(
|
||||
|
||||
client = AsyncOpenAI(
|
||||
base_url=config.settings.llm_api_url,
|
||||
api_key=config.settings.llm_api_key,
|
||||
timeout=timeout,
|
||||
)
|
||||
try:
|
||||
response = client.chat.completions.create(
|
||||
response = await client.chat.completions.create(
|
||||
model=model,
|
||||
messages=[
|
||||
{"role": "system", "content": system_prompt},
|
||||
|
||||
@@ -82,7 +82,7 @@ async def extract_keywords(query: str, mode: str, limit: int) -> ExtractedKeywor
|
||||
|
||||
user_prompt += f"""Input:{text}"""
|
||||
|
||||
keywords = llm.call(
|
||||
keywords = await llm.call(
|
||||
system_prompt=system_prompt,
|
||||
user_prompt=user_prompt,
|
||||
json_schema = ExtractedKeywordsLLM.model_json_schema(),
|
||||
|
||||
@@ -292,7 +292,7 @@ async def _get_article_keywords(
|
||||
if not text:
|
||||
return []
|
||||
|
||||
raw = llm.call(
|
||||
raw = await llm.call(
|
||||
system_prompt=KEYWORD_SYSTEM_PROMPT,
|
||||
user_prompt=f"Artikel:\n{text}",
|
||||
temperature=0.3,
|
||||
|
||||
@@ -444,7 +444,7 @@ async def generate_person_bio(
|
||||
|
||||
user_prompt = f"Daten zur Person:\n{person_json}"
|
||||
|
||||
bio = llm.call(
|
||||
bio = await llm.call(
|
||||
system_prompt=system_prompt,
|
||||
user_prompt=user_prompt,
|
||||
temperature=0.8,
|
||||
|
||||
+1
-1
@@ -41,7 +41,7 @@
|
||||
<app-topic-chip
|
||||
[label]="category | workPrimaryCategory"
|
||||
[color]="primaryCategoryChipColor()"
|
||||
[disabled]="true" />
|
||||
[disabled]="false" />
|
||||
}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
Reference in New Issue
Block a user