Compare commits
498
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
470b9095c4 | ||
|
|
a25d70466f | ||
|
|
4270dafd6a | ||
|
|
fc3baef406 | ||
|
|
be20407238 | ||
|
|
26c4dc8fe7 | ||
|
|
4dd124d003 | ||
|
|
ee40f1386a | ||
|
|
4f116d3ca2 | ||
|
|
9ef1ce7ce1 | ||
|
|
641f40ff45 | ||
|
|
6f0d17a991 | ||
|
|
2d1155d46b | ||
|
|
a1cf6e06af | ||
|
|
2e4a861e9c | ||
|
|
70e4ad71a6 | ||
|
|
dc27b49f63 | ||
|
|
b8707c7619 | ||
|
|
b251abb79f | ||
|
|
14be6c1a6c | ||
|
|
7addfe2a71 | ||
|
|
2474700473 | ||
|
|
0150f81a24 | ||
|
|
8a801d0bb5 | ||
|
|
496d2c88f0 | ||
|
|
9d8b287c13 | ||
|
|
94e0cad2d0 | ||
|
|
8be123bf3a | ||
|
|
570da1b47c | ||
|
|
02dd286d55 | ||
|
|
58199760de | ||
|
|
17b59213d3 | ||
|
|
06e2785914 | ||
|
|
0aea390e5e | ||
|
|
c33a900c66 | ||
|
|
f36e9a7d54 | ||
|
|
7259e3a0c0 | ||
|
|
b0581ad452 | ||
|
|
813953f1f5 | ||
|
|
288b21d407 | ||
|
|
01453f73dc | ||
|
|
410f1ade01 | ||
|
|
621a9dd2a1 | ||
|
|
18b9b8bf67 | ||
|
|
3f1ea0a418 | ||
|
|
211f7b82dc | ||
|
|
6675976feb | ||
|
|
034d3ee453 | ||
|
|
faa866f4e1 | ||
|
|
9c3e36930c | ||
|
|
d4daecd921 | ||
|
|
9f10e9e7af | ||
|
|
fa9def349c | ||
|
|
4073214131 | ||
|
|
03fac2a656 | ||
|
|
a204584ddd | ||
|
|
25de01c7be | ||
|
|
176235689f | ||
|
|
f27ee8b295 | ||
|
|
32616fe6aa | ||
|
|
9a5cb9e9b0 | ||
|
|
d11869c70b | ||
|
|
abb8c9dbb5 | ||
|
|
b8442213f8 | ||
|
|
0d19abb293 | ||
|
|
6ea3e79087 | ||
|
|
ba72b146a2 | ||
|
|
0f360c86b2 | ||
|
|
ecf7a6f905 | ||
|
|
345dffaa9b | ||
|
|
7b912196e9 | ||
|
|
6e4742206f | ||
|
|
a28ecc9d02 | ||
|
|
53397f844e | ||
|
|
818398ccda | ||
|
|
a6c7068ca6 | ||
|
|
4785bb4d40 | ||
|
|
1a9f9496fd | ||
|
|
78f35daa58 | ||
|
|
b2e70c2bb3 | ||
|
|
3d8ceeb5b6 | ||
|
|
0b8540d70b | ||
|
|
e9ccfe6796 | ||
|
|
e20f2732b3 | ||
|
|
4da4ea1bff | ||
|
|
93ba39f9b0 | ||
|
|
0642a3704d | ||
|
|
57e1bafa8b | ||
|
|
3d5eb524aa | ||
|
|
c15afed0aa | ||
|
|
b133ce80c9 | ||
|
|
ae8332dc3d | ||
|
|
026a35dd90 | ||
|
|
5fdc1cdce3 | ||
|
|
02bb8b8fb8 | ||
|
|
27f289f4a0 | ||
|
|
6af1747477 | ||
|
|
401b82c226 | ||
|
|
9d128e18b6 | ||
|
|
a6a78bb556 | ||
|
|
bc59c3f563 | ||
|
|
8b7ac08192 | ||
|
|
4fe78c2b88 | ||
|
|
2e8dd00aa6 | ||
|
|
127eed5c49 | ||
|
|
7a84fc2b12 | ||
|
|
96e0925054 | ||
|
|
730ee7f89a | ||
|
|
e62d1ca458 | ||
|
|
6bca5643ee | ||
|
|
db20b23ff3 | ||
|
|
66f34668a9 | ||
|
|
ceadc26741 | ||
|
|
3a74dc9b7b | ||
|
|
4a47d752cb | ||
|
|
1bca6648bd | ||
|
|
af00bc4635 | ||
|
|
def210b4b9 | ||
|
|
89bdab0a26 | ||
|
|
448922d907 | ||
|
|
3ef8c28191 | ||
|
|
46aee46ea3 | ||
|
|
e57875d2a5 | ||
|
|
28726cf4c7 | ||
|
|
b0e4ad639e | ||
|
|
1810918e43 | ||
|
|
a736539851 | ||
|
|
591233e255 | ||
|
|
c2a2a31fb9 | ||
|
|
d4a4bfa2c7 | ||
|
|
3a127450e3 | ||
|
|
c2f9a6381a | ||
|
|
7adf12912f | ||
|
|
0b2b05ae85 | ||
|
|
127c32dce7 | ||
|
|
652ff8db15 | ||
|
|
79c1076272 | ||
|
|
d29028a5bd | ||
|
|
8cba5387c7 | ||
|
|
bdb546db12 | ||
|
|
59ed0ad1a4 | ||
|
|
3d57dda846 | ||
|
|
6cdf5f4704 | ||
|
|
9f4bb77208 | ||
|
|
aa05beb594 | ||
|
|
6c2e3fab04 | ||
|
|
be556f09ad | ||
|
|
2fc9722914 | ||
|
|
9e39650899 | ||
|
|
1860e7c371 | ||
|
|
e5283543a1 | ||
|
|
bf5d626209 | ||
|
|
424649ecdc | ||
|
|
11ac6525c1 | ||
|
|
8a684c8b57 | ||
|
|
4805fe9c3c | ||
|
|
d9e91eebe3 | ||
|
|
537ab7adb5 | ||
|
|
90ec5c2c8d | ||
|
|
cbbcaa2325 | ||
|
|
e6eabf08c9 | ||
|
|
82800c95c2 | ||
|
|
ae8d01b5ce | ||
|
|
b616d061bb | ||
|
|
3a78519655 | ||
|
|
c6de85d4a0 | ||
|
|
71fe4a54e7 | ||
|
|
02b498f829 | ||
|
|
18f661e3b4 | ||
|
|
8a61382cdd | ||
|
|
22bfb2feba | ||
|
|
358a47bbf5 | ||
|
|
ceed96102f | ||
|
|
467f40a625 | ||
|
|
bdf16de838 | ||
|
|
e8b5dcfd5b | ||
|
|
f0caacd696 | ||
|
|
579f9f1baf | ||
|
|
4faed7aaf0 | ||
|
|
a686e6c1c3 | ||
|
|
2a2521b75f | ||
|
|
e7afd7e68a | ||
|
|
59cba664e1 | ||
|
|
9d24c0a9bb | ||
|
|
fd40ccc654 | ||
|
|
7d695f8439 | ||
|
|
f25c5cd222 | ||
|
|
0b5c6bed37 | ||
|
|
2d485263d1 | ||
|
|
a1670f9170 | ||
|
|
4b57dea33a | ||
|
|
0aadbdbe7a | ||
|
|
03fcd7879a | ||
|
|
d5cfb784c8 | ||
|
|
10ceb60dce | ||
|
|
1a0d45f118 | ||
|
|
f7bbf58135 | ||
|
|
cf1a55cd6b | ||
|
|
3a342961e2 | ||
|
|
82d2c508b8 | ||
|
|
e62226a0ff | ||
|
|
9533db313e | ||
|
|
f5f4fb7799 | ||
|
|
db2fb18e89 | ||
|
|
5c4dbe602f | ||
|
|
d3686f9de9 | ||
|
|
399ed285e2 | ||
|
|
4d1f2e64d1 | ||
|
|
00e5597b08 | ||
|
|
8cec89ced4 | ||
|
|
d4557c6d7b | ||
|
|
daf71a6dae | ||
|
|
ddbf000213 | ||
|
|
08e164211c | ||
|
|
9dfba9f8c6 | ||
|
|
68956dc52c | ||
|
|
293a62d91c | ||
|
|
ee98b589c9 | ||
|
|
4e0afc12ed | ||
|
|
fa68c338c2 | ||
|
|
0712d3f3fa | ||
|
|
3d78ec900e | ||
|
|
b6095188ac | ||
|
|
14e25a522c | ||
|
|
2f5ed6ad15 | ||
|
|
a344c3f055 | ||
|
|
fc134dad8e | ||
|
|
2ada70dc9a | ||
|
|
a103609485 | ||
|
|
387a7d8da0 | ||
|
|
2962b784ad | ||
|
|
2ca6f2ae39 | ||
|
|
b2c6534c60 | ||
|
|
b28271edf6 | ||
|
|
c3ec095ed1 | ||
|
|
f119de52d3 | ||
|
|
8d0a4f2e5a | ||
|
|
720e6f9612 | ||
|
|
59a1f765d0 | ||
|
|
924405fc08 | ||
|
|
c02d2e4744 | ||
|
|
1b327ed4e1 | ||
|
|
0d63b6a196 | ||
|
|
44dd9524d9 | ||
|
|
389523bb44 | ||
|
|
908e28c731 | ||
|
|
6cccd6d19f | ||
|
|
16f7e665fe | ||
|
|
e78b406d6d | ||
|
|
292c02cac8 | ||
|
|
ff322fc29b | ||
|
|
1a01ff5198 | ||
|
|
c47d5ee170 | ||
|
|
afaa840d48 | ||
|
|
fb44e9db3c | ||
|
|
762e3f9a15 | ||
|
|
697dacea81 | ||
|
|
3b926837d8 | ||
|
|
ad83def6ab | ||
|
|
81b768b244 | ||
|
|
7e8b7eb2c0 | ||
|
|
0dd2023224 | ||
|
|
d4880b417b | ||
|
|
a7ced052dd | ||
|
|
e751e58fa7 | ||
|
|
0b3be35885 | ||
|
|
5323797c71 | ||
|
|
19bc80134b | ||
|
|
82fe042b2b | ||
|
|
c368ea8f59 | ||
|
|
9ac618ebec | ||
|
|
de6339586f | ||
|
|
97c9e2eec3 | ||
|
|
167913aa85 | ||
|
|
20f1de61b8 | ||
|
|
85e79aeb3e | ||
|
|
83ed0bcaee | ||
|
|
5095f58c9a | ||
|
|
807adbd6e4 | ||
|
|
75ae1acaf3 | ||
|
|
b9d0d4cbf3 | ||
|
|
18c9785325 | ||
|
|
2067d9ab03 | ||
|
|
84c94d135d | ||
|
|
8db323d605 | ||
|
|
99944653a7 | ||
|
|
213079e30d | ||
|
|
98f04245f0 | ||
|
|
8680b9e60e | ||
|
|
fbe2f787a7 | ||
|
|
5b3176dc6e | ||
|
|
2cbff8ea0e | ||
|
|
ee85c99c2f | ||
|
|
b834c1e1d4 | ||
|
|
f342406402 | ||
|
|
f4e0888ce2 | ||
|
|
712fcbb749 | ||
|
|
cb5a887d12 | ||
|
|
755f83f65a | ||
|
|
4bd4a015f1 | ||
|
|
a5664e01fe | ||
|
|
d3266ee50e | ||
|
|
6fdf007401 | ||
|
|
7b838bae80 | ||
|
|
db3d984125 | ||
|
|
2e0883edae | ||
|
|
9da17840ad | ||
|
|
2bc29747b5 | ||
|
|
8becf406d6 | ||
|
|
0ff0298b99 | ||
|
|
a224977a0d | ||
|
|
83ffe6e3f7 | ||
|
|
5aedb9d94f | ||
|
|
8a51484352 | ||
|
|
577cc8fe7a | ||
|
|
373d0850a3 | ||
|
|
086915254c | ||
|
|
83f3dc593d | ||
|
|
05929cf76a | ||
|
|
a948182da5 | ||
|
|
339523c268 | ||
|
|
b7c8df4e89 | ||
|
|
2aea08ab31 | ||
|
|
571ecd5204 | ||
|
|
03a5f188b2 | ||
|
|
80ac59b496 | ||
|
|
90d07b5ea1 | ||
|
|
c1c27f5a95 | ||
|
|
616b83e546 | ||
|
|
b9891ea709 | ||
|
|
ebb986b225 | ||
|
|
7f71c976bb | ||
|
|
8e352dfbb2 | ||
|
|
225c0b9209 | ||
|
|
b7884f26bb | ||
|
|
499564148e | ||
|
|
ea131c9780 | ||
|
|
8d4fb333a2 | ||
|
|
504809e473 | ||
|
|
aead21ceb2 | ||
|
|
129142dfba | ||
|
|
d762b6c707 | ||
|
|
f9b63977ff | ||
|
|
0a97b3797e | ||
|
|
b5d4e5a3c7 | ||
|
|
cfc2c29994 | ||
|
|
d1490dceb0 | ||
|
|
5a47d9bb52 | ||
|
|
716b5b11d6 | ||
|
|
abb792e3cd | ||
|
|
c8b7a8f173 | ||
|
|
1f95e5dae1 | ||
|
|
9e48cc1641 | ||
|
|
b1aa10109c | ||
|
|
f58b26600d | ||
|
|
c4d828ce6d | ||
|
|
2834cbd4de | ||
|
|
c377c8cacd | ||
|
|
05f5bf1ce2 | ||
|
|
ad16c95466 | ||
|
|
9987266860 | ||
|
|
925a01e6a4 | ||
|
|
c203a31842 | ||
|
|
4ac8118e92 | ||
|
|
c4f6759790 | ||
|
|
efa43910c1 | ||
|
|
ccf230756e | ||
|
|
ff370d49c8 | ||
|
|
246e523234 | ||
|
|
0ca9e034b4 | ||
|
|
c58ae13484 | ||
|
|
5c0f6929bf | ||
|
|
9a919a8a75 | ||
|
|
a4f0a711a8 | ||
|
|
281c389872 | ||
|
|
8a469a73bf | ||
|
|
970486d860 | ||
|
|
df9c102e54 | ||
|
|
b636c0323c | ||
|
|
55d0b7918f | ||
|
|
0cc22dc109 | ||
|
|
67dbc2a833 | ||
|
|
025a61dc13 | ||
|
|
e702ada559 | ||
|
|
715f775071 | ||
|
|
272979cd58 | ||
|
|
7bf2b57b95 | ||
|
|
a0628121a3 | ||
|
|
b22f16809d | ||
|
|
b9c4067250 | ||
|
|
377e75f89d | ||
|
|
90860230f4 | ||
|
|
d005162a80 | ||
|
|
c242dafd92 | ||
|
|
67eee2913e | ||
|
|
0f65a0f589 | ||
|
|
410bcdec4b | ||
|
|
a3646beb1b | ||
|
|
afeff33ea7 | ||
|
|
28c00b42e4 | ||
|
|
1748e0a51a | ||
|
|
51a8d3db71 | ||
|
|
06f61c18dd | ||
|
|
a25b2ce248 | ||
|
|
f5ad24f83a | ||
|
|
b39daba561 | ||
|
|
53155d4e53 | ||
|
|
8589bc6084 | ||
|
|
807a32eb5a | ||
|
|
8583f6622e | ||
|
|
af5dd299e0 | ||
|
|
b0eab84000 | ||
|
|
e6493b9f22 | ||
|
|
ae52ad2a0f | ||
|
|
45aad0c49e | ||
|
|
6a94153b22 | ||
|
|
f813314d83 | ||
|
|
93481bf9c5 | ||
|
|
a76789f34b | ||
|
|
e09a55fb52 | ||
|
|
ede9290643 | ||
|
|
53d19e5b72 | ||
|
|
3609376c78 | ||
|
|
afd45a98bd | ||
|
|
032e0a1a06 | ||
|
|
2566fa9208 | ||
|
|
a47f50bd06 | ||
|
|
5fa728b3a1 | ||
|
|
0566ebbd93 | ||
|
|
81527a9d8d | ||
|
|
c7413c7088 | ||
|
|
a6dc55a44d | ||
|
|
ab14d3e9ae | ||
|
|
7829d9cf79 | ||
|
|
7efec21435 | ||
|
|
03627bdb00 | ||
|
|
db89618d4d | ||
|
|
538d73c1b1 | ||
|
|
4e9d0eace8 | ||
|
|
f4d43db325 | ||
|
|
22b10c7cee | ||
|
|
e92b450e5b | ||
|
|
5d72140758 | ||
|
|
63865efe84 | ||
|
|
3d0377adff | ||
|
|
bee19dfa39 | ||
|
|
4e8e744fc5 | ||
|
|
75c0638df5 | ||
|
|
9254dcf115 | ||
|
|
86d65b2d5a | ||
|
|
162aa1301d | ||
|
|
e1e9ffa8ec | ||
|
|
c5523bf63f | ||
|
|
8c981be503 | ||
|
|
a20759903e | ||
|
|
912023aa8c | ||
|
|
3b4d0b3339 | ||
|
|
e5f28f2143 | ||
|
|
069566d71d | ||
|
|
07278b3f65 | ||
|
|
3684a5acf5 | ||
|
|
5ce97e6854 | ||
|
|
8bb0cf18ad | ||
|
|
19933d69b6 | ||
|
|
9aeb8171a7 | ||
|
|
f4542d21b8 | ||
|
|
532c94b00b | ||
|
|
5d1d62acb8 | ||
|
|
efca552861 | ||
|
|
7c136074b2 | ||
|
|
ec78bdb1f3 | ||
|
|
8f1462cecc | ||
|
|
b19928c7a1 | ||
|
|
dfdc35ad81 | ||
|
|
e1d0fe9229 | ||
|
|
1a2b1a1970 | ||
|
|
9b046325c0 | ||
|
|
8f65cd78ba | ||
|
|
7775400a3f | ||
|
|
64ccedf44d | ||
|
|
21ea772656 | ||
|
|
d16b1544b9 | ||
|
|
afe3038dce | ||
|
|
13c6e76e59 | ||
|
|
b2faa2bc98 | ||
|
|
e5f48457d2 | ||
|
|
baf71577fe | ||
|
|
34b6979666 | ||
|
|
ecd21ce0a9 | ||
|
|
3b9436474e | ||
|
|
31b285518d | ||
|
|
16e582e942 | ||
|
|
62d3adb745 | ||
|
|
ccade53358 | ||
|
|
164e79978f | ||
|
|
d39d222ea8 | ||
|
|
275a6e1948 | ||
|
|
d32f3f7c7b |
@@ -0,0 +1,15 @@
|
||||
*
|
||||
!background-jobs
|
||||
!service
|
||||
service/*
|
||||
!service/scripts
|
||||
|
||||
# Data-only folders that do not belong in the job image.
|
||||
service/scripts/multipliers
|
||||
|
||||
**/__pycache__
|
||||
**/*.pyc
|
||||
**/.venv
|
||||
**/.env
|
||||
**/.env.*
|
||||
**/out
|
||||
@@ -5,7 +5,6 @@ from typing import Any
|
||||
|
||||
from openalex_client import get_all_author_works
|
||||
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent
|
||||
INPUT_FILE = BASE_DIR / "career_stage_sample.csv"
|
||||
OUTPUT_FILE = BASE_DIR / "career_stage_results.csv"
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
from typing import Callable, Literal
|
||||
from typing import Literal
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
import pandas as pd
|
||||
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent
|
||||
INPUT_FILE = BASE_DIR / "career_stage_results.csv"
|
||||
PLOTS_DIR = BASE_DIR / "plots"
|
||||
|
||||
@@ -4,7 +4,6 @@ from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import urlencode
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
|
||||
OPENALEX_WORKS_URL = "https://api.openalex.org/works"
|
||||
REQUEST_TIMEOUT_SECONDS = 30
|
||||
PER_PAGE = 200
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
.env
|
||||
.env.*
|
||||
__pycache__/
|
||||
*.pyc
|
||||
.venv/
|
||||
@@ -0,0 +1,7 @@
|
||||
# Copy this file to `.env` and fill in the real values.
|
||||
# `.env` is gitignored and is NOT baked into the image.
|
||||
INSE_ELASTIC_URL=https://inse.nes.uni-due.de/elastic
|
||||
INSE_ELASTIC_API_KEY=your-elastic-api-key-here
|
||||
INSE_LLM_BASE_URL=https://project.nes.uni-due.de/llm2/v1/
|
||||
INSE_LLM_API_KEY=your-llm-api-key-here
|
||||
INSE_LLM_MODEL=gemma4-e4b
|
||||
@@ -0,0 +1,5 @@
|
||||
# Local secrets – never commit
|
||||
.env
|
||||
|
||||
__pycache__/
|
||||
*.pyc
|
||||
@@ -0,0 +1,95 @@
|
||||
# Background Jobs
|
||||
|
||||
Background Jobs sind Docker-Container, die regelmäßig oder manuell Elasticsearch-Daten verarbeiten. Sie werden vom Backend über den Docker-Socket gestartet.
|
||||
|
||||
**Wichtig:** Jobs sind in der **Datenbank**, nicht im Image. Das Image enthält nur die ausführbaren Skripte.
|
||||
|
||||
## Jobs anlegen
|
||||
|
||||
**Frontend** (`/jobs`):
|
||||
|
||||
- "Neuer Job" → Name + Command + optionales Image + Zeitplan
|
||||
|
||||
**API**:
|
||||
|
||||
```bash
|
||||
curl -X POST -H "Authorization: Bearer $TOKEN" \
|
||||
-d '{"name": "Sync", "command": "python sync.py --sync-delta", "schedule": "0 3 * * *"}' \
|
||||
http://localhost:8000/api/background-jobs/tasks
|
||||
```
|
||||
|
||||
Command-Beispiele:
|
||||
|
||||
```
|
||||
python service/scripts/demo/demo.py 20
|
||||
python sync.py --sync-delta
|
||||
python service/scripts/news/ude/run_pipeline.py --skip-upload --max-items 5
|
||||
python -m service.scripts.news.topic_mapper.map_news_topics --output-index docker-job_test --max-docs 50
|
||||
python -m service.scripts.projects.topic_mapper.map_project_topics --dry-run
|
||||
sh -c "cd service/scripts/projects/bund && python gpc.data.py --skip-upload"
|
||||
```
|
||||
|
||||
**Neue Jobs = kein Image-Rebuild.** Die Skripte sind bereits im Image; der Command wird direkt an Docker übergeben.
|
||||
|
||||
## Image & Dockerfile
|
||||
|
||||
Das [Dockerfile](../service/scripts/jobs-image/Dockerfile) kopiert den kompletten `service/scripts/`-Baum (Pfade im Container = Pfade im Repo) plus `background-jobs/app/` (sync.py) und hat keinen ENTRYPOINT. Neue Skripte unter `service/scripts` landen automatisch im nächsten Build — ohne Dockerfile-Änderung. Der Backend startet Container direkt:
|
||||
|
||||
```python
|
||||
docker.run(image="...", command="python sync.py --sync-delta")
|
||||
```
|
||||
|
||||
**Skripte hinzugefügt oder geändert?** → Image neu bauen + pushen:
|
||||
|
||||
```bash
|
||||
docker build -f service/scripts/jobs-image/Dockerfile -t docker.nes.uni-due.de/inse/background-jobs:latest .
|
||||
docker push docker.nes.uni-due.de/inse/background-jobs:latest
|
||||
```
|
||||
|
||||
Lokal testen ohne Pull:
|
||||
|
||||
```bash
|
||||
export BACKGROUND_JOBS_PULL_BEFORE_RUN=false
|
||||
```
|
||||
|
||||
## Scheduling
|
||||
|
||||
Job mit `schedule: "0 3 * * *"` und `enabled: true` läuft automatisch täglich um 3:00 UTC. Manuell starten: "Jetzt ausführen" Button oder API.
|
||||
|
||||
## Logs
|
||||
|
||||
Während Laufzeit: Live vom Container. Nach Beendigung: Letzte 200 Zeilen in der DB. Frontend: "Logs anzeigen" Button.
|
||||
|
||||
## Docker-Socket (Deployment)
|
||||
|
||||
```yaml
|
||||
# docker-compose
|
||||
backend:
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
```
|
||||
|
||||
Ohne Socket-Mount funktioniert nichts.
|
||||
|
||||
## Env-Variablen
|
||||
|
||||
Standard-Image erhält automatisch:
|
||||
|
||||
- `INSE_ELASTIC_URL`, `INSE_ELASTIC_API_KEY`
|
||||
- `INSE_LLM_*`, `ELASTICSEARCH_INSE_*`, `SENTENCE_TRANSFORMERS_MODEL_NAME`
|
||||
|
||||
Plus `env` aus der Job-Definition.
|
||||
|
||||
**Eigene Images** bekommen nur die `env`-Variablen (Sicherheit).
|
||||
|
||||
## API
|
||||
|
||||
- `GET /api/background-jobs/tasks` — Jobs auflisten
|
||||
- `POST /api/background-jobs/tasks` — Job anlegen
|
||||
- `DELETE /api/background-jobs/tasks/{id}` — Job löschen
|
||||
- `POST /api/background-jobs/tasks/{id}/run` — Run starten
|
||||
- `PATCH /api/background-jobs/tasks/{id}` — Schedule ändern
|
||||
- `GET /api/background-jobs/runs/{id}/logs` — Logs abrufen
|
||||
- `POST /api/background-jobs/runs/{id}/stop` — Run stoppen
|
||||
|
||||
Alle Endpoints erfordern Superadmin-Auth.
|
||||
@@ -0,0 +1,152 @@
|
||||
import os
|
||||
from urllib.parse import quote
|
||||
|
||||
import requests
|
||||
from dotenv import load_dotenv
|
||||
from requests.adapters import HTTPAdapter
|
||||
|
||||
load_dotenv()
|
||||
|
||||
INSE_URL = os.getenv("INSE_ELASTIC_URL", "https://inse.nes.uni-due.de/elastic")
|
||||
INSE_API_KEY = os.getenv("INSE_ELASTIC_API_KEY")
|
||||
if not INSE_API_KEY:
|
||||
raise RuntimeError(
|
||||
"INSE_ELASTIC_API_KEY is not set. Copy .env.example to .env and fill it in, "
|
||||
"or pass it as an environment variable."
|
||||
)
|
||||
|
||||
ES_HEADERS = {
|
||||
"Authorization": f"ApiKey {INSE_API_KEY}",
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
_session = requests.Session()
|
||||
_session.headers.update(ES_HEADERS)
|
||||
_adapter = HTTPAdapter(pool_connections=32, pool_maxsize=32)
|
||||
_session.mount("https://", _adapter)
|
||||
_session.mount("http://", _adapter)
|
||||
|
||||
def _send_es_request(method: str, url: str, payload: dict = None) -> dict:
|
||||
|
||||
try:
|
||||
response = _session.request(
|
||||
method=method,
|
||||
url=url,
|
||||
json=payload,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
except requests.RequestException as error:
|
||||
print(f"Send Request failed: ({method} {url}): {error}")
|
||||
raise
|
||||
|
||||
def add_entry(index: str, entry: dict):
|
||||
|
||||
endpoint = f"{INSE_URL}/{index}/_doc"
|
||||
|
||||
document_body = {
|
||||
"news_id": entry["news_id"],
|
||||
"relevant": int(entry["relevant"]),
|
||||
"authors": entry["authors"],
|
||||
"keywords": entry.get("keywords", []),
|
||||
}
|
||||
|
||||
response_data = _send_es_request("POST", endpoint, payload=document_body)
|
||||
|
||||
created_id = response_data["_id"]
|
||||
entry["_id"] = created_id
|
||||
|
||||
return created_id
|
||||
|
||||
def index_entry(index: str, document_id: str, entry: dict):
|
||||
|
||||
encoded_document_id = quote(document_id, safe="")
|
||||
endpoint = f"{INSE_URL}/{index}/_doc/{encoded_document_id}"
|
||||
|
||||
document_body = {
|
||||
"news_id": entry["news_id"],
|
||||
"relevant": int(entry["relevant"]),
|
||||
"authors": entry["authors"],
|
||||
"keywords": entry.get("keywords", []),
|
||||
}
|
||||
|
||||
return _send_es_request("PUT", endpoint, payload=document_body)
|
||||
|
||||
def update_entry(index: str, document_id: str, partial_doc: dict):
|
||||
|
||||
encoded_document_id = quote(document_id, safe="")
|
||||
endpoint = f"{INSE_URL}/{index}/_update/{encoded_document_id}"
|
||||
|
||||
return _send_es_request("POST", endpoint, payload={"doc": partial_doc})
|
||||
|
||||
def get_entry(index: str, document_id: str) -> dict:
|
||||
|
||||
encoded_document_id = quote(document_id, safe="")
|
||||
endpoint = f"{INSE_URL}/{index}/_doc/{encoded_document_id}"
|
||||
|
||||
return _send_es_request("GET", endpoint)
|
||||
|
||||
def delete_entry(index: str, document_id: str):
|
||||
|
||||
encoded_document_id = quote(document_id, safe="")
|
||||
endpoint = f"{INSE_URL}/{index}/_doc/{encoded_document_id}"
|
||||
|
||||
return _send_es_request("DELETE", endpoint)
|
||||
|
||||
def get_all_entries(index: str, fields: list = None) -> list:
|
||||
|
||||
if not fields:
|
||||
source_fields = True
|
||||
else:
|
||||
source_fields = fields
|
||||
|
||||
endpoint = f"{INSE_URL}/{index}/_search"
|
||||
|
||||
page_size = 1000
|
||||
results = []
|
||||
last_sort_value = None
|
||||
|
||||
while True:
|
||||
payload = {
|
||||
"query": {"match_all": {}},
|
||||
"size": page_size,
|
||||
"sort": [{"_doc": "asc"}],
|
||||
"_source": source_fields,
|
||||
}
|
||||
if last_sort_value is not None:
|
||||
payload["search_after"] = last_sort_value
|
||||
|
||||
response_data = _send_es_request("POST", endpoint, payload=payload)
|
||||
results_list = response_data["hits"]["hits"]
|
||||
|
||||
if not results_list:
|
||||
break
|
||||
|
||||
results.extend(results_list)
|
||||
last_sort_value = results_list[-1]["sort"]
|
||||
|
||||
return results
|
||||
|
||||
def delete_all_entries(index: str):
|
||||
|
||||
endpoint = f"{INSE_URL}/{index}/_delete_by_query"
|
||||
|
||||
payload = {
|
||||
"query": {"match_all": {}}
|
||||
}
|
||||
|
||||
return _send_es_request("POST", endpoint, payload=payload)
|
||||
|
||||
def remove_field_all(index: str, field: str):
|
||||
|
||||
endpoint = f"{INSE_URL}/{index}/_update_by_query"
|
||||
|
||||
payload = {
|
||||
"query": {"exists": {"field": field}},
|
||||
"script": {
|
||||
"source": f"ctx._source.remove('{field}')",
|
||||
"lang": "painless",
|
||||
},
|
||||
}
|
||||
|
||||
return _send_es_request("POST", endpoint, payload=payload)
|
||||
@@ -0,0 +1,95 @@
|
||||
import os
|
||||
|
||||
from dotenv import load_dotenv
|
||||
from openai import APIConnectionError, OpenAI
|
||||
|
||||
load_dotenv()
|
||||
|
||||
LLM_BASE_URL = os.getenv("INSE_LLM_BASE_URL", "https://project.nes.uni-due.de/llm2/v1/")
|
||||
LLM_API_KEY = os.getenv("INSE_LLM_API_KEY")
|
||||
if not LLM_API_KEY:
|
||||
raise RuntimeError(
|
||||
"INSE_LLM_API_KEY is not set. Copy .env.example to .env and fill it in, "
|
||||
"or pass it as an environment variable."
|
||||
)
|
||||
LLM_MODEL = os.getenv("INSE_LLM_MODEL", "gemma4-e4b")
|
||||
|
||||
SYSTEM_PROMPT_RELEVANT = ("""
|
||||
Du bewertest Nachrichtenartikel aus dem Campus-Aktuell-Bereich der Universität Duisburg-Essen.
|
||||
Entscheide, ob der Artikel inhaltlich über eine konkrete Person berichtet, also über deren Werdegang, Forschung, Leistung, Auszeichnung oder Tätigkeit.
|
||||
Falls du dir unsicher bist, ob eine Person im Mittelpunkt steht, dann entscheide dich bitte für die positivere Option (also 1), damit die Namensextraktion auf keinen Fall bei Artikeln mit Personenbezug versäumt wird.
|
||||
Antworte mit 1, wenn eine konkrete Person im Mittelpunkt steht.
|
||||
Antworte mit 0, wenn es sich um allgemeine Mitteilungen handelt, die keine einzelne Person in den Mittelpunkt stellen, zum Beispiel Veranstaltungs- und Terminhinweise, Spendenaufrufe, organisatorische Ankündigungen, allgemeine Universitätsinformationen oder Pressemitteilungen ohne Personenbezug.
|
||||
Die bloße Nennung von Namen (etwa als Autor oder Ansprechpartner) reicht für eine 1 nicht aus; die Person muss inhaltlich Thema des Artikels sein.
|
||||
Antworte ausschließlich mit einer einzigen Ziffer: 0 oder 1.
|
||||
""")
|
||||
|
||||
SYSTEM_PROMPT_NAMES = ("""
|
||||
Aus dem nachfolgenden Campus-Aktuell-Artikel der Universität Duisburg-Essen: Nenne die Namen aller konkreten Personen, um die es im Artikel inhaltlich geht.
|
||||
Es können mehrere Personen sein. Bitte achte darauf dass du nur die Namen der Personen nennst, die tatsächlich im Mittelpunkt des Artikels stehen.
|
||||
Insbesondere am Ende von Artikeln werden oft Personen genannt, die nur als Ansprechpartner oder Organisator und sollen deshalb nicht genannt werden.
|
||||
Antworte ausschließlich mit gültigem JSON in exakt diesem Format: {\"person\": [\"Vorname Nachname\", \"Vorname Nachname\"]}
|
||||
Gib keine Erklärungen und kein Markdown aus, nur das JSON.
|
||||
""")
|
||||
|
||||
SYSTEM_PROMPT_KEYWORDS = ("""
|
||||
Extrahiere aus dem nachfolgenden Campus-Aktuell-Artikel der Universität Duisburg-Essen die wichtigsten Schlagwörter (Keywords).
|
||||
Wähle ausschließlich Begriffe oder Phrasen, die tatsächlich im Text vorkommen. Erfinde keine Begriffe, verallgemeinere nicht und nenne keine Oberbegriffe, die nicht im Text stehen.
|
||||
Übersetze keine Begriffe – verwende ausschließlich Wörter und Phrasen in der Sprache des Artikels.
|
||||
Gib jedes Schlagwort in seiner Grundform an: Bei deutschen Begriffen Substantive im Nominativ Singular; bei englischen Begriffen Substantive im Singular. Verwende den Plural nur, wenn der Begriff üblicherweise im Plural gebraucht wird.
|
||||
Vermeide Redundanz: Wenn zwei mögliche Schlagwörter dieselbe Wortbasis teilen (z.B. „Forschung" und „Forschungsprojekt"), nenne nur den spezifischeren Begriff.
|
||||
Nenne maximal sechs prägnante Begriffe oder kurze Phrasen. Konzentriere dich auf inhaltlich zentrale Begriffe, nicht auf Personennamen oder Datumsangaben.
|
||||
Antworte ausschließlich mit gültigem JSON in exakt diesem Format: {\"keywords\": [\"Schlagwort\", \"Schlagwort\"]}
|
||||
Gib keine Erklärungen und kein Markdown aus, nur das JSON.
|
||||
""")
|
||||
|
||||
_client = OpenAI(
|
||||
base_url=LLM_BASE_URL,
|
||||
api_key=LLM_API_KEY,
|
||||
timeout=30,
|
||||
)
|
||||
|
||||
def call(system_prompt, user_prompt, model=LLM_MODEL, temperature=1.0, top_p=0.95):
|
||||
try:
|
||||
response = _client.chat.completions.create(
|
||||
model=model,
|
||||
messages=[
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": user_prompt},
|
||||
],
|
||||
temperature=temperature,
|
||||
top_p=top_p,
|
||||
extra_body={"top_k": 64},
|
||||
)
|
||||
except APIConnectionError:
|
||||
return None
|
||||
|
||||
return response.choices[0].message.content or None
|
||||
|
||||
def is_news_relevant(text: str) -> bool:
|
||||
result = call(SYSTEM_PROMPT_RELEVANT, text)
|
||||
if result is None:
|
||||
return False
|
||||
return result.strip() == "1"
|
||||
|
||||
def extract_names(text: str) -> list[str]:
|
||||
result = call(SYSTEM_PROMPT_NAMES, text)
|
||||
if result is None:
|
||||
return []
|
||||
try:
|
||||
import json
|
||||
data = json.loads(result)
|
||||
return data.get("person", [])
|
||||
except json.JSONDecodeError:
|
||||
return []
|
||||
|
||||
def extract_keywords(text: str) -> list[str]:
|
||||
result = call(SYSTEM_PROMPT_KEYWORDS, text)
|
||||
if result is None:
|
||||
return []
|
||||
try:
|
||||
import json
|
||||
data = json.loads(result)
|
||||
return data.get("keywords", [])
|
||||
except json.JSONDecodeError:
|
||||
return []
|
||||
@@ -0,0 +1,247 @@
|
||||
import argparse
|
||||
import json
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
|
||||
import elastic.client as es_client
|
||||
import llm.client as llm_client
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
POSTPROC_INDEX = "aktuell_postproc"
|
||||
|
||||
def print_pretty_json(data):
|
||||
logger.info(json.dumps(data, indent=2))
|
||||
|
||||
def sync_single_news(news_id, max_retries=3):
|
||||
attempt = 0
|
||||
while attempt < max_retries:
|
||||
try:
|
||||
news_text = es_client.get_entry("aktuell", news_id)["_source"]["full_content"]
|
||||
is_news_relevant = llm_client.is_news_relevant(news_text)
|
||||
authors = llm_client.extract_names(news_text)
|
||||
keywords = llm_client.extract_keywords(news_text)
|
||||
new_entry = {
|
||||
"news_id": news_id,
|
||||
"relevant": is_news_relevant,
|
||||
"authors": authors,
|
||||
"keywords": keywords,
|
||||
}
|
||||
es_client.add_entry("aktuell_postproc", new_entry)
|
||||
return True
|
||||
except Exception as error:
|
||||
attempt += 1
|
||||
logger.warning(f"Warning syncing news_id {news_id} (Attempt {attempt}/{max_retries})")
|
||||
if attempt < max_retries:
|
||||
time.sleep(1)
|
||||
else:
|
||||
logger.error(f"Error: {news_id} - {error}")
|
||||
return False
|
||||
|
||||
def update_keywords_single(postproc_entry, target_index=POSTPROC_INDEX, max_retries=3):
|
||||
doc_id = postproc_entry["_id"]
|
||||
source = postproc_entry["_source"]
|
||||
news_id = source["news_id"]
|
||||
attempt = 0
|
||||
while attempt < max_retries:
|
||||
try:
|
||||
news_text = es_client.get_entry("aktuell", news_id)["_source"]["full_content"]
|
||||
keywords = llm_client.extract_keywords(news_text)
|
||||
if not keywords:
|
||||
# Empty article or unparseable LLM answer: writing an empty list
|
||||
# would look like a success and block a later retry.
|
||||
logger.info(f"Skipped {news_id}: no keywords extracted.")
|
||||
return False
|
||||
if target_index == POSTPROC_INDEX:
|
||||
es_client.update_entry(POSTPROC_INDEX, doc_id, {"keywords": keywords})
|
||||
else:
|
||||
# Key the target doc on news_id so re-runs update it in place
|
||||
# instead of piling up a new document each time.
|
||||
es_client.index_entry(
|
||||
target_index,
|
||||
news_id,
|
||||
{
|
||||
"news_id": news_id,
|
||||
"relevant": source.get("relevant", 0),
|
||||
"authors": source.get("authors", []),
|
||||
"keywords": keywords,
|
||||
},
|
||||
)
|
||||
return True
|
||||
except Exception as error:
|
||||
attempt += 1
|
||||
logger.warning(f"Warning updating keywords for news_id {news_id} (Attempt {attempt}/{max_retries})")
|
||||
if attempt < max_retries:
|
||||
time.sleep(1)
|
||||
else:
|
||||
logger.error(f"Error: {news_id} - {error}")
|
||||
return False
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Synchronize news articles from 'aktuell' index to 'aktuell_postproc' index with relevance and author extraction using LLM.")
|
||||
|
||||
parser.add_argument(
|
||||
"--delete-all",
|
||||
action="store_true",
|
||||
help="Delete all entries from index 'aktuell_postproc'.",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--sync-delta",
|
||||
action="store_true",
|
||||
help="Sync only missing entries from 'aktuell' to 'aktuell_postproc'.",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--update-keywords",
|
||||
action="store_true",
|
||||
help="Add 'keywords' to existing 'aktuell_postproc' entries that don't have them yet (keeps relevant/authors).",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--reset-keywords",
|
||||
action="store_true",
|
||||
help="Remove the 'keywords' field from all 'aktuell_postproc' entries (keeps relevant/authors). Run before re-extracting with a new prompt.",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--stats",
|
||||
action="store_true",
|
||||
help="Print statistics about the entries in 'aktuell_postproc' and 'aktuell'.",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--threads",
|
||||
type=int,
|
||||
default=4,
|
||||
help="Number of threads for --sync-delta (Default: 4).",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--limit",
|
||||
type=int,
|
||||
default=None,
|
||||
help="Process at most this many entries (used by --update-keywords, e.g. for a smoke test).",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--target-index",
|
||||
default=POSTPROC_INDEX,
|
||||
help=(
|
||||
f"Index that --update-keywords writes to (default: {POSTPROC_INDEX}). Any other "
|
||||
"index gets new documents instead of in-place updates, and every entry is "
|
||||
"re-extracted rather than only those missing keywords."
|
||||
),
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.delete_all:
|
||||
es_client.delete_all_entries("aktuell_postproc")
|
||||
|
||||
if args.reset_keywords:
|
||||
result = es_client.remove_field_all("aktuell_postproc", "keywords")
|
||||
logger.info(f"Removed 'keywords' from {result.get('updated', 0)} entries.")
|
||||
|
||||
if args.sync_delta:
|
||||
start_time = time.time()
|
||||
aktuell_ids_raw = es_client.get_all_entries("aktuell", fields=["_id"])
|
||||
postproc_ids_raw = es_client.get_all_entries("aktuell_postproc", fields=["news_id"])
|
||||
|
||||
source_ids = set(entry["_id"] for entry in aktuell_ids_raw)
|
||||
target_ids = set(entry["_source"]["news_id"] for entry in postproc_ids_raw)
|
||||
missing_ids = source_ids - target_ids
|
||||
|
||||
logger.info(f"Number of missing IDs: {len(missing_ids)}")
|
||||
|
||||
missing_ids = list(missing_ids)
|
||||
total = len(missing_ids)
|
||||
|
||||
processed = 0
|
||||
succeeded = 0
|
||||
progress_lock = threading.Lock()
|
||||
|
||||
with ThreadPoolExecutor(max_workers=args.threads) as executor:
|
||||
futures = [executor.submit(sync_single_news, news_id) for news_id in missing_ids]
|
||||
for future in as_completed(futures):
|
||||
was_successful = future.result()
|
||||
with progress_lock:
|
||||
processed += 1
|
||||
if was_successful:
|
||||
succeeded += 1
|
||||
logger.info(f"Sync: {processed} / {total}")
|
||||
|
||||
end_time = time.time()
|
||||
logger.info(f"Sync DONE: {succeeded} entries synced.")
|
||||
logger.info(f"Time taken: {end_time - start_time} seconds.")
|
||||
|
||||
if args.update_keywords:
|
||||
start_time = time.time()
|
||||
postproc_entries = es_client.get_all_entries(
|
||||
POSTPROC_INDEX, fields=["news_id", "keywords", "relevant", "authors"]
|
||||
)
|
||||
|
||||
if args.target_index == POSTPROC_INDEX:
|
||||
pending = [entry for entry in postproc_entries if not entry["_source"].get("keywords")]
|
||||
logger.info(f"Number of entries without keywords: {len(pending)}")
|
||||
else:
|
||||
# Writing elsewhere never marks the postproc entries, so the "missing
|
||||
# keywords" filter would select the same entries on every run. Pick
|
||||
# entries that already have keywords instead: those are known to come
|
||||
# from articles with actual content, unlike the empty archive stubs.
|
||||
pending = [entry for entry in postproc_entries if entry["_source"].get("keywords")]
|
||||
logger.info(f"Re-extracting keywords into '{args.target_index}': {len(pending)} candidates.")
|
||||
|
||||
if args.limit is not None:
|
||||
pending = pending[:args.limit]
|
||||
|
||||
total = len(pending)
|
||||
logger.info(f"Processing {total} entries.")
|
||||
|
||||
processed = 0
|
||||
succeeded = 0
|
||||
progress_lock = threading.Lock()
|
||||
|
||||
with ThreadPoolExecutor(max_workers=args.threads) as executor:
|
||||
futures = [
|
||||
executor.submit(update_keywords_single, entry, args.target_index)
|
||||
for entry in pending
|
||||
]
|
||||
for future in as_completed(futures):
|
||||
was_successful = future.result()
|
||||
with progress_lock:
|
||||
processed += 1
|
||||
if was_successful:
|
||||
succeeded += 1
|
||||
logger.info(f"Update keywords: {processed} / {total}")
|
||||
|
||||
end_time = time.time()
|
||||
logger.info(f"Update keywords DONE: {succeeded} entries updated.")
|
||||
logger.info(f"Time taken: {end_time - start_time} seconds.")
|
||||
|
||||
if args.stats:
|
||||
aktuell_entries = es_client.get_all_entries("aktuell", fields=["_id"])
|
||||
logger.info(f"Total entries in 'aktuell': {len(aktuell_entries)}")
|
||||
|
||||
postproc_entries = es_client.get_all_entries("aktuell_postproc", fields=["_id", "news_id", "relevant", "authors", "keywords"])
|
||||
total_entries = len(postproc_entries)
|
||||
relevant_count = sum(1 for entry in postproc_entries if entry["_source"]["relevant"] == 1)
|
||||
irrelevant_count = total_entries - relevant_count
|
||||
news_with_extracted_names = sum(1 for entry in postproc_entries if entry["_source"]["authors"])
|
||||
news_without_extracted_names = total_entries - news_with_extracted_names
|
||||
news_with_keywords = sum(1 for entry in postproc_entries if entry["_source"].get("keywords"))
|
||||
news_without_keywords = total_entries - news_with_keywords
|
||||
|
||||
logger.info(f"Total entries in 'aktuell_postproc': {total_entries}")
|
||||
logger.info(f"Relevant entries: {relevant_count}")
|
||||
logger.info(f"Irrelevant entries: {irrelevant_count}")
|
||||
logger.info(f"Entries with extracted names: {news_with_extracted_names}")
|
||||
logger.info(f"Entries without extracted names: {news_without_extracted_names}")
|
||||
logger.info(f"Entries with keywords: {news_with_keywords}")
|
||||
logger.info(f"Entries without keywords: {news_without_keywords}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -3,7 +3,6 @@ from pathlib import Path
|
||||
|
||||
from llama_parse import LlamaParse
|
||||
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent
|
||||
|
||||
AD_PATH = BASE_DIR / "AD.pdf"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import pymupdf4llm
|
||||
|
||||
AD_PATH = "188274\AD.pdf"
|
||||
CD_PATH = "188274\СD.pdf"
|
||||
AD_PATH = r"188274\AD.pdf"
|
||||
CD_PATH = r"188274\СD.pdf"
|
||||
|
||||
ad_md = pymupdf4llm.to_markdown(AD_PATH)
|
||||
cd_md = pymupdf4llm.to_markdown(CD_PATH)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from pathlib import Path
|
||||
import getpass
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pymupdf
|
||||
import requests
|
||||
@@ -206,7 +206,7 @@ def make_debug_data(
|
||||
) -> dict:
|
||||
choice = {}
|
||||
|
||||
if "choices" in data and data["choices"]:
|
||||
if data.get("choices"):
|
||||
choice = data["choices"][0]
|
||||
|
||||
message = choice.get("message", {})
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from pathlib import Path
|
||||
import getpass
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import requests
|
||||
|
||||
@@ -181,7 +181,7 @@ def make_debug_data(
|
||||
):
|
||||
choice = {}
|
||||
|
||||
if "choices" in data and data["choices"]:
|
||||
if data.get("choices"):
|
||||
choice = data["choices"][0]
|
||||
|
||||
message = choice.get("message", {})
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from pathlib import Path
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
SCRIPT_DIR = Path(__file__).resolve().parent
|
||||
ROOT_DIR = SCRIPT_DIR
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from pathlib import Path
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import pymupdf
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from pathlib import Path
|
||||
|
||||
import pymupdf # PyMuPDF
|
||||
|
||||
try:
|
||||
@@ -7,7 +8,7 @@ except ImportError:
|
||||
MarkItDown = None
|
||||
|
||||
|
||||
AD_PATH = Path("154115\AD.pdf")
|
||||
AD_PATH = Path(r"154115\AD.pdf")
|
||||
OUT_DIR = Path("ad_extraction_outputs3")
|
||||
OUT_DIR.mkdir(exist_ok=True)
|
||||
|
||||
|
||||
@@ -1,337 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from collections import Counter
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
|
||||
ES_BASE_URL = "https://project.nes.uni-due.de/elastic"
|
||||
ES_API_KEY = "am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ=="
|
||||
TARGET_INDEX = "work-classifications"
|
||||
|
||||
SAMPLE_SIZE = 1000
|
||||
RANDOM_SEED = 20260713
|
||||
REQUEST_TIMEOUT = 60.0
|
||||
|
||||
OUTPUT_DIR = ROOT / "evaluation"
|
||||
OUTPUT_FILE = OUTPUT_DIR / "index_validation_audit_1000.json"
|
||||
|
||||
|
||||
def now() -> str:
|
||||
return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
|
||||
|
||||
|
||||
def authorization_header(api_key: str) -> str:
|
||||
value = api_key.strip()
|
||||
if not value:
|
||||
raise ValueError(
|
||||
"ES_API_KEY is empty. Set it at the top of the script."
|
||||
)
|
||||
if value.startswith("ApiKey "):
|
||||
return value
|
||||
return f"ApiKey {value}"
|
||||
|
||||
|
||||
def es_request(
|
||||
session: requests.Session,
|
||||
method: str,
|
||||
path: str,
|
||||
body: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
url = f"{ES_BASE_URL.rstrip('/')}/{path.lstrip('/')}"
|
||||
response = session.request(
|
||||
method,
|
||||
url,
|
||||
json=body,
|
||||
timeout=REQUEST_TIMEOUT,
|
||||
)
|
||||
response.raise_for_status()
|
||||
|
||||
payload = response.json()
|
||||
if not isinstance(payload, dict):
|
||||
raise ValueError("Elasticsearch returned a non-object JSON response")
|
||||
|
||||
return payload
|
||||
|
||||
|
||||
def total_hits_value(total: Any) -> int:
|
||||
if isinstance(total, int):
|
||||
return total
|
||||
if isinstance(total, dict):
|
||||
value = total.get("value")
|
||||
if isinstance(value, int):
|
||||
return value
|
||||
raise ValueError("Could not read Elasticsearch total hits")
|
||||
|
||||
|
||||
def load_random_sample(
|
||||
session: requests.Session,
|
||||
) -> tuple[int, list[dict[str, Any]]]:
|
||||
body = {
|
||||
"size": SAMPLE_SIZE,
|
||||
"track_total_hits": True,
|
||||
"_source": [
|
||||
"work_id",
|
||||
"classification",
|
||||
"validation",
|
||||
"classification_meta",
|
||||
],
|
||||
"query": {
|
||||
"function_score": {
|
||||
"query": {
|
||||
"match_all": {}
|
||||
},
|
||||
"random_score": {
|
||||
"seed": RANDOM_SEED,
|
||||
"field": "_seq_no",
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
response = es_request(
|
||||
session,
|
||||
"POST",
|
||||
f"{TARGET_INDEX}/_search",
|
||||
body,
|
||||
)
|
||||
|
||||
hits_block = response.get("hits")
|
||||
if not isinstance(hits_block, dict):
|
||||
raise ValueError("Elasticsearch response has no hits object")
|
||||
|
||||
index_total = total_hits_value(hits_block.get("total"))
|
||||
raw_hits = hits_block.get("hits")
|
||||
|
||||
if not isinstance(raw_hits, list):
|
||||
raise ValueError("Elasticsearch response has no hits list")
|
||||
|
||||
documents: list[dict[str, Any]] = []
|
||||
|
||||
for hit in raw_hits:
|
||||
if not isinstance(hit, dict):
|
||||
continue
|
||||
|
||||
work_id = hit.get("_id")
|
||||
source = hit.get("_source")
|
||||
|
||||
if not isinstance(work_id, str):
|
||||
continue
|
||||
if not isinstance(source, dict):
|
||||
source = {}
|
||||
|
||||
documents.append(
|
||||
{
|
||||
"work_id": work_id,
|
||||
"source": source,
|
||||
}
|
||||
)
|
||||
|
||||
return index_total, documents
|
||||
|
||||
|
||||
def build_report(
|
||||
index_total: int,
|
||||
documents: list[dict[str, Any]],
|
||||
) -> dict[str, Any]:
|
||||
valid_count = 0
|
||||
invalid_count = 0
|
||||
missing_validation_count = 0
|
||||
|
||||
error_counts: Counter[str] = Counter()
|
||||
category_counts: Counter[str] = Counter()
|
||||
invalid_category_counts: Counter[str] = Counter()
|
||||
model_counts: Counter[str] = Counter()
|
||||
|
||||
invalid_items: list[dict[str, Any]] = []
|
||||
missing_validation_items: list[str] = []
|
||||
sampled_work_ids: list[str] = []
|
||||
|
||||
for document in documents:
|
||||
work_id = document["work_id"]
|
||||
source = document["source"]
|
||||
sampled_work_ids.append(work_id)
|
||||
|
||||
classification = source.get("classification")
|
||||
validation = source.get("validation")
|
||||
classification_meta = source.get("classification_meta")
|
||||
|
||||
if isinstance(classification, dict):
|
||||
category = classification.get("primary_category")
|
||||
if isinstance(category, str):
|
||||
category_counts[category] += 1
|
||||
else:
|
||||
category = None
|
||||
else:
|
||||
classification = {}
|
||||
category = None
|
||||
|
||||
if isinstance(classification_meta, dict):
|
||||
model = classification_meta.get("model")
|
||||
if isinstance(model, str):
|
||||
model_counts[model] += 1
|
||||
else:
|
||||
model_counts["missing"] += 1
|
||||
else:
|
||||
model_counts["missing"] += 1
|
||||
|
||||
if not isinstance(validation, dict):
|
||||
missing_validation_count += 1
|
||||
missing_validation_items.append(work_id)
|
||||
continue
|
||||
|
||||
errors = validation.get("errors")
|
||||
if not isinstance(errors, list):
|
||||
errors = []
|
||||
|
||||
normalized_errors = [
|
||||
error
|
||||
for error in errors
|
||||
if isinstance(error, str) and error
|
||||
]
|
||||
|
||||
if validation.get("valid") is True:
|
||||
valid_count += 1
|
||||
continue
|
||||
|
||||
invalid_count += 1
|
||||
|
||||
for error in normalized_errors:
|
||||
error_counts[error] += 1
|
||||
|
||||
if category is not None:
|
||||
invalid_category_counts[category] += 1
|
||||
|
||||
invalid_items.append(
|
||||
{
|
||||
"work_id": work_id,
|
||||
"category": category,
|
||||
"score": classification.get(
|
||||
"applied_orientation_score"
|
||||
),
|
||||
"quadrant": classification.get("pasteur_quadrant"),
|
||||
"confidence": classification.get("confidence"),
|
||||
"errors": normalized_errors,
|
||||
}
|
||||
)
|
||||
|
||||
sampled_count = len(documents)
|
||||
evaluated_count = valid_count + invalid_count
|
||||
|
||||
return {
|
||||
"audit": {
|
||||
"created_at": now(),
|
||||
"index": TARGET_INDEX,
|
||||
"sample_size_requested": SAMPLE_SIZE,
|
||||
"sample_size_returned": sampled_count,
|
||||
"index_total_documents": index_total,
|
||||
"sampled_all_documents": sampled_count == index_total,
|
||||
"sampling_method": "random_score",
|
||||
"random_seed": RANDOM_SEED,
|
||||
},
|
||||
"summary": {
|
||||
"valid": valid_count,
|
||||
"invalid": invalid_count,
|
||||
"missing_validation": missing_validation_count,
|
||||
"evaluated": evaluated_count,
|
||||
"valid_rate_of_sample": (
|
||||
valid_count / sampled_count
|
||||
if sampled_count
|
||||
else None
|
||||
),
|
||||
"invalid_rate_of_sample": (
|
||||
invalid_count / sampled_count
|
||||
if sampled_count
|
||||
else None
|
||||
),
|
||||
"missing_validation_rate_of_sample": (
|
||||
missing_validation_count / sampled_count
|
||||
if sampled_count
|
||||
else None
|
||||
),
|
||||
"valid_rate_among_evaluated": (
|
||||
valid_count / evaluated_count
|
||||
if evaluated_count
|
||||
else None
|
||||
),
|
||||
},
|
||||
"validation_errors": {
|
||||
"total_error_occurrences": sum(error_counts.values()),
|
||||
"counts": dict(error_counts.most_common()),
|
||||
},
|
||||
"distributions": {
|
||||
"categories": dict(category_counts),
|
||||
"invalid_categories": dict(invalid_category_counts),
|
||||
"models": dict(model_counts),
|
||||
},
|
||||
"invalid_items": invalid_items,
|
||||
"missing_validation_items": missing_validation_items,
|
||||
"sampled_work_ids": sampled_work_ids,
|
||||
"interpretation": (
|
||||
"This audit evaluates stored validation results only. "
|
||||
"A valid result is structurally consistent but is not proof "
|
||||
"that the scientific classification is semantically correct."
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
session = requests.Session()
|
||||
session.headers.update(
|
||||
{
|
||||
"Authorization": authorization_header(ES_API_KEY),
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
)
|
||||
|
||||
index_total, documents = load_random_sample(session)
|
||||
report = build_report(index_total, documents)
|
||||
|
||||
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
|
||||
OUTPUT_FILE.write_text(
|
||||
json.dumps(report, ensure_ascii=False, indent=2),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
summary = report["summary"]
|
||||
errors = report["validation_errors"]["counts"]
|
||||
|
||||
print(f"Index: {TARGET_INDEX}")
|
||||
print(
|
||||
"Sample: "
|
||||
f"{report['audit']['sample_size_returned']}/"
|
||||
f"{report['audit']['index_total_documents']}"
|
||||
)
|
||||
print(
|
||||
"Valid: "
|
||||
f"{summary['valid']} "
|
||||
f"({summary['valid_rate_of_sample']:.2%})"
|
||||
)
|
||||
print(
|
||||
"Invalid: "
|
||||
f"{summary['invalid']} "
|
||||
f"({summary['invalid_rate_of_sample']:.2%})"
|
||||
)
|
||||
print(
|
||||
"Missing validation: "
|
||||
f"{summary['missing_validation']} "
|
||||
f"({summary['missing_validation_rate_of_sample']:.2%})"
|
||||
)
|
||||
|
||||
if errors:
|
||||
print("Validation errors:")
|
||||
for error, count in errors.items():
|
||||
print(f" {error}: {count}")
|
||||
else:
|
||||
print("Validation errors: none")
|
||||
|
||||
print(f"Report: {OUTPUT_FILE}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
File diff suppressed because it is too large
Load Diff
+543
@@ -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": []
|
||||
}
|
||||
}
|
||||
@@ -1,611 +0,0 @@
|
||||
import json
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Config
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
BASE_URL = "https://project.nes.uni-due.de/elastic".rstrip("/")
|
||||
API_KEY = "am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ=="
|
||||
|
||||
HEADERS = {
|
||||
"Authorization": f"ApiKey {API_KEY}",
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
}
|
||||
|
||||
UDE_OPENALEX_ID = "https://openalex.org/I62318514"
|
||||
UDE_ROR = "https://ror.org/04mz5ra38"
|
||||
UDE_DISPLAY_NAME = "University of Duisburg-Essen"
|
||||
|
||||
AFFILIATION_YEAR_GTE = 2025
|
||||
WORK_YEAR_GTE = 1950
|
||||
|
||||
EXCLUDED_TYPES = {
|
||||
"editorial",
|
||||
"erratum",
|
||||
"paratext",
|
||||
"retraction",
|
||||
}
|
||||
|
||||
AUTHOR_PAGE_SIZE = 1000
|
||||
AUTHOR_BATCH_SIZE = 250
|
||||
WORK_PAGE_SIZE = 1000
|
||||
INNER_HITS_SIZE = 100
|
||||
|
||||
OUTPUT_AUTHORS_JSONL = "ude_authors_set.jsonl"
|
||||
OUTPUT_WORKS_JSONL = "ude_works_set.jsonl"
|
||||
OUTPUT_REPORT_JSON = "ude_audit_report.json"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def es_search(index: str, body: dict[str, Any]) -> dict[str, Any]:
|
||||
url = f"{BASE_URL}/{index}/_search"
|
||||
response = requests.post(url, headers=HEADERS, json=body, timeout=120)
|
||||
|
||||
if not response.ok:
|
||||
raise RuntimeError(
|
||||
f"Elasticsearch error {response.status_code} for index {index}:\n"
|
||||
f"{response.text}"
|
||||
)
|
||||
|
||||
return response.json()
|
||||
|
||||
|
||||
def write_json(path: str, data: Any) -> None:
|
||||
with open(path, "w", encoding="utf-8", newline="\n") as f:
|
||||
json.dump(data, f, ensure_ascii=True, indent=2)
|
||||
|
||||
|
||||
def write_jsonl(path: str, records: list[dict[str, Any]]) -> None:
|
||||
with open(path, "w", encoding="utf-8", newline="\n") as f:
|
||||
for record in records:
|
||||
f.write(json.dumps(record, ensure_ascii=True) + "\n")
|
||||
|
||||
|
||||
def text_present(value: Any) -> bool:
|
||||
return isinstance(value, str) and bool(value.strip())
|
||||
|
||||
|
||||
def has_abstract(source: dict[str, Any]) -> bool:
|
||||
return text_present(source.get("abstract"))
|
||||
|
||||
|
||||
def is_ude_institution(institution: dict[str, Any] | None) -> bool:
|
||||
if not institution:
|
||||
return False
|
||||
|
||||
return (
|
||||
institution.get("id") == UDE_OPENALEX_ID
|
||||
or institution.get("ror") == UDE_ROR
|
||||
or institution.get("display_name") == UDE_DISPLAY_NAME
|
||||
)
|
||||
|
||||
|
||||
def get_ude_affiliation_years(author: dict[str, Any]) -> list[int]:
|
||||
years: set[int] = set()
|
||||
|
||||
for affiliation in author.get("affiliations", []) or []:
|
||||
institution = affiliation.get("institution")
|
||||
|
||||
if not is_ude_institution(institution):
|
||||
continue
|
||||
|
||||
for year in affiliation.get("years", []) or []:
|
||||
if isinstance(year, int):
|
||||
years.add(year)
|
||||
|
||||
return sorted(years)
|
||||
|
||||
|
||||
def recent_ude_affiliation_filter() -> dict[str, Any]:
|
||||
return {
|
||||
"nested": {
|
||||
"path": "affiliations",
|
||||
"query": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"term": {
|
||||
"affiliations.institution.id": UDE_OPENALEX_ID
|
||||
}
|
||||
},
|
||||
{"term": {"affiliations.institution.ror": UDE_ROR}},
|
||||
{
|
||||
"match_phrase": {
|
||||
"affiliations.institution.display_name": UDE_DISPLAY_NAME
|
||||
}
|
||||
},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
},
|
||||
{
|
||||
"range": {
|
||||
"affiliations.years": {"gte": AFFILIATION_YEAR_GTE}
|
||||
}
|
||||
},
|
||||
]
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def last_known_ude_filter() -> dict[str, Any]:
|
||||
return {
|
||||
"nested": {
|
||||
"path": "last_known_institutions",
|
||||
"query": {
|
||||
"match_phrase": {
|
||||
"last_known_institutions.display_name": UDE_DISPLAY_NAME
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def last_known_exists_filter() -> dict[str, Any]:
|
||||
return {
|
||||
"nested": {
|
||||
"path": "last_known_institutions",
|
||||
"query": {"exists": {"field": "last_known_institutions.display_name"}},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Author queries
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def backend_compatible_authors_query(search_after=None) -> dict[str, Any]:
|
||||
body = {
|
||||
"size": AUTHOR_PAGE_SIZE,
|
||||
"track_total_hits": True,
|
||||
"_source": [
|
||||
"id",
|
||||
"display_name",
|
||||
"orcid",
|
||||
"works_count",
|
||||
"cited_by_count",
|
||||
"last_known_institutions",
|
||||
"affiliations",
|
||||
],
|
||||
"query": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
last_known_ude_filter(),
|
||||
recent_ude_affiliation_filter(),
|
||||
]
|
||||
}
|
||||
},
|
||||
"sort": [{"id": {"order": "asc"}}],
|
||||
}
|
||||
|
||||
if search_after:
|
||||
body["search_after"] = search_after
|
||||
|
||||
return body
|
||||
|
||||
|
||||
def empty_last_known_recent_ude_authors_query(search_after=None) -> dict[str, Any]:
|
||||
body = {
|
||||
"size": AUTHOR_PAGE_SIZE,
|
||||
"track_total_hits": True,
|
||||
"_source": [
|
||||
"id",
|
||||
"display_name",
|
||||
"orcid",
|
||||
"works_count",
|
||||
"cited_by_count",
|
||||
"last_known_institutions",
|
||||
"affiliations",
|
||||
],
|
||||
"query": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
recent_ude_affiliation_filter(),
|
||||
],
|
||||
"must_not": [
|
||||
last_known_exists_filter(),
|
||||
],
|
||||
}
|
||||
},
|
||||
"sort": [{"id": {"order": "asc"}}],
|
||||
}
|
||||
|
||||
if search_after:
|
||||
body["search_after"] = search_after
|
||||
|
||||
return body
|
||||
|
||||
|
||||
def make_author_record(source: dict[str, Any], source_set: str) -> dict[str, Any]:
|
||||
return {
|
||||
"id": source.get("id"),
|
||||
"display_name": source.get("display_name"),
|
||||
"orcid": source.get("orcid"),
|
||||
"works_count": source.get("works_count"),
|
||||
"cited_by_count": source.get("cited_by_count"),
|
||||
"source_sets": [source_set],
|
||||
"ude_affiliation_years": get_ude_affiliation_years(source),
|
||||
}
|
||||
|
||||
|
||||
def merge_author(
|
||||
authors_by_id: dict[str, dict[str, Any]],
|
||||
source: dict[str, Any],
|
||||
source_set: str,
|
||||
) -> None:
|
||||
author_id = source.get("id")
|
||||
|
||||
if not author_id:
|
||||
return
|
||||
|
||||
if author_id not in authors_by_id:
|
||||
authors_by_id[author_id] = make_author_record(source, source_set)
|
||||
return
|
||||
|
||||
if source_set not in authors_by_id[author_id]["source_sets"]:
|
||||
authors_by_id[author_id]["source_sets"].append(source_set)
|
||||
|
||||
existing_years = set(authors_by_id[author_id].get("ude_affiliation_years") or [])
|
||||
existing_years.update(get_ude_affiliation_years(source))
|
||||
authors_by_id[author_id]["ude_affiliation_years"] = sorted(existing_years)
|
||||
|
||||
|
||||
def collect_author_group(
|
||||
authors_by_id: dict[str, dict[str, Any]],
|
||||
group_name: str,
|
||||
query_builder,
|
||||
) -> int:
|
||||
search_after = None
|
||||
total_expected = None
|
||||
collected = 0
|
||||
|
||||
while True:
|
||||
result = es_search("openalex-authors", query_builder(search_after))
|
||||
hits = result["hits"]["hits"]
|
||||
|
||||
if total_expected is None:
|
||||
total_expected = result["hits"]["total"]["value"]
|
||||
print(f"{group_name} expected: {total_expected}")
|
||||
|
||||
if not hits:
|
||||
break
|
||||
|
||||
for hit in hits:
|
||||
collected += 1
|
||||
merge_author(authors_by_id, hit["_source"], group_name)
|
||||
|
||||
search_after = hits[-1]["sort"]
|
||||
|
||||
print(f"{group_name}: read {collected} / {total_expected}")
|
||||
time.sleep(0.05)
|
||||
|
||||
return collected
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Work queries
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def works_by_author_batch_query(
|
||||
author_ids: list[str], search_after=None
|
||||
) -> dict[str, Any]:
|
||||
body = {
|
||||
"size": WORK_PAGE_SIZE,
|
||||
"track_total_hits": True,
|
||||
"_source": [
|
||||
"id",
|
||||
"doi",
|
||||
"title",
|
||||
"display_name",
|
||||
"abstract",
|
||||
"publication_year",
|
||||
"publication_date",
|
||||
"type",
|
||||
"language",
|
||||
],
|
||||
"query": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{"range": {"publication_year": {"gte": WORK_YEAR_GTE}}},
|
||||
{
|
||||
"nested": {
|
||||
"path": "authorships",
|
||||
"query": {"terms": {"authorships.author.id": author_ids}},
|
||||
"inner_hits": {
|
||||
"size": INNER_HITS_SIZE,
|
||||
"_source": [
|
||||
"authorships.author.id",
|
||||
"authorships.author.display_name",
|
||||
"author.id",
|
||||
"author.display_name",
|
||||
],
|
||||
},
|
||||
}
|
||||
},
|
||||
]
|
||||
}
|
||||
},
|
||||
"sort": [{"id": {"order": "asc"}}],
|
||||
}
|
||||
|
||||
if search_after:
|
||||
body["search_after"] = search_after
|
||||
|
||||
return body
|
||||
|
||||
|
||||
def extract_inner_hit_authors(hit: dict[str, Any]) -> list[dict[str, str]]:
|
||||
inner_hits = (
|
||||
hit.get("inner_hits", {}).get("authorships", {}).get("hits", {}).get("hits", [])
|
||||
)
|
||||
|
||||
authors = []
|
||||
|
||||
for inner_hit in inner_hits:
|
||||
source = inner_hit.get("_source") or {}
|
||||
|
||||
author = source.get("author")
|
||||
|
||||
if not author and "authorships" in source:
|
||||
authorship = source.get("authorships") or {}
|
||||
author = authorship.get("author")
|
||||
|
||||
if not isinstance(author, dict):
|
||||
continue
|
||||
|
||||
author_id = author.get("id")
|
||||
display_name = author.get("display_name")
|
||||
|
||||
if author_id:
|
||||
authors.append(
|
||||
{
|
||||
"id": author_id,
|
||||
"display_name": display_name,
|
||||
}
|
||||
)
|
||||
|
||||
return authors
|
||||
|
||||
|
||||
def minimal_work_record(source: dict[str, Any]) -> dict[str, Any]:
|
||||
work_type = source.get("type")
|
||||
|
||||
return {
|
||||
"id": source.get("id"),
|
||||
"doi": source.get("doi"),
|
||||
"title": source.get("title") or source.get("display_name"),
|
||||
"publication_year": source.get("publication_year"),
|
||||
"publication_date": source.get("publication_date"),
|
||||
"type": work_type,
|
||||
"language": source.get("language"),
|
||||
"has_abstract": has_abstract(source),
|
||||
"is_excluded_type": work_type in EXCLUDED_TYPES,
|
||||
"author_ids_in_set": [],
|
||||
"author_names_in_set": [],
|
||||
}
|
||||
|
||||
|
||||
def merge_work(
|
||||
works_by_id: dict[str, dict[str, Any]],
|
||||
hit: dict[str, Any],
|
||||
) -> None:
|
||||
source = hit["_source"]
|
||||
work_id = source.get("id")
|
||||
|
||||
if not work_id:
|
||||
return
|
||||
|
||||
if work_id not in works_by_id:
|
||||
works_by_id[work_id] = minimal_work_record(source)
|
||||
|
||||
work = works_by_id[work_id]
|
||||
|
||||
existing_author_ids = set(work.get("author_ids_in_set") or [])
|
||||
existing_author_names = set(work.get("author_names_in_set") or [])
|
||||
|
||||
for author in extract_inner_hit_authors(hit):
|
||||
author_id = author.get("id")
|
||||
display_name = author.get("display_name")
|
||||
|
||||
if author_id:
|
||||
existing_author_ids.add(author_id)
|
||||
|
||||
if display_name:
|
||||
existing_author_names.add(display_name)
|
||||
|
||||
work["author_ids_in_set"] = sorted(existing_author_ids)
|
||||
work["author_names_in_set"] = sorted(existing_author_names)
|
||||
|
||||
|
||||
def collect_works_by_final_authors(
|
||||
authors: list[dict[str, Any]],
|
||||
) -> list[dict[str, Any]]:
|
||||
author_ids = [author["id"] for author in authors if author.get("id")]
|
||||
works_by_id: dict[str, dict[str, Any]] = {}
|
||||
|
||||
total_batches = (len(author_ids) + AUTHOR_BATCH_SIZE - 1) // AUTHOR_BATCH_SIZE
|
||||
|
||||
for batch_start in range(0, len(author_ids), AUTHOR_BATCH_SIZE):
|
||||
batch = author_ids[batch_start : batch_start + AUTHOR_BATCH_SIZE]
|
||||
batch_number = batch_start // AUTHOR_BATCH_SIZE + 1
|
||||
|
||||
print(f"\nWork batch {batch_number}/{total_batches}")
|
||||
|
||||
search_after = None
|
||||
batch_hits_read = 0
|
||||
|
||||
while True:
|
||||
result = es_search(
|
||||
"openalex-works*",
|
||||
works_by_author_batch_query(batch, search_after),
|
||||
)
|
||||
|
||||
hits = result["hits"]["hits"]
|
||||
|
||||
if not hits:
|
||||
break
|
||||
|
||||
batch_hits_read += len(hits)
|
||||
|
||||
for hit in hits:
|
||||
merge_work(works_by_id, hit)
|
||||
|
||||
search_after = hits[-1]["sort"]
|
||||
|
||||
print(
|
||||
f" batch hits read: {batch_hits_read}, "
|
||||
f"unique works so far: {len(works_by_id)}"
|
||||
)
|
||||
|
||||
time.sleep(0.05)
|
||||
|
||||
return [works_by_id[work_id] for work_id in sorted(works_by_id.keys())]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Report
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def build_report(
|
||||
authors: list[dict[str, Any]],
|
||||
works: list[dict[str, Any]],
|
||||
backend_query_count: int,
|
||||
empty_last_known_query_count: int,
|
||||
) -> dict[str, Any]:
|
||||
backend_author_count = sum(
|
||||
"backend_compatible" in author.get("source_sets", []) for author in authors
|
||||
)
|
||||
|
||||
empty_last_known_author_count = sum(
|
||||
"empty_last_known_recent_ude" in author.get("source_sets", [])
|
||||
for author in authors
|
||||
)
|
||||
|
||||
works_with_abstract = sum(work.get("has_abstract") is True for work in works)
|
||||
works_excluded_type = sum(work.get("is_excluded_type") is True for work in works)
|
||||
|
||||
return {
|
||||
"filters": {
|
||||
"final_author_set": {
|
||||
"definition": (
|
||||
"backend-compatible UDE authors plus authors with recent UDE "
|
||||
"affiliation and empty last_known_institutions"
|
||||
),
|
||||
"components": {
|
||||
"backend_compatible": {
|
||||
"last_known_institutions.display_name": UDE_DISPLAY_NAME,
|
||||
"affiliations.institution": {
|
||||
"id": UDE_OPENALEX_ID,
|
||||
"ror": UDE_ROR,
|
||||
"display_name": UDE_DISPLAY_NAME,
|
||||
},
|
||||
"affiliations.years_gte": AFFILIATION_YEAR_GTE,
|
||||
},
|
||||
"empty_last_known_recent_ude": {
|
||||
"last_known_institutions": "missing_or_empty",
|
||||
"affiliations.institution": {
|
||||
"id": UDE_OPENALEX_ID,
|
||||
"ror": UDE_ROR,
|
||||
"display_name": UDE_DISPLAY_NAME,
|
||||
},
|
||||
"affiliations.years_gte": AFFILIATION_YEAR_GTE,
|
||||
},
|
||||
},
|
||||
},
|
||||
"work_set": {
|
||||
"definition": "All works authored by final_author_set",
|
||||
"work_year_gte": WORK_YEAR_GTE,
|
||||
"works_index": "openalex-works*",
|
||||
},
|
||||
"excluded_types": sorted(EXCLUDED_TYPES),
|
||||
},
|
||||
"counts": {
|
||||
"backend_author_count": backend_author_count,
|
||||
"empty_last_known_recent_ude_author_count": empty_last_known_author_count,
|
||||
"final_author_count": len(authors),
|
||||
"works_by_final_authors": len(works),
|
||||
"works_with_abstract": works_with_abstract,
|
||||
"works_without_abstract": len(works) - works_with_abstract,
|
||||
"works_excluded_type": works_excluded_type,
|
||||
},
|
||||
"debug_counts": {
|
||||
"backend_query_count_before_dedup": backend_query_count,
|
||||
"empty_last_known_query_count_before_dedup": empty_last_known_query_count,
|
||||
},
|
||||
"output_files": {
|
||||
"authors": OUTPUT_AUTHORS_JSONL,
|
||||
"works": OUTPUT_WORKS_JSONL,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Main
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def main():
|
||||
authors_by_id: dict[str, dict[str, Any]] = {}
|
||||
|
||||
backend_query_count = collect_author_group(
|
||||
authors_by_id=authors_by_id,
|
||||
group_name="backend_compatible",
|
||||
query_builder=backend_compatible_authors_query,
|
||||
)
|
||||
|
||||
empty_last_known_query_count = collect_author_group(
|
||||
authors_by_id=authors_by_id,
|
||||
group_name="empty_last_known_recent_ude",
|
||||
query_builder=empty_last_known_recent_ude_authors_query,
|
||||
)
|
||||
|
||||
authors = [authors_by_id[author_id] for author_id in sorted(authors_by_id.keys())]
|
||||
|
||||
for author in authors:
|
||||
author["source_sets"] = sorted(author["source_sets"])
|
||||
|
||||
write_jsonl(OUTPUT_AUTHORS_JSONL, authors)
|
||||
|
||||
print(f"\nFinal author count: {len(authors)}")
|
||||
print(f"Written: {OUTPUT_AUTHORS_JSONL}")
|
||||
|
||||
works = collect_works_by_final_authors(authors)
|
||||
write_jsonl(OUTPUT_WORKS_JSONL, works)
|
||||
|
||||
print(f"\nFinal work count: {len(works)}")
|
||||
print(f"Written: {OUTPUT_WORKS_JSONL}")
|
||||
|
||||
report = build_report(
|
||||
authors=authors,
|
||||
works=works,
|
||||
backend_query_count=backend_query_count,
|
||||
empty_last_known_query_count=empty_last_known_query_count,
|
||||
)
|
||||
|
||||
write_json(OUTPUT_REPORT_JSON, report)
|
||||
|
||||
print("\n=== AUDIT SUMMARY ===")
|
||||
print(json.dumps(report["counts"], ensure_ascii=False, indent=2))
|
||||
print(f"\nWritten: {OUTPUT_REPORT_JSON}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,943 +0,0 @@
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5035144962",
|
||||
"display_name": "Christine Arentz"
|
||||
},
|
||||
"works": [
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5035144962",
|
||||
"display_name": "Christine Arentz"
|
||||
},
|
||||
"work_id": "https://openalex.org/W7139039021",
|
||||
"doi": "https://doi.org/10.57684/cos-1429",
|
||||
"input": {
|
||||
"title": "Analyse der Begutachtungsdaten privatversicherter Pflegebedürftiger und mögliche Implikationen für die gesetzliche Pflegeversicherung",
|
||||
"abstract": "Hintergrund: Seit Einführung des neuen Pflegebedürftigkeitsbegriffs 2017 ist die Anzahl der Leistungsempfänger in der gesetzlichen Pflegeversicherung deutlich über das demografisch zu erwartende Ausmaß angestiegen. In der Folge sind die Beitragssätze in der Sozialen Pflegeversicherung und die Prämien in der Privaten Pflegepflichtversicherung wiederholt gestiegen. Dieser Beitrag analysiert die Charakteristika der Erstantragsteller in der privaten Pflegepflichtversicherung mit einem Fokus auf Pflegegrad 1, um Präventionspotentiale für die Versicherten und Reformelemente für die gesetzliche Pflegeversicherung zu identifizieren. Methodik: Die Datenerhebung erfolgte durch die Medicproof GmbH im Rahmen der Pflegebegutachtung der Privatversicherten in Deutschland, die von 2017-2023 einen Erstantrag auf Leistungen der Privaten Pflegepflichtversicherung stellten. Die Daten wurden in aggregierter Form zur Verfügung gestellt und mit deskriptiven Methoden ausgewertet. Ergebnisse: Über 70% der Erstanträge enden in einer Einstufung in Pflegegrad 1 oder 2. Versicherte in höheren Pflegegraden sind eher männlich und tendenziell jünger. Sie erhalten ein hohes Maß an professioneller Pflege, wohingegen Versicherte in Pflegegrad 1 zu 83% ausschließlich von privaten Pflegepersonen gepflegt werden. Versicherte in Pflegegrad 1 haben vor allem leichte Einschränkungen im Bereich der Mobilität. Daraus ergeben sich Einschränkungen im Bereich der Selbstversorgung und im Umgang mit Krankheits- und therapiebedingten Anforderungen. 30% der Pflegebedürftigen in Pflegegrad 1 werden bereits innerhalb eines Jahres hochgestuft, dabei verschlechtern sich vor allem die Mobilität sowie kognitive und kommunikative Fähigkeiten. Schlussfolgerung: Von dem erleichterten Zugang zu Leistungen der Pflegeversicherung profitieren in Pflegegrad 1 vor allem Pflegebedürftige mit leichten Einschränkungen, die vor allem Unterstützung bei der Selbstversorgung und dem Umgang mit Krankheits- und therapiebedingten Anforderungen benötigen. Diese Gruppe benötigt häufig noch keine inhärente pflegerische Unterstützung. Allerdings werden viele innerhalb eines Jahres aufgrund von Verschlechterungen in präventionssensitiven Bereichen in einen höheren Pflegegrad eingestuft. Die zunehmende finanzielle Beanspruchung der Pflegeversicherung unterstreicht die Notwendigkeit, Ressourcen bedarfsgerechter einzusetzen und Prävention als zentralen Bestandteil der Leistungserbringung zu stärken.",
|
||||
"venue": "Cologne Open Science (RFH - University of Applied Sciences Cologne)",
|
||||
"work_type": "article",
|
||||
"topics": [
|
||||
"Health and Medical Studies",
|
||||
"General Health Professions",
|
||||
"Health Professions",
|
||||
"Social and Demographic Issues in Germany",
|
||||
"Social Policies and Healthcare Reform",
|
||||
"Political science",
|
||||
"Humanities",
|
||||
"Gynecology"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2026,
|
||||
"language": "de"
|
||||
},
|
||||
"debug": {
|
||||
"publication_date": "2026-01-01",
|
||||
"has_abstract": true,
|
||||
"excluded_type": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5035144962",
|
||||
"display_name": "Christine Arentz"
|
||||
},
|
||||
"work_id": "https://openalex.org/W7140804993",
|
||||
"doi": "https://doi.org/10.2478/wd-2026-0044",
|
||||
"input": {
|
||||
"title": "Reform der Pflegeversicherung: Effizientere Leistungen und stärkere Kapitaldeckung",
|
||||
"abstract": "Abstract The tense financial situation of social care insurance will worsen significantly as the baby boomers reach the age when they will need care. In order to avoid placing an even greater burden on contributors, reforms should focus primarily on the expenditure side. To this end, benefits should be reviewed and prioritized, and parallel financing structures should be eliminated. Pay-as-you-go financing should be stabilized through greater capital coverage. In addition, it makes sense to cover co-payments through private supplementary insurance. Simplified and standardized regulation of the long-term care sector can also reduce costs and, as a result, co-payments.",
|
||||
"venue": "Wirtschaftsdienst",
|
||||
"work_type": "article",
|
||||
"topics": [
|
||||
"Social Policies and Healthcare Reform",
|
||||
"General Health Professions",
|
||||
"Health Professions",
|
||||
"Social and Demographic Issues in Germany",
|
||||
"German Economic Analysis & Policies",
|
||||
"Economics and Econometrics",
|
||||
"Economics, Econometrics and Finance",
|
||||
"Order (exchange)"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2026,
|
||||
"language": "en"
|
||||
},
|
||||
"debug": {
|
||||
"publication_date": "2026-03-01",
|
||||
"has_abstract": true,
|
||||
"excluded_type": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5035144962",
|
||||
"display_name": "Christine Arentz"
|
||||
},
|
||||
"work_id": "https://openalex.org/W7116692940",
|
||||
"doi": "https://doi.org/10.2478/wd-2025-0217",
|
||||
"input": {
|
||||
"title": "Soziale Pflegeversicherung: Finanziell stabilisieren",
|
||||
"abstract": null,
|
||||
"venue": "Wirtschaftsdienst",
|
||||
"work_type": "article",
|
||||
"topics": [
|
||||
"Social and Demographic Issues in Germany",
|
||||
"General Health Professions",
|
||||
"Health Professions",
|
||||
"Social Policies and Healthcare Reform",
|
||||
"Sustainability, Environment, and Optimization Algorithms",
|
||||
"Water Science and Technology",
|
||||
"Environmental Science",
|
||||
"Economics"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2025,
|
||||
"language": "en"
|
||||
},
|
||||
"debug": {
|
||||
"publication_date": "2025-12-01",
|
||||
"has_abstract": false,
|
||||
"excluded_type": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5035144962",
|
||||
"display_name": "Christine Arentz"
|
||||
},
|
||||
"work_id": "https://openalex.org/W4382499444",
|
||||
"doi": "https://doi.org/10.1007/978-3-658-37071-8_6",
|
||||
"input": {
|
||||
"title": "Absicherung von Pflegekostenrisiken im Spannungsfeld von Versicherungsprinzipien und Solidaritätsnormen",
|
||||
"abstract": "Zusammenfassung Die gesetzliche Pflegeversicherung wurde 1995 für alle Bürger verpflichtend als Teilleistungsversicherung eingeführt. Die Versicherungspflicht war folgerichtig, um die Gesellschaft vor Freifahrerverhalten zu schützen. Allerdings hat die Ausgestaltung als Teilleistungsversicherung bei gleichzeitig unzureichender Dynamisierung der Versicherungsleistungen zu einem insbesondere im stationären Bereich immer höheren Eigenanteil der Pflegebedürftigen an den Pflegekosten geführt. Dieser Umstand ist seit einigen Jahren Gegenstand fortlaufender politischer Debatten und Reformbemühungen. Nach einem Problemaufriss wird die aktuelle Debatte eingeordnet und diskutiert, wie in einer alternden Gesellschaft eine absehbar weiter steigende Finanzierungslast aus den Pflegekostenrisiken auf die verschiedenen Akteure (Versicherung, Gesellschaft und Pflegebedürftige) verteilt werden soll. Hierbei spielen unterschiedliche Solidaritätsnormen eine entscheidende Rolle, um die unterschiedlichen Vorstellungen zur Fairness der Lastenverteilung zu verstehen.",
|
||||
"venue": null,
|
||||
"work_type": "book-chapter",
|
||||
"topics": [
|
||||
"Social and Demographic Issues in Germany",
|
||||
"General Health Professions",
|
||||
"Health Professions",
|
||||
"Health and Medical Studies",
|
||||
"Social Policies and Healthcare Reform",
|
||||
"Political science",
|
||||
"Humanities",
|
||||
"Art"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2023,
|
||||
"language": "de"
|
||||
},
|
||||
"debug": {
|
||||
"publication_date": "2023-01-01",
|
||||
"has_abstract": true,
|
||||
"excluded_type": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5035144962",
|
||||
"display_name": "Christine Arentz"
|
||||
},
|
||||
"work_id": "https://openalex.org/W3213629311",
|
||||
"doi": null,
|
||||
"input": {
|
||||
"title": "Ihr Kinderlein kommet? Regelungen für den Schul- und Kitabesuch in der Pandemie im Bundesländervergleich",
|
||||
"abstract": "Neben den Zielen des Infektionsschutzes und der Vermeidung von Überlastungen der Kapazitäten des Gesundheitswesens ist auch das Nutzen von Bildungs- und Betreuungsangeboten ein weiteres Ziel, das insbesondere im Kontext steigender Frauenerwerbstätigkeit und im Hinblick auf das Kindeswohl Bedeutung erlangt hat. Letzteres rückte insbesondere während der corona-bedingten Kita- und Schulschließungen in das gesellschaftliche Bewusstsein. Allerdings stehen diese drei Ziele - bei gegebenen Testkapazitäten und ambulanten Behandlungskapazitäten - in einem Konflikt. Denn gerade bei Kindern und Jugendlichen treten Erkrankungen, deren Symptome auch auf eine SARS-CoV-2-Infektion hinweisen könnten, im Vergleich zu Erwachsenen häufiger auf. Im letzten Jahr schwankte die Anzahl derjenigen Kinder und Jugendlichen, die neu aufgetretene \"respiratorische Symptome\" wie Schnupfen, Husten oder Halsschmerzen aufwiesen, im November und Dezember um wöchentlich eine Million, teilweise lagen sie darüber. Würden in diesem Jahr alle Kinder und Jugendliche mit diesen Symptomen getestet, müssten wahrscheinlich fast alle der gegenwärtig möglichen PCR-Tests im November und Dezember allein für diese Bevölkerungsgruppe verwendet werden. Suchten gleichzeitig nur die Hälfte aller entsprechend erkrankten Kinder einen Kinderarzt auf - in \"normalen\" Zeiten sind es durchschnittlich etwa ein Fünftel - müsste jeder Kinderarzt im Durchschnitt allein 275 gesetzlich versicherte Patienten mehr in den Monaten November und Dezember behandeln. [...]",
|
||||
"venue": "RePEc: Research Papers in Economics",
|
||||
"work_type": "article",
|
||||
"topics": [
|
||||
"Health and Medical Studies",
|
||||
"General Health Professions",
|
||||
"Health Professions",
|
||||
"Immune responses and vaccinations",
|
||||
"Immunology",
|
||||
"Immunology and Microbiology",
|
||||
"Respiratory viral infections research",
|
||||
"Epidemiology"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2020,
|
||||
"language": "de"
|
||||
},
|
||||
"debug": {
|
||||
"publication_date": "2020-01-01",
|
||||
"has_abstract": true,
|
||||
"excluded_type": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5035144962",
|
||||
"display_name": "Christine Arentz"
|
||||
},
|
||||
"work_id": "https://openalex.org/W3013757714",
|
||||
"doi": null,
|
||||
"input": {
|
||||
"title": "Zwei-Säulen-Strategie in der Pflegefinanzierung: Einführung einer Eigenanteilsversicherung. Zum künftigen Umgang mit den selbst zu tragenden Pflegekosten",
|
||||
"abstract": "Die gesetzliche Pflegeversicherung ist als Teilleistungsversicherung konzipiert, ein Teil der tatsächlich anfallenden Pflegekosten muss seit jeher von den Pflegebedürftigen selbst getragen werden. Allerdings ist dieser selbst zu finanzierende Anteil an den Pflegekosten seit Einführung der Versicherung fast kontinuierlich gestiegen - selbst die jüngsten Pflegereformen konnten diesen Trend nicht umkehren. Die steigenden Eigenanteile stehen zunehmend in der Kritik. Zudem wird befürchtet, dass gegenwärtige Reformvorhaben noch einmal deutliche Steigerungen der Pflegekosten - und damit auch der Eigenanteile - hervorbringen. Ein aktuell in der Politik diskutierter Reformvorschlag nimmt sich dieses Problems an. Vorgeschlagen wird ein sogenannter Sockel-Spitze-Tausch, der die pflegebedingten Eigenanteile deckeln soll. Allerdings würde dadurch der Umlageanteil in der Pflegeversicherung ausgeweitet. In Zeiten des demografischen Wandels erscheint dies riskant. Auf mittlere Sicht besteht dann das politische Risiko, Leistungen kürzen zu müssen, weil der Druck auf den Beitragssatz und damit die Belastung der jüngeren Generationen zu stark steigen. Deshalb wird in diesem Papier ein alternativer Reformvorschlag erarbeitet. Kern des Vorschlags ist es, das heutige System der Pflegefinanzierung auf zwei Säulen zu stützen: Die gegenwärtige gesetzliche Pflegeversicherung übernimmt einen gesetzlich fixierten prozentualen Anteil an den Gesamtkosten, eine kapitalgedeckte Eigenanteilsversicherung den verbleibenden Anteil - gegebenenfalls mit einem politisch definierten Selbstbehalt versehen. Ob diese zweite Säule verpflichtend eingeführt wird oder freiwillig verbleibt, wird hier offengelassen und nur gezeigt, welche flankierenden sozialpolitischen Maßnahmen ergriffen werden müssen, sollte die Eigenanteilsversicherung tatsächlich verpflichtend eingeführt werden. Die Umstellung auf eine Zwei-Säulen-Strategie bietet der Politik auch die Möglichkeit, die Mischung von Umlage- und Kapitaldeckungsverfahren so zu justieren, dass die heute bereits im Umlagesystem der sozialen Pflegeversicherung angelegten Belastungen für die jüngeren und zukünftigen Generationen nicht weiter erhöht oder sogar verringert werden. Ein deutlicher Vorteil eines solchen Modells liegt somit darin, dass die Lastverschiebung zwischen den Generationen im Umfang der kapitalgedeckt finanzierten Leistungen begrenzt werden kann, ohne Leistungsversprechen insgesamt einzuschränken.",
|
||||
"venue": "IW policy papers",
|
||||
"work_type": "article",
|
||||
"topics": [
|
||||
"Social and Demographic Issues in Germany",
|
||||
"General Health Professions",
|
||||
"Health Professions",
|
||||
"Social Policies and Healthcare Reform",
|
||||
"German Economic Analysis & Policies",
|
||||
"Economics and Econometrics",
|
||||
"Economics, Econometrics and Finance",
|
||||
"Political science"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2019,
|
||||
"language": "de"
|
||||
},
|
||||
"debug": {
|
||||
"publication_date": "2019-01-01",
|
||||
"has_abstract": true,
|
||||
"excluded_type": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5035144962",
|
||||
"display_name": "Christine Arentz"
|
||||
},
|
||||
"work_id": "https://openalex.org/W2789684353",
|
||||
"doi": "https://doi.org/10.5771/1611-5821-2018-1-21",
|
||||
"input": {
|
||||
"title": "Zur regionalen Ungleichverteilung von Ärzten in Deutschland – eine Frage der Privaten Krankenversicherung?",
|
||||
"abstract": "Gesundheits- und Sozialpolitik is an independent journal that informs about new developments in legislature and management regarding healthcare and social security. Insiders and scholars discuss recent reforms, rehash background information, develop case scenarios for legislature, describe ways and conflicts of management, and document jurisdiction in a comprised form.",
|
||||
"venue": "Gesundheits- und Sozialpolitik",
|
||||
"work_type": "article",
|
||||
"topics": [
|
||||
"Health and Medical Studies",
|
||||
"General Health Professions",
|
||||
"Health Professions",
|
||||
"Medical and Health Sciences Research",
|
||||
"Public Health, Environmental and Occupational Health",
|
||||
"Medicine",
|
||||
"Legislature",
|
||||
"Jurisdiction"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2018,
|
||||
"language": "de"
|
||||
},
|
||||
"debug": {
|
||||
"publication_date": "2018-01-01",
|
||||
"has_abstract": true,
|
||||
"excluded_type": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5035144962",
|
||||
"display_name": "Christine Arentz"
|
||||
},
|
||||
"work_id": "https://openalex.org/W2589041178",
|
||||
"doi": "https://doi.org/10.1093/eurpub/ckw167.070",
|
||||
"input": {
|
||||
"title": "Digitisation of health care – consequences for public and private health systems",
|
||||
"abstract": null,
|
||||
"venue": "European Journal of Public Health",
|
||||
"work_type": "article",
|
||||
"topics": [
|
||||
"Healthcare Systems and Public Health",
|
||||
"Epidemiology",
|
||||
"Medicine",
|
||||
"Health Systems, Economic Evaluations, Quality of Life",
|
||||
"Economics and Econometrics",
|
||||
"Economics, Econometrics and Finance",
|
||||
"Public health",
|
||||
"Health care"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2016,
|
||||
"language": "en"
|
||||
},
|
||||
"debug": {
|
||||
"publication_date": "2016-11-01",
|
||||
"has_abstract": false,
|
||||
"excluded_type": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5035144962",
|
||||
"display_name": "Christine Arentz"
|
||||
},
|
||||
"work_id": "https://openalex.org/W3084548972",
|
||||
"doi": null,
|
||||
"input": {
|
||||
"title": "Behavior-based tariffs in health insurance: Compatibility with the German system",
|
||||
"abstract": "In the following, we will analyze the consequences of an implementation of behavior-based tariffs/bonus programs in private and public health insurance in Germany. Programs rewarding a particular behavior have been used in health insurance for years. However, the respective debate has recently been revived as insurers started using so called wearables to monitor the behavior of their insured more accurately.",
|
||||
"venue": "Econstor (Econstor)",
|
||||
"work_type": "article",
|
||||
"topics": [
|
||||
"Healthcare Policy and Management",
|
||||
"Economics and Econometrics",
|
||||
"Economics, Econometrics and Finance",
|
||||
"Health and Medical Studies",
|
||||
"General Health Professions",
|
||||
"Health Professions",
|
||||
"Medical and Health Sciences Research",
|
||||
"Public Health, Environmental and Occupational Health"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2016,
|
||||
"language": "en"
|
||||
},
|
||||
"debug": {
|
||||
"publication_date": "2016-01-01",
|
||||
"has_abstract": true,
|
||||
"excluded_type": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5035144962",
|
||||
"display_name": "Christine Arentz"
|
||||
},
|
||||
"work_id": "https://openalex.org/W2276566688",
|
||||
"doi": null,
|
||||
"input": {
|
||||
"title": "Brot für die Tafel statt Brot für die Tonne? Frankreich verbietet dem Handel das Wegwerfen von Lebensmitteln",
|
||||
"abstract": null,
|
||||
"venue": "RePEc: Research Papers in Economics",
|
||||
"work_type": "preprint",
|
||||
"topics": [
|
||||
"European Socioeconomic and Political Studies",
|
||||
"Economics and Econometrics",
|
||||
"Economics, Econometrics and Finance",
|
||||
"Economic and Business Studies",
|
||||
"Tafel equation",
|
||||
"Tonne",
|
||||
"Chemistry",
|
||||
"Electrochemistry"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2015,
|
||||
"language": "de"
|
||||
},
|
||||
"debug": {
|
||||
"publication_date": "2015-01-01",
|
||||
"has_abstract": false,
|
||||
"excluded_type": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5035144962",
|
||||
"display_name": "Christine Arentz"
|
||||
},
|
||||
"work_id": "https://openalex.org/W2078290836",
|
||||
"doi": "https://doi.org/10.3790/sfo.63.9.231",
|
||||
"input": {
|
||||
"title": "Zum Umgang mit Nicht-Zahlern in der Krankenversicherung",
|
||||
"abstract": "Seit Einführung der allgemeinen Krankenversicherungspflicht in Deutschland dürfen Krankenkassen und private Krankenversicherungen Versicherte nicht mehr ausschließen, wenn diese ihre Beiträge oder Prämien nicht entrichten. Dies hat zu einer wachsenden Anzahl von Nicht-Zahlern und zu einer gesundheitspolitischen Diskussion um den Umgang mit diesen geführt. In diesem Beitrag wird argumentiert, dass zunächst Maßnahmen zur Begrenzung der Lasten durch Nicht-Zahler wie ein verbesserter Zugang zu Transferleistungen auf der einen sowie wirtschaftliche Anreize für Krankenkassen und Krankenversicherungen zur Forderungseintreibung auf der anderen Seite zu ergreifen sind. Darüber hinaus wird das Beitragsschulden-Entlastungsgesetz im Hinblick auf seine Verteilungswirkungen sowie auf die Kompatibilität mit der jeweiligen Finanzierungslogik der GKV und der PKV analysiert. Non-Payers in the German Health Insurance: Consequences and Policy Options Since the introduction of the health insurance mandate in Germany, health insurance funds are no longer allowed to exclude members who do not pay their premiums. This has led to an increase in the number of non-payers and a political discussion about how to deal with this problem. We argue that a first priority should be given to steps to reduce the burden of non-payers, such as improved access to social transfer payments as well as financial incentives for health insurance funds to collect outstanding bills. In addition, we analyse the recent legislation with regard to its distributional effects as well as its compatibility with the financial logic of the public and private health care system, respectively.",
|
||||
"venue": "Sozialer Fortschritt",
|
||||
"work_type": "article",
|
||||
"topics": [
|
||||
"Health and Medical Studies",
|
||||
"General Health Professions",
|
||||
"Health Professions",
|
||||
"Social and Demographic Issues in Germany",
|
||||
"Social Policies and Healthcare Reform",
|
||||
"Political science",
|
||||
"Health insurance",
|
||||
"Legislation"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2014,
|
||||
"language": "de"
|
||||
},
|
||||
"debug": {
|
||||
"publication_date": "2014-09-01",
|
||||
"has_abstract": true,
|
||||
"excluded_type": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5035144962",
|
||||
"display_name": "Christine Arentz"
|
||||
},
|
||||
"work_id": "https://openalex.org/W2263277206",
|
||||
"doi": null,
|
||||
"input": {
|
||||
"title": "Reform der gesetzlichen Pflegeversicherung. Systematische Antworten auf ökonomische Herausforderungen und politische Restriktionen: Pflegevorsorge und IWP-Optionsmodell",
|
||||
"abstract": "[Probleme der heutigen Pflegeversicherung und Ziele einer Reform] Über die Defizite und den Reformbedarf der sozialen Pflegeversicherung besteht weitgehend Einigkeit. Weniger Konsens besteht aber hinsichtlich der notwendigen Reformschritte und gangbarer Wege in Richtung einer nachhaltigen Finanzierung der zukünftigen Pflegekosten. Im Folgenden wird zuerst kurz erläutert, welche Probleme die heutige Ausgestaltung der Pflegeversicherung aufwirft und welche Ziele infolge dessen mit einer Systemreform verfolgt werden sollten. Ferner wird diskutiert, ob und wie bei einer Systemumstellung Vertrauensschutz gewährt werden sollte und welche (vermuteten) politischen Bedingungen zu berücksichtigen sind. Anhand dieser konzeptuellen Leitlinien wird anschließend aufgezeigt, wie diese Ziele durch das Konzept der Pflegevorsorge erreicht werden können. Zusätzlich werden Reformvarianten vorgestellt, die mögliche politische Restriktionen berücksichtigen.",
|
||||
"venue": "Econstor (Econstor)",
|
||||
"work_type": "preprint",
|
||||
"topics": [
|
||||
"Social and Demographic Issues in Germany",
|
||||
"General Health Professions",
|
||||
"Health Professions",
|
||||
"Social Policies and Healthcare Reform",
|
||||
"Political science"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2014,
|
||||
"language": "de"
|
||||
},
|
||||
"debug": {
|
||||
"publication_date": "2014-04-01",
|
||||
"has_abstract": true,
|
||||
"excluded_type": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5035144962",
|
||||
"display_name": "Christine Arentz"
|
||||
},
|
||||
"work_id": "https://openalex.org/W2574946759",
|
||||
"doi": "https://doi.org/10.1515/9783110503883-003",
|
||||
"input": {
|
||||
"title": "Zur Einführung der Bürgerprivatversicherung in das deutsche Krankenversicherungssystem: Mögliche Handlungsoptionen",
|
||||
"abstract": "Zur Einführung der Bürgerprivatversicherung in das deutsche Krankenversicherungssystem: Mögliche Handlungsoptionen was published in Grenzgänge zwischen Wirtschaftswissenschaft und Wirtschaftspolitik on page 17.",
|
||||
"venue": "MADOC (University of Mannheim)",
|
||||
"work_type": "book-chapter",
|
||||
"topics": [
|
||||
"German Economic Analysis & Policies",
|
||||
"Economics and Econometrics",
|
||||
"Economics, Econometrics and Finance",
|
||||
"Political science",
|
||||
"Philosophy"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2014,
|
||||
"language": "de"
|
||||
},
|
||||
"debug": {
|
||||
"publication_date": "2014-12-31",
|
||||
"has_abstract": true,
|
||||
"excluded_type": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5035144962",
|
||||
"display_name": "Christine Arentz"
|
||||
},
|
||||
"work_id": "https://openalex.org/W2257825028",
|
||||
"doi": null,
|
||||
"input": {
|
||||
"title": "Unisex-Tarife in der Krankenversicherung: Folgen für die deutsche private Krankenversicherung und das Reformkonzept der Bürgerversicherung",
|
||||
"abstract": "In einer Grundsatzentscheidung hat der Europäische Gerichtshof am 1. März 2011 (AZ: C-236/09) festgelegt, dass Versicherungen ab dem 21.12.2012 nur noch Unisextarife anbieten dürfen. Das Urteil nimmt hierbei Bezug auf die Gleichstellungsrichtlinie 2004/113/EG zur Gleichstellung von Mann und Frau beim Zugang zu Gütern und Dienstleistung. Das Urteil des EuGH ist juristisch umstritten (Gerken und Sohn, 2011), da die Definition von Diskrimi-nierung fragwürdig erscheint. So wurde in der bisherigen Rechtsprechung Diskriminierung als Ungleichbehandlung gleicher Sachverhalte angesehen. Auf die Versicherungswirtschaft bezogen war daher eine Differenzierung der Prämien dann nicht ausgeschlossen, wenn die Prämienunterschiede auf versicherungsmathematischen Unterschieden beruhten, etwa un-terschiedliche Lebensdauer zwischen Mann und Frau, und die Versicherer dies auch nach-weisen konnten (Busch und Pimpertz, 2012, S. 40). Das Urteil weicht von dieser ursprüngli-chen Position ab und erfordert nun die Gleichbehandlung auch offensichtlicher statistischer Unterschiede.",
|
||||
"venue": "Econstor (Econstor)",
|
||||
"work_type": "preprint",
|
||||
"topics": [
|
||||
"German Economic Analysis & Policies",
|
||||
"Economics and Econometrics",
|
||||
"Economics, Econometrics and Finance",
|
||||
"Political science"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2013,
|
||||
"language": "de"
|
||||
},
|
||||
"debug": {
|
||||
"publication_date": "2013-02-01",
|
||||
"has_abstract": true,
|
||||
"excluded_type": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5035144962",
|
||||
"display_name": "Christine Arentz"
|
||||
},
|
||||
"work_id": "https://openalex.org/W2268727219",
|
||||
"doi": null,
|
||||
"input": {
|
||||
"title": "Die Schweiz als Vorbild? Zur Zähmung \"gieriger\" Manager",
|
||||
"abstract": null,
|
||||
"venue": "Social Science Open Access Repository (GESIS – Leibniz Institute for the Social Sciences)",
|
||||
"work_type": "article",
|
||||
"topics": [
|
||||
"Sociology and Education Studies",
|
||||
"Sociology and Political Science",
|
||||
"Social Sciences",
|
||||
"Corporate Management and Leadership",
|
||||
"Organizational Behavior and Human Resource Management",
|
||||
"Business, Management and Accounting",
|
||||
"Corporate Governance and Management",
|
||||
"Strategy and Management"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2013,
|
||||
"language": "de"
|
||||
},
|
||||
"debug": {
|
||||
"publication_date": "2013-01-01",
|
||||
"has_abstract": false,
|
||||
"excluded_type": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5035144962",
|
||||
"display_name": "Christine Arentz"
|
||||
},
|
||||
"work_id": "https://openalex.org/W2271589891",
|
||||
"doi": null,
|
||||
"input": {
|
||||
"title": "Die Bürgerversicherung - mal wieder die Lösung allen Übels?",
|
||||
"abstract": null,
|
||||
"venue": "Social Science Open Access Repository (GESIS – Leibniz Institute for the Social Sciences)",
|
||||
"work_type": "article",
|
||||
"topics": [
|
||||
"German Economic Analysis & Policies",
|
||||
"Economics and Econometrics",
|
||||
"Economics, Econometrics and Finance",
|
||||
"Corporate Taxation and Avoidance",
|
||||
"Accounting",
|
||||
"Business, Management and Accounting",
|
||||
"Physics"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2013,
|
||||
"language": "de"
|
||||
},
|
||||
"debug": {
|
||||
"publication_date": "2013-01-01",
|
||||
"has_abstract": false,
|
||||
"excluded_type": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5035144962",
|
||||
"display_name": "Christine Arentz"
|
||||
},
|
||||
"work_id": "https://openalex.org/W2326608588",
|
||||
"doi": "https://doi.org/10.1055/s-0033-1335382",
|
||||
"input": {
|
||||
"title": "Zur Zukunft der PKV: Probleme und Perspektiven",
|
||||
"abstract": "Die deutsche Private Krankenversicherung (PKV) steht seit einiger Zeit verstärkt in der Kritik. Ihr werden vor allem Prämiensteigerungen und intransparente Tarifgestaltung vorgeworfen. Vor dem Hintergrund der Finanzkrise wird zudem die Zukunftsfähigkeit des kapitalgedeckten Systems der PKV infrage gestellt. Ziel des Artikels ist es, die entscheidenden Probleme der heutigen PKV aufzuzeigen und mögliche Lösungen zu präsentieren. Das grundlegende Problem des heutigen Systems ist der fehlende Wettbewerb um Bestandskunden. Durch die fehlende bzw. unzureichende Übertragbarkeit der Altersrückstellungen sind Versicherte, insbesondere mit Vorerkrankungen, nach kurzer Zeit bei ihrer Versicherung eingesperrt. Auch die Übertragung durchschnittlicher Altersrückstellungen löst dieses Problem nicht. Vielmehr bedarf es der Übertragung individuell prospektiver Altersrückstellungen, um einen effizienten Wettbewerb um alle Versicherten unabhängig von deren Risiko zu ermöglichen. Dieses System wird im Artikel ausführlich erläutert und mögliche Einwände analysiert.",
|
||||
"venue": "Gesundheitsökonomie & Qualitätsmanagement",
|
||||
"work_type": "article",
|
||||
"topics": [
|
||||
"Social and Demographic Issues in Germany",
|
||||
"General Health Professions",
|
||||
"Health Professions",
|
||||
"Health and Medical Studies",
|
||||
"Humanities",
|
||||
"Political science",
|
||||
"Gynecology",
|
||||
"Philosophy"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2013,
|
||||
"language": "de"
|
||||
},
|
||||
"debug": {
|
||||
"publication_date": "2013-08-09",
|
||||
"has_abstract": true,
|
||||
"excluded_type": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5035144962",
|
||||
"display_name": "Christine Arentz"
|
||||
},
|
||||
"work_id": "https://openalex.org/W3125706204",
|
||||
"doi": null,
|
||||
"input": {
|
||||
"title": "Zum Umgang mit Nicht-Zahlern in der Krankenversicherung",
|
||||
"abstract": "Abstract Seit Einfuhrung der allgemeinen Krankenversicherungspflicht in Deutschland durfen Krankenkassen und private Krankenversicherungen Versicherte nicht mehr ausschliesen, wenn diese ihre Beitrage oder Pramien nicht entrichten. Dies hat zu einer wachsenden Anzahl von Nicht-Zahlern und zu einer gesundheitspolitischen Diskussion um den Umgang mit diesen gefuhrt. In diesem Beitrag wird argumentiert, dass zunachst Masnahmen zur Begrenzung der Lasten durch Nicht-Zahler wie ein verbesserter Zugang zu Transferleistungen auf der einen sowie wirtschaftliche Anreize fur Krankenkassen und Krankenversicherungen zur Forderungseintreibung auf der anderen Seite zu ergreifen sind. Daruber hinaus wird das Beitragsschulden-Entlastungsgesetz im Hinblick auf seine Verteilungswirkungen sowie auf die Kompatibilitat mit der jeweiligen Finanzierungslogik der GKV und der PKV analysiert. Non-Payers in the German Health Insurance: Consequences and Policy Options Since the introduction of the health insurance mandate in German...",
|
||||
"venue": "RePEc: Research Papers in Economics",
|
||||
"work_type": "preprint",
|
||||
"topics": [
|
||||
"Social and Demographic Issues in Germany",
|
||||
"General Health Professions",
|
||||
"Health Professions",
|
||||
"Health and Medical Studies",
|
||||
"Social Policies and Healthcare Reform",
|
||||
"Political science",
|
||||
"Mandate",
|
||||
"Humanities"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2013,
|
||||
"language": "de"
|
||||
},
|
||||
"debug": {
|
||||
"publication_date": "2013-05-01",
|
||||
"has_abstract": true,
|
||||
"excluded_type": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5035144962",
|
||||
"display_name": "Christine Arentz"
|
||||
},
|
||||
"work_id": "https://openalex.org/W1968517082",
|
||||
"doi": "https://doi.org/10.1007/s10198-012-0406-7",
|
||||
"input": {
|
||||
"title": "Private health insurance: a role model for European health systems",
|
||||
"abstract": null,
|
||||
"venue": "The European Journal of Health Economics",
|
||||
"work_type": "article",
|
||||
"topics": [
|
||||
"Healthcare Policy and Management",
|
||||
"Economics and Econometrics",
|
||||
"Economics, Econometrics and Finance",
|
||||
"Global Health Care Issues",
|
||||
"General Health Professions",
|
||||
"Health Professions",
|
||||
"Health Systems, Economic Evaluations, Quality of Life",
|
||||
"Health care"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2012,
|
||||
"language": "en"
|
||||
},
|
||||
"debug": {
|
||||
"publication_date": "2012-06-21",
|
||||
"has_abstract": false,
|
||||
"excluded_type": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5035144962",
|
||||
"display_name": "Christine Arentz"
|
||||
},
|
||||
"work_id": "https://openalex.org/W2283336045",
|
||||
"doi": null,
|
||||
"input": {
|
||||
"title": "Auswirkungen von Gentests in der Krankenversicherung",
|
||||
"abstract": "Die Entschlüsselung des menschlichen Erbgutes hat neben großen Hoffnungen auf ein besseres Verständnis und Behandlungsmöglichkeiten schwerer Krankheiten eine Reihe von ethischen, sozialen und ökonomischen Fragen aufgeworfen. Die ethischen und sozialen Aspekte umfassen Fragen der informationellen Selbstbestimmtheit (wem gehört die Geninformation, kann man Individuen verpflichten, Gentests zu machen, Recht auf Nichtwissen) und eventueller gesellschaftlicher Diskriminierung von genetischen Risikopatienten (Durnin et al., 2012; Feiring, 2009). In ökonomischer Hinsicht ist vor allem das Versicherungswesen von der Entwicklung von Gentests betroffen, allen voran Lebens-, Kranken- und Pflegeversicherungen. Wenn genetische Informationen dazu verwendet werden können, eine präzisere Risikoeinschätzung vor-zunehmen, kann dies je nach Ausgestaltung des Versicherungssystems zu erheblichen Belastungen für Risikopatienten führen. Auf der anderen Seite erhofft man sich durch eine bessere Informationslage bessere Behandlungs- und Präventionsleistungen, womit die gesamt-wirtschaftlichen Ausgaben in der Kranken- oder Pflegeversicherung sinken könnten. Der vorliegende Artikel analysiert, welche konkreten Auswirkungen von Gentests auf bestehende private und öffentliche Krankenversicherungssysteme zu erwarten sind.",
|
||||
"venue": "Econstor (Econstor)",
|
||||
"work_type": "preprint",
|
||||
"topics": [
|
||||
"Healthcare Policy and Management",
|
||||
"Economics and Econometrics",
|
||||
"Economics, Econometrics and Finance",
|
||||
"Global Health Care Issues",
|
||||
"General Health Professions",
|
||||
"Health Professions",
|
||||
"Health and Medical Studies",
|
||||
"Political science"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2012,
|
||||
"language": "de"
|
||||
},
|
||||
"debug": {
|
||||
"publication_date": "2012-04-01",
|
||||
"has_abstract": true,
|
||||
"excluded_type": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5035144962",
|
||||
"display_name": "Christine Arentz"
|
||||
},
|
||||
"work_id": "https://openalex.org/W1937315894",
|
||||
"doi": null,
|
||||
"input": {
|
||||
"title": "Pflegevorsorge II: Einstieg in den Umstieg auf Kapitaldeckung in der Pflegeversicherung",
|
||||
"abstract": "Die gesetzliche Pflegeversicherung wurde 1995 mit dem Ziel eingeführt, die Sozialhilfeträger bzw. die Steuerzahler zu entlasten. Viele Personen hatten im Laufe ihres Erwerbslebens nicht für die finanziellen Risiken aus Pflegebedürftigkeit vorgesorgt und stießen daher bei Pflegebedürftigkeit schnell an die Grenzen ihrer finanziellen Belastungsfähigkeit. Die seit 1995 bestehende allgemeine Versicherungspflicht war daher vom Grundsatz her geeignet, die ungerechtfertigte Inanspruchnahme von gesellschaftlich finanzierten Mitteln zu vermeiden. Allerdings war die Ausgestaltung der gesetzlichen Pflegeversicherung vor dem Hin-tergrund der damals bereits bekannten demografischen Veränderungen von Anbeginn problematisch: Umlagesysteme sind von demografischen Verschiebungen besonders negativ betroffen. Abnehmende Geburtenraten und eine längere Lebenser-wartung führen zu einem immer ungünstigeren Verhältnis zwischen Beitragszahlern und Leistungsempfängern. Ohne drastische Eingriffe auf der Leistungsseite oder Re-form des Systems ist daher in der Zukunft der gesetzlichen Pflegeversicherung mit massiven Beitragssatzerhöhungen zu rechnen.",
|
||||
"venue": "RePEc: Research Papers in Economics",
|
||||
"work_type": "preprint",
|
||||
"topics": [
|
||||
"Social and Demographic Issues in Germany",
|
||||
"General Health Professions",
|
||||
"Health Professions",
|
||||
"Social Policies and Healthcare Reform",
|
||||
"Family Support in Illness",
|
||||
"Sociology and Political Science",
|
||||
"Social Sciences",
|
||||
"Political science"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2011,
|
||||
"language": "de"
|
||||
},
|
||||
"debug": {
|
||||
"publication_date": "2011-01-01",
|
||||
"has_abstract": true,
|
||||
"excluded_type": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5035144962",
|
||||
"display_name": "Christine Arentz"
|
||||
},
|
||||
"work_id": "https://openalex.org/W2059037213",
|
||||
"doi": "https://doi.org/10.1007/s10273-011-1191-0",
|
||||
"input": {
|
||||
"title": "Zur Reform der Pflegeversicherung: Einstieg in ein nachhaltiges und wettbewerbliches System",
|
||||
"abstract": "Bundesgesundheitsminister Rösler hat für 2011 eine umfassende Pflegereform sowohl der Leistungsseite als auch der Einnahmenstruktur angekündigt. Die Autoren dieses Beitrags machen den Vorschlag, die umlagefinanzierte Pflegeversicherung um eine kapitalgedeckte Säule zu ergänzen.",
|
||||
"venue": "Wirtschaftsdienst",
|
||||
"work_type": "article",
|
||||
"topics": [
|
||||
"Social and Demographic Issues in Germany",
|
||||
"General Health Professions",
|
||||
"Health Professions",
|
||||
"Social Policies and Healthcare Reform",
|
||||
"Political science",
|
||||
"Humanities",
|
||||
"Art"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2011,
|
||||
"language": "de"
|
||||
},
|
||||
"debug": {
|
||||
"publication_date": "2011-02-01",
|
||||
"has_abstract": true,
|
||||
"excluded_type": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5035144962",
|
||||
"display_name": "Christine Arentz"
|
||||
},
|
||||
"work_id": "https://openalex.org/W2101901310",
|
||||
"doi": null,
|
||||
"input": {
|
||||
"title": "Reform der gesetzlichen Pflegeversicherung: Teilkapitaldeckungsmodelle im Vergleich",
|
||||
"abstract": null,
|
||||
"venue": "Econstor (Econstor)",
|
||||
"work_type": "preprint",
|
||||
"topics": [
|
||||
"Social and Demographic Issues in Germany",
|
||||
"General Health Professions",
|
||||
"Health Professions",
|
||||
"Social Policies and Healthcare Reform",
|
||||
"Global Health Care Issues",
|
||||
"Political science"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2011,
|
||||
"language": "de"
|
||||
},
|
||||
"debug": {
|
||||
"publication_date": "2011-04-01",
|
||||
"has_abstract": false,
|
||||
"excluded_type": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5035144962",
|
||||
"display_name": "Christine Arentz"
|
||||
},
|
||||
"work_id": "https://openalex.org/W2135574436",
|
||||
"doi": null,
|
||||
"input": {
|
||||
"title": "Medizinisch-technischer Fortschritt im Gesund- heitswesen: Zentrale Kosten-Nutzen-Bewertung ohne Alternative?",
|
||||
"abstract": null,
|
||||
"venue": "Econstor (Econstor)",
|
||||
"work_type": "preprint",
|
||||
"topics": [
|
||||
"Health Systems, Economic Evaluations, Quality of Life",
|
||||
"Economics and Econometrics",
|
||||
"Economics, Econometrics and Finance",
|
||||
"Medical and Health Sciences Research",
|
||||
"Public Health, Environmental and Occupational Health",
|
||||
"Medicine",
|
||||
"Health and Medical Studies",
|
||||
"General Health Professions"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2011,
|
||||
"language": "de"
|
||||
},
|
||||
"debug": {
|
||||
"publication_date": "2011-01-01",
|
||||
"has_abstract": false,
|
||||
"excluded_type": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5035144962",
|
||||
"display_name": "Christine Arentz"
|
||||
},
|
||||
"work_id": "https://openalex.org/W2259174845",
|
||||
"doi": null,
|
||||
"input": {
|
||||
"title": "Die Pflegeversicherung ist pflegebedürftig – gut ergänzt ist halb gewonnen",
|
||||
"abstract": "Health Policy, Germany",
|
||||
"venue": "RePEc: Research Papers in Economics",
|
||||
"work_type": "preprint",
|
||||
"topics": [
|
||||
"Social and Demographic Issues in Germany",
|
||||
"General Health Professions",
|
||||
"Health Professions",
|
||||
"Erg",
|
||||
"Ophthalmology",
|
||||
"Medicine",
|
||||
"Retinal"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2011,
|
||||
"language": "de"
|
||||
},
|
||||
"debug": {
|
||||
"publication_date": "2011-01-01",
|
||||
"has_abstract": true,
|
||||
"excluded_type": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5035144962",
|
||||
"display_name": "Christine Arentz"
|
||||
},
|
||||
"work_id": "https://openalex.org/W1521055996",
|
||||
"doi": null,
|
||||
"input": {
|
||||
"title": "Die Gesundheitsreform: Transparent, stabil und gerecht?",
|
||||
"abstract": "Health Policy, Germany",
|
||||
"venue": "RePEc: Research Papers in Economics",
|
||||
"work_type": "preprint",
|
||||
"topics": [
|
||||
"Health and Medical Studies",
|
||||
"General Health Professions",
|
||||
"Health Professions",
|
||||
"Chemistry"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2010,
|
||||
"language": "de"
|
||||
},
|
||||
"debug": {
|
||||
"publication_date": "2010-01-01",
|
||||
"has_abstract": true,
|
||||
"excluded_type": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5035144962",
|
||||
"display_name": "Christine Arentz"
|
||||
},
|
||||
"work_id": "https://openalex.org/W2256739053",
|
||||
"doi": null,
|
||||
"input": {
|
||||
"title": "Der Staat wird’s schon richten, der Staat macht’s schon gut?",
|
||||
"abstract": null,
|
||||
"venue": "RePEc: Research Papers in Economics",
|
||||
"work_type": "preprint",
|
||||
"topics": [
|
||||
"Economic and Social Issues",
|
||||
"Sociology and Political Science",
|
||||
"Social Sciences",
|
||||
"Public Administration and Political Analysis",
|
||||
"Political Science and International Relations",
|
||||
"Sociology and Education Studies",
|
||||
"Philosophy",
|
||||
"Humanities"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2009,
|
||||
"language": "de"
|
||||
},
|
||||
"debug": {
|
||||
"publication_date": "2009-01-01",
|
||||
"has_abstract": false,
|
||||
"excluded_type": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5035144962",
|
||||
"display_name": "Christine Arentz"
|
||||
},
|
||||
"work_id": "https://openalex.org/W2267859866",
|
||||
"doi": null,
|
||||
"input": {
|
||||
"title": "Ist die Krankenversicherung der richtige Ort für Familienpolitik",
|
||||
"abstract": "Health Insurance",
|
||||
"venue": "RePEc: Research Papers in Economics",
|
||||
"work_type": "preprint",
|
||||
"topics": [
|
||||
"Social and Demographic Issues in Germany",
|
||||
"General Health Professions",
|
||||
"Health Professions",
|
||||
"Social Policies and Healthcare Reform",
|
||||
"Health and Medical Studies",
|
||||
"Die (integrated circuit)",
|
||||
"Engineering",
|
||||
"Mechanical engineering"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2009,
|
||||
"language": "de"
|
||||
},
|
||||
"debug": {
|
||||
"publication_date": "2009-01-01",
|
||||
"has_abstract": true,
|
||||
"excluded_type": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5035144962",
|
||||
"display_name": "Christine Arentz"
|
||||
},
|
||||
"work_id": "https://openalex.org/W2241055839",
|
||||
"doi": null,
|
||||
"input": {
|
||||
"title": "Reflexionen zu sechzig Jahren Soziale Marktwirtschaft",
|
||||
"abstract": "Social Market Economy",
|
||||
"venue": "RePEc: Research Papers in Economics",
|
||||
"work_type": "preprint",
|
||||
"topics": [
|
||||
"Economic and Social Issues",
|
||||
"Sociology and Political Science",
|
||||
"Social Sciences",
|
||||
"Political science",
|
||||
"Economics"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2008,
|
||||
"language": "de"
|
||||
},
|
||||
"debug": {
|
||||
"publication_date": "2008-01-01",
|
||||
"has_abstract": true,
|
||||
"excluded_type": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5035144962",
|
||||
"display_name": "Christine Arentz"
|
||||
},
|
||||
"work_id": "https://openalex.org/W3142662954",
|
||||
"doi": null,
|
||||
"input": {
|
||||
"title": "\"monitor\" und die Altersrente - Enthüllungsjournalismus ohne Enthüllung?",
|
||||
"abstract": null,
|
||||
"venue": "IWP Ordnungspolitischer Kommentar",
|
||||
"work_type": "article",
|
||||
"topics": [
|
||||
"Social Policies and Healthcare Reform",
|
||||
"General Health Professions",
|
||||
"Health Professions",
|
||||
"Social and Demographic Issues in Germany",
|
||||
"Medicine"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2008,
|
||||
"language": "de"
|
||||
},
|
||||
"debug": {
|
||||
"publication_date": "2008-01-01",
|
||||
"has_abstract": false,
|
||||
"excluded_type": false
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,136 +0,0 @@
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5075663980",
|
||||
"display_name": "Ursula Neumann"
|
||||
},
|
||||
"works": [
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5075663980",
|
||||
"display_name": "Ursula Neumann"
|
||||
},
|
||||
"work_id": "https://openalex.org/W7125710157",
|
||||
"doi": "https://doi.org/10.1055/s-0045-1814333",
|
||||
"input": {
|
||||
"title": "GALAD Score predicts Recurrence Risk and Mortality after Curative Resection of Hepatocellular Carcinoma",
|
||||
"abstract": null,
|
||||
"venue": "Zeitschrift für Gastroenterologie",
|
||||
"work_type": "article",
|
||||
"topics": [
|
||||
"Liver Disease Diagnosis and Treatment",
|
||||
"Epidemiology",
|
||||
"Medicine",
|
||||
"Peptidase Inhibition and Analysis",
|
||||
"Oncology",
|
||||
"Hepatocellular Carcinoma Treatment and Prognosis",
|
||||
"Hepatology",
|
||||
"Hepatocellular carcinoma"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2026,
|
||||
"language": null
|
||||
},
|
||||
"debug": {
|
||||
"publication_date": "2026-01-01",
|
||||
"has_abstract": false,
|
||||
"excluded_type": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5075663980",
|
||||
"display_name": "Ursula Neumann"
|
||||
},
|
||||
"work_id": "https://openalex.org/W4409704961",
|
||||
"doi": "https://doi.org/10.1007/978-3-658-46233-8_10",
|
||||
"input": {
|
||||
"title": "Multiprofessionelle Kooperation und Schulabsentismus: Theoriezugänge und Befunde aus Sicht der Kinder- und Jugendpsychiatrie",
|
||||
"abstract": null,
|
||||
"venue": "Absentismus und Dropout",
|
||||
"work_type": "book-chapter",
|
||||
"topics": [
|
||||
"Youth Substance Use and School Attendance",
|
||||
"Education",
|
||||
"Social Sciences",
|
||||
"Child and Adolescent Psychosocial and Emotional Development",
|
||||
"Clinical Psychology",
|
||||
"Psychology",
|
||||
"Early Childhood Education and Development",
|
||||
"Political science"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2025,
|
||||
"language": "de"
|
||||
},
|
||||
"debug": {
|
||||
"publication_date": "2025-01-01",
|
||||
"has_abstract": false,
|
||||
"excluded_type": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5075663980",
|
||||
"display_name": "Ursula Neumann"
|
||||
},
|
||||
"work_id": "https://openalex.org/W4283385417",
|
||||
"doi": "https://doi.org/10.1024/1422-4917/a000884",
|
||||
"input": {
|
||||
"title": "Verlauf von Schulabsentismus 1.5 bis 3 Jahre nach Erstvorstellung: Prädiktoren, psychosoziales Funktionsniveau und Inanspruchnahme von Hilfen",
|
||||
"abstract": "Course of School Absenteeism 1.5-3 Years After Initial Evaluation: Symptoms, Psychosocial Functioning, and Help-Seeking Behavior <b>Abstract.</b> <i>Objective:</i> To explore the course of patients with school absenteeism 1.5-3 years after their initial evaluation, including symptoms, school attendance, psychosocial functioning, and help-seeking behavior. <i>Method:</i> Of the 237 patients from specialized psychiatric units for youths displaying school absenteeism, we successfully contacted 108 of them 1.5-3 years after initial admission. We conducted a telephone interview with their parents (SDQ, school situation, help-seeking behavior). Among others, we analyzed the extent of school absenteeism, the scales of the Inventory of School Attendance Problems (ISAP; Knollmann et al., 2019), and the quality of school absenteeism (school refusal vs. truancy vs. mixed group) at admission as possible predictors. <i>Results:</i> The patients had received an extensive amount of youth-welfare measures and inpatient, daycare, and outpatient therapy. 46.3 % had elevated values in the SDQ total score at follow-up, mostly because of emotional problems or problems with peers. Psychosocial functioning, including school attendance, was described as poor for only about 30 %. School attendance problems were significantly predicted by having a conduct disorder and elevated scores on the ISAP-scales Aggression, Teacher Problems, and Peer Problems, though the effect sizes were weak. <i>Conclusions:</i> Externalizing symptoms and associated psychosocial problems seem to be predictive of a negative course of school absenteeism. Implications for prospective longitudinal studies are discussed.",
|
||||
"venue": "Zeitschrift für Kinder- und Jugendpsychiatrie und Psychotherapie",
|
||||
"work_type": "article",
|
||||
"topics": [
|
||||
"Youth Substance Use and School Attendance",
|
||||
"Education",
|
||||
"Social Sciences",
|
||||
"Child and Adolescent Psychosocial and Emotional Development",
|
||||
"Clinical Psychology",
|
||||
"Psychology",
|
||||
"Educational and Psychological Assessments",
|
||||
"Developmental and Educational Psychology"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2022,
|
||||
"language": "de"
|
||||
},
|
||||
"debug": {
|
||||
"publication_date": "2022-06-24",
|
||||
"has_abstract": true,
|
||||
"excluded_type": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5075663980",
|
||||
"display_name": "Ursula Neumann"
|
||||
},
|
||||
"work_id": "https://openalex.org/W4283385776",
|
||||
"doi": "https://doi.org/10.1024/1422-4917/a000882",
|
||||
"input": {
|
||||
"title": "Stationäre Schematherapie bei Schulvermeidung – ein Fallbeispiel",
|
||||
"abstract": "Inpatient Schema Therapy for School Avoidance - A Case Study <b>Abstract.</b> After a short overview of the basic concepts and methods of schema therapy, we report a case study on the inpatient treatment of a 16-year-old youth with depression and chronic school avoidance. The scores on the Schema inventories and Depression questionnaires are compared before vs. after the treatment, and we then discuss the opportunities and limitations of schema therapy with school-avoiding youths.",
|
||||
"venue": "Zeitschrift für Kinder- und Jugendpsychiatrie und Psychotherapie",
|
||||
"work_type": "article",
|
||||
"topics": [
|
||||
"Youth Substance Use and School Attendance",
|
||||
"Education",
|
||||
"Social Sciences",
|
||||
"Child and Adolescent Psychosocial and Emotional Development",
|
||||
"Clinical Psychology",
|
||||
"Psychology",
|
||||
"Educational and Psychological Assessments",
|
||||
"Developmental and Educational Psychology"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2022,
|
||||
"language": "de"
|
||||
},
|
||||
"debug": {
|
||||
"publication_date": "2022-06-24",
|
||||
"has_abstract": true,
|
||||
"excluded_type": false
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,198 +0,0 @@
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5093075883",
|
||||
"display_name": "Arman Arzani"
|
||||
},
|
||||
"works": [
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5093075883",
|
||||
"display_name": "Arman Arzani"
|
||||
},
|
||||
"work_id": "https://openalex.org/W4415655215",
|
||||
"doi": "https://doi.org/10.5220/0013658600004000",
|
||||
"input": {
|
||||
"title": "A Hybrid Approach for Mining the Organizational Structure from University Websites",
|
||||
"abstract": null,
|
||||
"venue": null,
|
||||
"work_type": "article",
|
||||
"topics": [
|
||||
"Data Mining Algorithms and Applications",
|
||||
"Information Systems",
|
||||
"Computer Science",
|
||||
"Advanced Text Analysis Techniques",
|
||||
"Artificial Intelligence",
|
||||
"Web visibility and informetrics",
|
||||
"Organizational structure",
|
||||
"Knowledge management"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2025,
|
||||
"language": null
|
||||
},
|
||||
"debug": {
|
||||
"publication_date": "2025-01-01",
|
||||
"has_abstract": false,
|
||||
"excluded_type": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5093075883",
|
||||
"display_name": "Arman Arzani"
|
||||
},
|
||||
"work_id": "https://openalex.org/W4402284842",
|
||||
"doi": "https://doi.org/10.2139/ssrn.4947351",
|
||||
"input": {
|
||||
"title": "Ai-Based Pattern Recognition in Limited, Unstructured Information: Improving Joint Value Creation in Mobility as a Service",
|
||||
"abstract": null,
|
||||
"venue": "SSRN Electronic Journal",
|
||||
"work_type": "preprint",
|
||||
"topics": [
|
||||
"Big Data and Business Intelligence",
|
||||
"Management Information Systems",
|
||||
"Business, Management and Accounting",
|
||||
"Customer churn and segmentation",
|
||||
"Marketing",
|
||||
"Semantic Web and Ontologies",
|
||||
"Artificial Intelligence",
|
||||
"Computer Science"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2024,
|
||||
"language": "en"
|
||||
},
|
||||
"debug": {
|
||||
"publication_date": "2024-01-01",
|
||||
"has_abstract": false,
|
||||
"excluded_type": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5093075883",
|
||||
"display_name": "Arman Arzani"
|
||||
},
|
||||
"work_id": "https://openalex.org/W4403369135",
|
||||
"doi": "https://doi.org/10.1007/s41060-024-00663-1",
|
||||
"input": {
|
||||
"title": "Discovering potential founders within academic institutions",
|
||||
"abstract": "Abstract Technology transfer is central to the development of an iconic entrepreneurial university. To foster knowledge transfer, many universities undergo a scouting process by their innovation coaches. The goal is to find staff members and students, who have the knowledge, expertise, and the potential to found startups by transforming their research results into a product. Since there is no systematic approach to measure the innovation potential of university members based on their academic activities, the scouting process is typically subjective and relies heavily on the experience of the innovation coaches. In this paper, we study the discovery of potential founders to support the scouting process using a data-driven approach. We create a novel data set by integrating the founder profiles with the academic activities from 8 universities across 5 countries. We explain the process of data integration as well as feature engineering. By applying machine learning methods, we investigate the classification accuracy of founders based on their academic background. Our analysis shows that using a random forest (RF), it is possible to differentiate founders and non-founders with an average accuracy of 79%. This accuracy remains mostly stable when applying an RF trained on one university to another, suggesting the existence of a generic founder profile. The detailed analysis indicates a high significance of the career path as well as patent- and grant-related features among others. Furthermore, we show that using a RF, it is possible to exploit these features to predict the future founding probability up to 3 years in advance with an accuracy of 80%. Finally, by analyzing the academic disciplines of founders we show that the patent documents have more influence on the startup’s core orientation than the publications.",
|
||||
"venue": "International Journal of Data Science and Analytics",
|
||||
"work_type": "article",
|
||||
"topics": [
|
||||
"Entrepreneurship Studies and Influences",
|
||||
"Management of Technology and Innovation",
|
||||
"Business, Management and Accounting",
|
||||
"Genetics, Bioinformatics, and Biomedical Research",
|
||||
"Molecular Biology",
|
||||
"Biochemistry, Genetics and Molecular Biology",
|
||||
"Biomedical and Engineering Education",
|
||||
"Biomedical Engineering"
|
||||
],
|
||||
"funders": [
|
||||
"Bundesministerium für Wirtschaft und Energie",
|
||||
"Universität Duisburg-Essen"
|
||||
],
|
||||
"year": 2024,
|
||||
"language": "en"
|
||||
},
|
||||
"debug": {
|
||||
"publication_date": "2024-10-13",
|
||||
"has_abstract": true,
|
||||
"excluded_type": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5093075883",
|
||||
"display_name": "Arman Arzani"
|
||||
},
|
||||
"work_id": "https://openalex.org/W4387698137",
|
||||
"doi": "https://doi.org/10.1145/3603765.3603774",
|
||||
"input": {
|
||||
"title": "Exploiting Topic Modelling for the Identification of Untapped Scientific Collaborations",
|
||||
"abstract": "Finding potential collaborators has become a challenge due to the growing number of scientists in organizations such as universities, research institutes, or companies. Collaboration Recommendation Systems (CRSs) have been developed to help researchers identify possible collaboration partners, but they often rely on citation graphs or paper abstracts which may not be readily available in organizational databases or online sources. However, scientific publication titles provide consistent bibliometric data that can provide insights into research areas. TOMOSCO is a topic modelling framework that uses transformer-based methods to extract research area information from small amounts of text, such as publication titles or brief project descriptions. TOMOSCO can classify, cluster, and match research topics across different disciplines, uncovering relationships among scientists and suggesting potential interdisciplinary collaborations. In experiments, TOMOSCO was able to identify existing collaborations with over 90% accuracy based solely on publication titles and propose new collaborations based on previously unseen publications and project descriptions.",
|
||||
"venue": null,
|
||||
"work_type": "article",
|
||||
"topics": [
|
||||
"Topic Modeling",
|
||||
"Artificial Intelligence",
|
||||
"Computer Science",
|
||||
"Complex Network Analysis Techniques",
|
||||
"Statistical and Nonlinear Physics",
|
||||
"Physics and Astronomy",
|
||||
"Computational and Text Analysis Methods",
|
||||
"General Social Sciences"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2023,
|
||||
"language": "en"
|
||||
},
|
||||
"debug": {
|
||||
"publication_date": "2023-05-10",
|
||||
"has_abstract": true,
|
||||
"excluded_type": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5093075883",
|
||||
"display_name": "Arman Arzani"
|
||||
},
|
||||
"work_id": "https://openalex.org/W4388860852",
|
||||
"doi": "https://doi.org/10.5220/0012156200003598",
|
||||
"input": {
|
||||
"title": "Discovering Potential Founders Based on Academic Background",
|
||||
"abstract": null,
|
||||
"venue": null,
|
||||
"work_type": "article",
|
||||
"topics": [
|
||||
"Education and Critical Thinking Development",
|
||||
"Education",
|
||||
"Social Sciences",
|
||||
"Computer science",
|
||||
"Data science"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2023,
|
||||
"language": "en"
|
||||
},
|
||||
"debug": {
|
||||
"publication_date": "2023-01-01",
|
||||
"has_abstract": false,
|
||||
"excluded_type": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5093075883",
|
||||
"display_name": "Arman Arzani"
|
||||
},
|
||||
"work_id": "https://openalex.org/W4388877173",
|
||||
"doi": "https://doi.org/10.5220/0012263100003598",
|
||||
"input": {
|
||||
"title": "Challenges in Implementing a University-Based Innovation Search Engine",
|
||||
"abstract": null,
|
||||
"venue": "Universitätsbibliographie, Universität Duisburg-Essen",
|
||||
"work_type": "article",
|
||||
"topics": [
|
||||
"Big Data and Business Intelligence",
|
||||
"Management Information Systems",
|
||||
"Business, Management and Accounting",
|
||||
"Computer science",
|
||||
"Search engine",
|
||||
"World Wide Web"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2023,
|
||||
"language": "en"
|
||||
},
|
||||
"debug": {
|
||||
"publication_date": "2023-01-01",
|
||||
"has_abstract": false,
|
||||
"excluded_type": false
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
-99
@@ -1,99 +0,0 @@
|
||||
{
|
||||
"config": {
|
||||
"selected_persons_file": "selected_persons.json",
|
||||
"classification_data_dir": "classification_data",
|
||||
"works_index": "openalex-works*",
|
||||
"work_year_gte": 1950,
|
||||
"excluded_types": ["editorial", "erratum", "paratext", "retraction"]
|
||||
},
|
||||
"persons": [
|
||||
{
|
||||
"id": "https://openalex.org/A5089242868",
|
||||
"display_name": "Lucas Davi",
|
||||
"output_file": "classification_data/A5089242868.json",
|
||||
"elasticsearch_hits_total": 136,
|
||||
"duplicate_hits_ignored": 1,
|
||||
"works_total": 135,
|
||||
"works_with_abstract": 95,
|
||||
"works_without_abstract": 40,
|
||||
"works_excluded_type": 0
|
||||
},
|
||||
{
|
||||
"id": "https://openalex.org/A5093075883",
|
||||
"display_name": "Arman Arzani",
|
||||
"output_file": "classification_data/A5093075883.json",
|
||||
"elasticsearch_hits_total": 6,
|
||||
"duplicate_hits_ignored": 0,
|
||||
"works_total": 6,
|
||||
"works_with_abstract": 2,
|
||||
"works_without_abstract": 4,
|
||||
"works_excluded_type": 0
|
||||
},
|
||||
{
|
||||
"id": "https://openalex.org/A5075352419",
|
||||
"display_name": "Markus Winterer",
|
||||
"output_file": "classification_data/A5075352419.json",
|
||||
"elasticsearch_hits_total": 151,
|
||||
"duplicate_hits_ignored": 1,
|
||||
"works_total": 150,
|
||||
"works_with_abstract": 84,
|
||||
"works_without_abstract": 66,
|
||||
"works_excluded_type": 1
|
||||
},
|
||||
{
|
||||
"id": "https://openalex.org/A5048213587",
|
||||
"display_name": "Frederik Ahlemann",
|
||||
"output_file": "classification_data/A5048213587.json",
|
||||
"elasticsearch_hits_total": 172,
|
||||
"duplicate_hits_ignored": 1,
|
||||
"works_total": 171,
|
||||
"works_with_abstract": 74,
|
||||
"works_without_abstract": 97,
|
||||
"works_excluded_type": 1
|
||||
},
|
||||
{
|
||||
"id": "https://openalex.org/A5088184531",
|
||||
"display_name": "Alf Kimms",
|
||||
"output_file": "classification_data/A5088184531.json",
|
||||
"elasticsearch_hits_total": 86,
|
||||
"duplicate_hits_ignored": 0,
|
||||
"works_total": 86,
|
||||
"works_with_abstract": 42,
|
||||
"works_without_abstract": 44,
|
||||
"works_excluded_type": 0
|
||||
},
|
||||
{
|
||||
"id": "https://openalex.org/A5075663980",
|
||||
"display_name": "Ursula Neumann",
|
||||
"output_file": "classification_data/A5075663980.json",
|
||||
"elasticsearch_hits_total": 4,
|
||||
"duplicate_hits_ignored": 0,
|
||||
"works_total": 4,
|
||||
"works_with_abstract": 2,
|
||||
"works_without_abstract": 2,
|
||||
"works_excluded_type": 0
|
||||
},
|
||||
{
|
||||
"id": "https://openalex.org/A5035144962",
|
||||
"display_name": "Christine Arentz",
|
||||
"output_file": "classification_data/A5035144962.json",
|
||||
"elasticsearch_hits_total": 30,
|
||||
"duplicate_hits_ignored": 0,
|
||||
"works_total": 30,
|
||||
"works_with_abstract": 20,
|
||||
"works_without_abstract": 10,
|
||||
"works_excluded_type": 0
|
||||
},
|
||||
{
|
||||
"id": "https://openalex.org/A5058038339",
|
||||
"display_name": "Pascal Dreher",
|
||||
"output_file": "classification_data/A5058038339.json",
|
||||
"elasticsearch_hits_total": 30,
|
||||
"duplicate_hits_ignored": 0,
|
||||
"works_total": 30,
|
||||
"works_with_abstract": 28,
|
||||
"works_without_abstract": 2,
|
||||
"works_excluded_type": 0
|
||||
}
|
||||
]
|
||||
}
|
||||
Binary file not shown.
-146
@@ -1,146 +0,0 @@
|
||||
{
|
||||
"counts": {
|
||||
"persons_total": 8,
|
||||
"works_total": 612,
|
||||
"valid_outputs": 607,
|
||||
"validation_errors": 5,
|
||||
"api_errors": 0
|
||||
},
|
||||
"category_distribution": {
|
||||
"basic_research": 250,
|
||||
"applied_research": 219,
|
||||
"experimental_development": 123,
|
||||
"non_research": 20
|
||||
},
|
||||
"category_share": {
|
||||
"basic_research": 0.4085,
|
||||
"applied_research": 0.3578,
|
||||
"experimental_development": 0.201,
|
||||
"non_research": 0.0327
|
||||
},
|
||||
"confidence_distribution": {
|
||||
"high": 345,
|
||||
"medium": 262,
|
||||
"low": 5
|
||||
},
|
||||
"abstract_coverage": {
|
||||
"works_with_abstract": 347,
|
||||
"works_without_abstract": 265,
|
||||
"missing_abstract_share": 0.433
|
||||
},
|
||||
"score_summary": {
|
||||
"scored_outputs": 592,
|
||||
"mean_applied_orientation_score": 51.9,
|
||||
"median_applied_orientation_score": 60.0,
|
||||
"min_applied_orientation_score": 10,
|
||||
"max_applied_orientation_score": 92
|
||||
},
|
||||
"quality_checks": {
|
||||
"high_confidence_without_abstract": 8,
|
||||
"title_only_high_confidence": 1,
|
||||
"non_research_with_score": 0,
|
||||
"score_range_mismatches": 5
|
||||
},
|
||||
"usage": {
|
||||
"prompt_tokens": 1564344,
|
||||
"uncached_prompt_tokens": 1360056,
|
||||
"completion_tokens": 551417,
|
||||
"real_total_usage": 1911473
|
||||
},
|
||||
"average_usage_per_work": {
|
||||
"prompt_tokens": 2556.12,
|
||||
"uncached_prompt_tokens": 2222.31,
|
||||
"completion_tokens": 901.01,
|
||||
"real_total_usage": 3123.32
|
||||
},
|
||||
"timing": {
|
||||
"average_duration_seconds_per_work": 15.28
|
||||
},
|
||||
"problem_cases": [
|
||||
{
|
||||
"person_name": "Christine Arentz",
|
||||
"person_id": "https://openalex.org/A5035144962",
|
||||
"work_id": "https://openalex.org/W3213629311",
|
||||
"doi": null,
|
||||
"title": "Ihr Kinderlein kommet? Regelungen für den Schul- und Kitabesuch in der Pandemie im Bundesländervergleich",
|
||||
"year": 2020,
|
||||
"work_type": "article",
|
||||
"has_abstract": true,
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 75,
|
||||
"confidence": "high",
|
||||
"classification_reason": "The abstract analyzes the conflict between health and educational goals to inform policy regarding pandemic regulations and resource allocation.",
|
||||
"validation_errors": ["applied_research_score_outside_expected_range"],
|
||||
"api_error": false,
|
||||
"api_error_message": null
|
||||
},
|
||||
{
|
||||
"person_name": "Christine Arentz",
|
||||
"person_id": "https://openalex.org/A5035144962",
|
||||
"work_id": "https://openalex.org/W2268727219",
|
||||
"doi": null,
|
||||
"title": "Die Schweiz als Vorbild? Zur Zähmung \"gieriger\" Manager",
|
||||
"year": 2013,
|
||||
"work_type": "article",
|
||||
"has_abstract": false,
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 15,
|
||||
"confidence": "medium",
|
||||
"classification_reason": "The title suggests a conceptual analysis of organizational behavior, fitting the basic research definition in social sciences.",
|
||||
"validation_errors": ["basic_research_score_outside_expected_range"],
|
||||
"api_error": false,
|
||||
"api_error_message": null
|
||||
},
|
||||
{
|
||||
"person_name": "Markus Winterer",
|
||||
"person_id": "https://openalex.org/A5075352419",
|
||||
"work_id": "https://openalex.org/W1970644787",
|
||||
"doi": "https://doi.org/10.1007/s11051-013-1664-8",
|
||||
"title": "Blocked-micropores, surface functionalized, bio-compatible and silica-coated iron oxide nanocomposites as advanced MRI contrast agent",
|
||||
"year": 2013,
|
||||
"work_type": "article",
|
||||
"has_abstract": false,
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 75,
|
||||
"confidence": "medium",
|
||||
"classification_reason": "The title describes a specific material (nanocomposites) designed for a practical medical application (MRI contrast agent).",
|
||||
"validation_errors": ["applied_research_score_outside_expected_range"],
|
||||
"api_error": false,
|
||||
"api_error_message": null
|
||||
},
|
||||
{
|
||||
"person_name": "Arman Arzani",
|
||||
"person_id": "https://openalex.org/A5093075883",
|
||||
"work_id": "https://openalex.org/W4403369135",
|
||||
"doi": "https://doi.org/10.1007/s41060-024-00663-1",
|
||||
"title": "Discovering potential founders within academic institutions",
|
||||
"year": 2024,
|
||||
"work_type": "article",
|
||||
"has_abstract": true,
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 75,
|
||||
"confidence": "high",
|
||||
"classification_reason": "The abstract defines a specific practical aim: supporting the university scouting process by developing a data-driven prediction model.",
|
||||
"validation_errors": ["applied_research_score_outside_expected_range"],
|
||||
"api_error": false,
|
||||
"api_error_message": null
|
||||
},
|
||||
{
|
||||
"person_name": "Arman Arzani",
|
||||
"person_id": "https://openalex.org/A5093075883",
|
||||
"work_id": "https://openalex.org/W4387698137",
|
||||
"doi": "https://doi.org/10.1145/3603765.3603774",
|
||||
"title": "Exploiting Topic Modelling for the Identification of Untapped Scientific Collaborations",
|
||||
"year": 2023,
|
||||
"work_type": "article",
|
||||
"has_abstract": true,
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 75,
|
||||
"confidence": "high",
|
||||
"classification_reason": "The abstract describes developing and testing TOMOSCO, a framework aimed at solving the specific practical problem of identifying untapped scientific collaborations.",
|
||||
"validation_errors": ["applied_research_score_outside_expected_range"],
|
||||
"api_error": false,
|
||||
"api_error_message": null
|
||||
}
|
||||
]
|
||||
}
|
||||
-626
@@ -1,626 +0,0 @@
|
||||
[
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5035144962",
|
||||
"display_name": "Christine Arentz"
|
||||
},
|
||||
"source_file": "llm_results/A5035144962_results.json",
|
||||
"summary": {
|
||||
"counts": {
|
||||
"works_total": 30,
|
||||
"valid_outputs": 28,
|
||||
"validation_errors": 2,
|
||||
"api_errors": 0
|
||||
},
|
||||
"category_distribution": {
|
||||
"basic_research": 9,
|
||||
"applied_research": 19,
|
||||
"experimental_development": 0,
|
||||
"non_research": 2
|
||||
},
|
||||
"category_share": {
|
||||
"basic_research": 0.3,
|
||||
"applied_research": 0.6333,
|
||||
"experimental_development": 0.0,
|
||||
"non_research": 0.0667
|
||||
},
|
||||
"confidence_distribution": {
|
||||
"high": 15,
|
||||
"medium": 15,
|
||||
"low": 0
|
||||
},
|
||||
"abstract_coverage": {
|
||||
"works_with_abstract": 20,
|
||||
"works_without_abstract": 10,
|
||||
"missing_abstract_share": 0.3333
|
||||
},
|
||||
"score_summary": {
|
||||
"scored_outputs": 28,
|
||||
"mean_applied_orientation_score": 52.68,
|
||||
"median_applied_orientation_score": 65.0,
|
||||
"min_applied_orientation_score": 10,
|
||||
"max_applied_orientation_score": 75
|
||||
},
|
||||
"quality_checks": {
|
||||
"high_confidence_without_abstract": 1,
|
||||
"title_only_high_confidence": 0,
|
||||
"non_research_with_score": 0,
|
||||
"score_range_mismatches": 2
|
||||
},
|
||||
"usage": {
|
||||
"prompt_tokens": 96289,
|
||||
"uncached_prompt_tokens": 10369,
|
||||
"completion_tokens": 27789,
|
||||
"real_total_usage": 38158
|
||||
},
|
||||
"average_usage_per_work": {
|
||||
"prompt_tokens": 3209.63,
|
||||
"uncached_prompt_tokens": 345.63,
|
||||
"completion_tokens": 926.3,
|
||||
"real_total_usage": 1271.93
|
||||
},
|
||||
"timing": {
|
||||
"average_duration_seconds_per_work": 16.43
|
||||
},
|
||||
"problem_cases": [
|
||||
{
|
||||
"person_name": "Christine Arentz",
|
||||
"person_id": "https://openalex.org/A5035144962",
|
||||
"work_id": "https://openalex.org/W3213629311",
|
||||
"doi": null,
|
||||
"title": "Ihr Kinderlein kommet? Regelungen für den Schul- und Kitabesuch in der Pandemie im Bundesländervergleich",
|
||||
"year": 2020,
|
||||
"work_type": "article",
|
||||
"has_abstract": true,
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 75,
|
||||
"confidence": "high",
|
||||
"classification_reason": "The abstract analyzes the conflict between health and educational goals to inform policy regarding pandemic regulations and resource allocation.",
|
||||
"validation_errors": [
|
||||
"applied_research_score_outside_expected_range"
|
||||
],
|
||||
"api_error": false,
|
||||
"api_error_message": null
|
||||
},
|
||||
{
|
||||
"person_name": "Christine Arentz",
|
||||
"person_id": "https://openalex.org/A5035144962",
|
||||
"work_id": "https://openalex.org/W2268727219",
|
||||
"doi": null,
|
||||
"title": "Die Schweiz als Vorbild? Zur Zähmung \"gieriger\" Manager",
|
||||
"year": 2013,
|
||||
"work_type": "article",
|
||||
"has_abstract": false,
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 15,
|
||||
"confidence": "medium",
|
||||
"classification_reason": "The title suggests a conceptual analysis of organizational behavior, fitting the basic research definition in social sciences.",
|
||||
"validation_errors": ["basic_research_score_outside_expected_range"],
|
||||
"api_error": false,
|
||||
"api_error_message": null
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5048213587",
|
||||
"display_name": "Frederik Ahlemann"
|
||||
},
|
||||
"source_file": "llm_results/A5048213587_results.json",
|
||||
"summary": {
|
||||
"counts": {
|
||||
"works_total": 171,
|
||||
"valid_outputs": 171,
|
||||
"validation_errors": 0,
|
||||
"api_errors": 0
|
||||
},
|
||||
"category_distribution": {
|
||||
"basic_research": 100,
|
||||
"applied_research": 58,
|
||||
"experimental_development": 6,
|
||||
"non_research": 7
|
||||
},
|
||||
"category_share": {
|
||||
"basic_research": 0.5848,
|
||||
"applied_research": 0.3392,
|
||||
"experimental_development": 0.0351,
|
||||
"non_research": 0.0409
|
||||
},
|
||||
"confidence_distribution": {
|
||||
"high": 76,
|
||||
"medium": 94,
|
||||
"low": 1
|
||||
},
|
||||
"abstract_coverage": {
|
||||
"works_with_abstract": 74,
|
||||
"works_without_abstract": 97,
|
||||
"missing_abstract_share": 0.5673
|
||||
},
|
||||
"score_summary": {
|
||||
"scored_outputs": 164,
|
||||
"mean_applied_orientation_score": 39.24,
|
||||
"median_applied_orientation_score": 35.0,
|
||||
"min_applied_orientation_score": 15,
|
||||
"max_applied_orientation_score": 85
|
||||
},
|
||||
"quality_checks": {
|
||||
"high_confidence_without_abstract": 4,
|
||||
"title_only_high_confidence": 1,
|
||||
"non_research_with_score": 0,
|
||||
"score_range_mismatches": 0
|
||||
},
|
||||
"usage": {
|
||||
"prompt_tokens": 411263,
|
||||
"uncached_prompt_tokens": 411263,
|
||||
"completion_tokens": 154527,
|
||||
"real_total_usage": 565790
|
||||
},
|
||||
"average_usage_per_work": {
|
||||
"prompt_tokens": 2405.05,
|
||||
"uncached_prompt_tokens": 2405.05,
|
||||
"completion_tokens": 903.67,
|
||||
"real_total_usage": 3308.71
|
||||
},
|
||||
"timing": {
|
||||
"average_duration_seconds_per_work": 15.21
|
||||
},
|
||||
"problem_cases": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5058038339",
|
||||
"display_name": "Pascal Dreher"
|
||||
},
|
||||
"source_file": "llm_results/A5058038339_results.json",
|
||||
"summary": {
|
||||
"counts": {
|
||||
"works_total": 30,
|
||||
"valid_outputs": 30,
|
||||
"validation_errors": 0,
|
||||
"api_errors": 0
|
||||
},
|
||||
"category_distribution": {
|
||||
"basic_research": 22,
|
||||
"applied_research": 2,
|
||||
"experimental_development": 6,
|
||||
"non_research": 0
|
||||
},
|
||||
"category_share": {
|
||||
"basic_research": 0.7333,
|
||||
"applied_research": 0.0667,
|
||||
"experimental_development": 0.2,
|
||||
"non_research": 0.0
|
||||
},
|
||||
"confidence_distribution": {
|
||||
"high": 29,
|
||||
"medium": 1,
|
||||
"low": 0
|
||||
},
|
||||
"abstract_coverage": {
|
||||
"works_with_abstract": 28,
|
||||
"works_without_abstract": 2,
|
||||
"missing_abstract_share": 0.0667
|
||||
},
|
||||
"score_summary": {
|
||||
"scored_outputs": 30,
|
||||
"mean_applied_orientation_score": 42.83,
|
||||
"median_applied_orientation_score": 35.0,
|
||||
"min_applied_orientation_score": 15,
|
||||
"max_applied_orientation_score": 90
|
||||
},
|
||||
"quality_checks": {
|
||||
"high_confidence_without_abstract": 1,
|
||||
"title_only_high_confidence": 0,
|
||||
"non_research_with_score": 0,
|
||||
"score_range_mismatches": 0
|
||||
},
|
||||
"usage": {
|
||||
"prompt_tokens": 98341,
|
||||
"uncached_prompt_tokens": 10245,
|
||||
"completion_tokens": 26388,
|
||||
"real_total_usage": 36633
|
||||
},
|
||||
"average_usage_per_work": {
|
||||
"prompt_tokens": 3278.03,
|
||||
"uncached_prompt_tokens": 341.5,
|
||||
"completion_tokens": 879.6,
|
||||
"real_total_usage": 1221.1
|
||||
},
|
||||
"timing": {
|
||||
"average_duration_seconds_per_work": 15.76
|
||||
},
|
||||
"problem_cases": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5075352419",
|
||||
"display_name": "Markus Winterer"
|
||||
},
|
||||
"source_file": "llm_results/A5075352419_results.json",
|
||||
"summary": {
|
||||
"counts": {
|
||||
"works_total": 150,
|
||||
"valid_outputs": 149,
|
||||
"validation_errors": 1,
|
||||
"api_errors": 0
|
||||
},
|
||||
"category_distribution": {
|
||||
"basic_research": 60,
|
||||
"applied_research": 36,
|
||||
"experimental_development": 49,
|
||||
"non_research": 5
|
||||
},
|
||||
"category_share": {
|
||||
"basic_research": 0.4,
|
||||
"applied_research": 0.24,
|
||||
"experimental_development": 0.3267,
|
||||
"non_research": 0.0333
|
||||
},
|
||||
"confidence_distribution": {
|
||||
"high": 85,
|
||||
"medium": 65,
|
||||
"low": 0
|
||||
},
|
||||
"abstract_coverage": {
|
||||
"works_with_abstract": 84,
|
||||
"works_without_abstract": 66,
|
||||
"missing_abstract_share": 0.44
|
||||
},
|
||||
"score_summary": {
|
||||
"scored_outputs": 145,
|
||||
"mean_applied_orientation_score": 55.46,
|
||||
"median_applied_orientation_score": 65,
|
||||
"min_applied_orientation_score": 15,
|
||||
"max_applied_orientation_score": 92
|
||||
},
|
||||
"quality_checks": {
|
||||
"high_confidence_without_abstract": 2,
|
||||
"title_only_high_confidence": 0,
|
||||
"non_research_with_score": 0,
|
||||
"score_range_mismatches": 1
|
||||
},
|
||||
"usage": {
|
||||
"prompt_tokens": 368720,
|
||||
"uncached_prompt_tokens": 368720,
|
||||
"completion_tokens": 132353,
|
||||
"real_total_usage": 501073
|
||||
},
|
||||
"average_usage_per_work": {
|
||||
"prompt_tokens": 2458.13,
|
||||
"uncached_prompt_tokens": 2458.13,
|
||||
"completion_tokens": 882.35,
|
||||
"real_total_usage": 3340.49
|
||||
},
|
||||
"timing": {
|
||||
"average_duration_seconds_per_work": 14.84
|
||||
},
|
||||
"problem_cases": [
|
||||
{
|
||||
"person_name": "Markus Winterer",
|
||||
"person_id": "https://openalex.org/A5075352419",
|
||||
"work_id": "https://openalex.org/W1970644787",
|
||||
"doi": "https://doi.org/10.1007/s11051-013-1664-8",
|
||||
"title": "Blocked-micropores, surface functionalized, bio-compatible and silica-coated iron oxide nanocomposites as advanced MRI contrast agent",
|
||||
"year": 2013,
|
||||
"work_type": "article",
|
||||
"has_abstract": false,
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 75,
|
||||
"confidence": "medium",
|
||||
"classification_reason": "The title describes a specific material (nanocomposites) designed for a practical medical application (MRI contrast agent).",
|
||||
"validation_errors": [
|
||||
"applied_research_score_outside_expected_range"
|
||||
],
|
||||
"api_error": false,
|
||||
"api_error_message": null
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5075663980",
|
||||
"display_name": "Ursula Neumann"
|
||||
},
|
||||
"source_file": "llm_results/A5075663980_results.json",
|
||||
"summary": {
|
||||
"counts": {
|
||||
"works_total": 4,
|
||||
"valid_outputs": 4,
|
||||
"validation_errors": 0,
|
||||
"api_errors": 0
|
||||
},
|
||||
"category_distribution": {
|
||||
"basic_research": 2,
|
||||
"applied_research": 2,
|
||||
"experimental_development": 0,
|
||||
"non_research": 0
|
||||
},
|
||||
"category_share": {
|
||||
"basic_research": 0.5,
|
||||
"applied_research": 0.5,
|
||||
"experimental_development": 0.0,
|
||||
"non_research": 0.0
|
||||
},
|
||||
"confidence_distribution": {
|
||||
"high": 2,
|
||||
"medium": 2,
|
||||
"low": 0
|
||||
},
|
||||
"abstract_coverage": {
|
||||
"works_with_abstract": 2,
|
||||
"works_without_abstract": 2,
|
||||
"missing_abstract_share": 0.5
|
||||
},
|
||||
"score_summary": {
|
||||
"scored_outputs": 4,
|
||||
"mean_applied_orientation_score": 51.25,
|
||||
"median_applied_orientation_score": 52.5,
|
||||
"min_applied_orientation_score": 30,
|
||||
"max_applied_orientation_score": 70
|
||||
},
|
||||
"quality_checks": {
|
||||
"high_confidence_without_abstract": 0,
|
||||
"title_only_high_confidence": 0,
|
||||
"non_research_with_score": 0,
|
||||
"score_range_mismatches": 0
|
||||
},
|
||||
"usage": {
|
||||
"prompt_tokens": 12867,
|
||||
"uncached_prompt_tokens": 1219,
|
||||
"completion_tokens": 3531,
|
||||
"real_total_usage": 4750
|
||||
},
|
||||
"average_usage_per_work": {
|
||||
"prompt_tokens": 3216.75,
|
||||
"uncached_prompt_tokens": 304.75,
|
||||
"completion_tokens": 882.75,
|
||||
"real_total_usage": 1187.5
|
||||
},
|
||||
"timing": {
|
||||
"average_duration_seconds_per_work": 14.66
|
||||
},
|
||||
"problem_cases": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5088184531",
|
||||
"display_name": "Alf Kimms"
|
||||
},
|
||||
"source_file": "llm_results/A5088184531_results.json",
|
||||
"summary": {
|
||||
"counts": {
|
||||
"works_total": 86,
|
||||
"valid_outputs": 86,
|
||||
"validation_errors": 0,
|
||||
"api_errors": 0
|
||||
},
|
||||
"category_distribution": {
|
||||
"basic_research": 27,
|
||||
"applied_research": 53,
|
||||
"experimental_development": 2,
|
||||
"non_research": 4
|
||||
},
|
||||
"category_share": {
|
||||
"basic_research": 0.314,
|
||||
"applied_research": 0.6163,
|
||||
"experimental_development": 0.0233,
|
||||
"non_research": 0.0465
|
||||
},
|
||||
"confidence_distribution": {
|
||||
"high": 41,
|
||||
"medium": 43,
|
||||
"low": 2
|
||||
},
|
||||
"abstract_coverage": {
|
||||
"works_with_abstract": 42,
|
||||
"works_without_abstract": 44,
|
||||
"missing_abstract_share": 0.5116
|
||||
},
|
||||
"score_summary": {
|
||||
"scored_outputs": 82,
|
||||
"mean_applied_orientation_score": 51.83,
|
||||
"median_applied_orientation_score": 62.5,
|
||||
"min_applied_orientation_score": 10,
|
||||
"max_applied_orientation_score": 85
|
||||
},
|
||||
"quality_checks": {
|
||||
"high_confidence_without_abstract": 0,
|
||||
"title_only_high_confidence": 0,
|
||||
"non_research_with_score": 0,
|
||||
"score_range_mismatches": 0
|
||||
},
|
||||
"usage": {
|
||||
"prompt_tokens": 217185,
|
||||
"uncached_prompt_tokens": 217185,
|
||||
"completion_tokens": 73706,
|
||||
"real_total_usage": 290891
|
||||
},
|
||||
"average_usage_per_work": {
|
||||
"prompt_tokens": 2525.41,
|
||||
"uncached_prompt_tokens": 2525.41,
|
||||
"completion_tokens": 857.05,
|
||||
"real_total_usage": 3382.45
|
||||
},
|
||||
"timing": {
|
||||
"average_duration_seconds_per_work": 14.48
|
||||
},
|
||||
"problem_cases": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5089242868",
|
||||
"display_name": "Lucas Davi"
|
||||
},
|
||||
"source_file": "llm_results/A5089242868_results.json",
|
||||
"summary": {
|
||||
"counts": {
|
||||
"works_total": 135,
|
||||
"valid_outputs": 135,
|
||||
"validation_errors": 0,
|
||||
"api_errors": 0
|
||||
},
|
||||
"category_distribution": {
|
||||
"basic_research": 30,
|
||||
"applied_research": 43,
|
||||
"experimental_development": 60,
|
||||
"non_research": 2
|
||||
},
|
||||
"category_share": {
|
||||
"basic_research": 0.2222,
|
||||
"applied_research": 0.3185,
|
||||
"experimental_development": 0.4444,
|
||||
"non_research": 0.0148
|
||||
},
|
||||
"confidence_distribution": {
|
||||
"high": 95,
|
||||
"medium": 38,
|
||||
"low": 2
|
||||
},
|
||||
"abstract_coverage": {
|
||||
"works_with_abstract": 95,
|
||||
"works_without_abstract": 40,
|
||||
"missing_abstract_share": 0.2963
|
||||
},
|
||||
"score_summary": {
|
||||
"scored_outputs": 133,
|
||||
"mean_applied_orientation_score": 64.86,
|
||||
"median_applied_orientation_score": 70,
|
||||
"min_applied_orientation_score": 15,
|
||||
"max_applied_orientation_score": 92
|
||||
},
|
||||
"quality_checks": {
|
||||
"high_confidence_without_abstract": 0,
|
||||
"title_only_high_confidence": 0,
|
||||
"non_research_with_score": 0,
|
||||
"score_range_mismatches": 0
|
||||
},
|
||||
"usage": {
|
||||
"prompt_tokens": 340687,
|
||||
"uncached_prompt_tokens": 340687,
|
||||
"completion_tokens": 128333,
|
||||
"real_total_usage": 469020
|
||||
},
|
||||
"average_usage_per_work": {
|
||||
"prompt_tokens": 2523.61,
|
||||
"uncached_prompt_tokens": 2523.61,
|
||||
"completion_tokens": 950.61,
|
||||
"real_total_usage": 3474.22
|
||||
},
|
||||
"timing": {
|
||||
"average_duration_seconds_per_work": 16.1
|
||||
},
|
||||
"problem_cases": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5093075883",
|
||||
"display_name": "Arman Arzani"
|
||||
},
|
||||
"source_file": "llm_results/A5093075883_results.json",
|
||||
"summary": {
|
||||
"counts": {
|
||||
"works_total": 6,
|
||||
"valid_outputs": 4,
|
||||
"validation_errors": 2,
|
||||
"api_errors": 0
|
||||
},
|
||||
"category_distribution": {
|
||||
"basic_research": 0,
|
||||
"applied_research": 6,
|
||||
"experimental_development": 0,
|
||||
"non_research": 0
|
||||
},
|
||||
"category_share": {
|
||||
"basic_research": 0.0,
|
||||
"applied_research": 1.0,
|
||||
"experimental_development": 0.0,
|
||||
"non_research": 0.0
|
||||
},
|
||||
"confidence_distribution": {
|
||||
"high": 2,
|
||||
"medium": 4,
|
||||
"low": 0
|
||||
},
|
||||
"abstract_coverage": {
|
||||
"works_with_abstract": 2,
|
||||
"works_without_abstract": 4,
|
||||
"missing_abstract_share": 0.6667
|
||||
},
|
||||
"score_summary": {
|
||||
"scored_outputs": 6,
|
||||
"mean_applied_orientation_score": 67.5,
|
||||
"median_applied_orientation_score": 67.5,
|
||||
"min_applied_orientation_score": 60,
|
||||
"max_applied_orientation_score": 75
|
||||
},
|
||||
"quality_checks": {
|
||||
"high_confidence_without_abstract": 0,
|
||||
"title_only_high_confidence": 0,
|
||||
"non_research_with_score": 0,
|
||||
"score_range_mismatches": 2
|
||||
},
|
||||
"usage": {
|
||||
"prompt_tokens": 18992,
|
||||
"uncached_prompt_tokens": 368,
|
||||
"completion_tokens": 4790,
|
||||
"real_total_usage": 5158
|
||||
},
|
||||
"average_usage_per_work": {
|
||||
"prompt_tokens": 3165.33,
|
||||
"uncached_prompt_tokens": 61.33,
|
||||
"completion_tokens": 798.33,
|
||||
"real_total_usage": 859.67
|
||||
},
|
||||
"timing": {
|
||||
"average_duration_seconds_per_work": 13.36
|
||||
},
|
||||
"problem_cases": [
|
||||
{
|
||||
"person_name": "Arman Arzani",
|
||||
"person_id": "https://openalex.org/A5093075883",
|
||||
"work_id": "https://openalex.org/W4403369135",
|
||||
"doi": "https://doi.org/10.1007/s41060-024-00663-1",
|
||||
"title": "Discovering potential founders within academic institutions",
|
||||
"year": 2024,
|
||||
"work_type": "article",
|
||||
"has_abstract": true,
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 75,
|
||||
"confidence": "high",
|
||||
"classification_reason": "The abstract defines a specific practical aim: supporting the university scouting process by developing a data-driven prediction model.",
|
||||
"validation_errors": [
|
||||
"applied_research_score_outside_expected_range"
|
||||
],
|
||||
"api_error": false,
|
||||
"api_error_message": null
|
||||
},
|
||||
{
|
||||
"person_name": "Arman Arzani",
|
||||
"person_id": "https://openalex.org/A5093075883",
|
||||
"work_id": "https://openalex.org/W4387698137",
|
||||
"doi": "https://doi.org/10.1145/3603765.3603774",
|
||||
"title": "Exploiting Topic Modelling for the Identification of Untapped Scientific Collaborations",
|
||||
"year": 2023,
|
||||
"work_type": "article",
|
||||
"has_abstract": true,
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 75,
|
||||
"confidence": "high",
|
||||
"classification_reason": "The abstract describes developing and testing TOMOSCO, a framework aimed at solving the specific practical problem of identifying untapped scientific collaborations.",
|
||||
"validation_errors": [
|
||||
"applied_research_score_outside_expected_range"
|
||||
],
|
||||
"api_error": false,
|
||||
"api_error_message": null
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,984 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sqlite3
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
from openai import OpenAI
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
PROMPT_FILE = ROOT / "prompt_frascati.txt"
|
||||
SQLITE_FILE = ROOT / "classification_pipeline.sqlite3"
|
||||
REPORTS_DIR = ROOT / "run_reports"
|
||||
|
||||
ES_BASE_URL = "https://project.nes.uni-due.de/elastic".rstrip("/")
|
||||
ES_API_KEY = "am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ=="
|
||||
AUTHORS_INDEX = "openalex-authors"
|
||||
WORKS_INDEX = "openalex-works*"
|
||||
TARGET_INDEX = "work-classifications"
|
||||
|
||||
LLM_BASE_URL = "https://project.nes.uni-due.de/llm2/v1/"
|
||||
LLM_API_KEY = "c2d5e7ccf7a4760dd3d19bed2caed9d85ff7437400e0ea82a6d6f912ebc2f212"
|
||||
LLM_MODEL = "gemma4-e4b"
|
||||
PROMPT_VERSION = "frascati_v1"
|
||||
|
||||
UDE_ID = "https://openalex.org/I62318514"
|
||||
UDE_ROR = "https://ror.org/04mz5ra38"
|
||||
UDE_NAME = "University of Duisburg-Essen"
|
||||
AFFILIATION_YEAR_GTE = 2025
|
||||
WORK_YEAR_GTE = 1950
|
||||
|
||||
AUTHOR_PAGE_SIZE = 1000
|
||||
AUTHOR_BATCH_SIZE = 250
|
||||
WORK_PAGE_SIZE = 200
|
||||
MAX_WORKERS = 20
|
||||
MAX_TOKENS = 2048
|
||||
REQUEST_TIMEOUT = 180.0
|
||||
RETRIES = 3
|
||||
RETRY_DELAYS = (2.0, 5.0, 10.0)
|
||||
|
||||
CATEGORIES = {
|
||||
"basic_research",
|
||||
"applied_research",
|
||||
"experimental_development",
|
||||
"non_research",
|
||||
}
|
||||
QUADRANTS = {
|
||||
"pure_basic",
|
||||
"use_inspired_basic",
|
||||
"pure_applied",
|
||||
"not_applicable",
|
||||
}
|
||||
CONFIDENCE = {"high", "medium", "low"}
|
||||
SIGNALS = {
|
||||
"title",
|
||||
"abstract",
|
||||
"venue",
|
||||
"work_type",
|
||||
"topics",
|
||||
"funders",
|
||||
"year",
|
||||
"language",
|
||||
}
|
||||
|
||||
RESPONSE_SCHEMA: dict[str, Any] = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"primary_category": {"type": "string", "enum": sorted(CATEGORIES)},
|
||||
"applied_orientation_score": {
|
||||
"anyOf": [
|
||||
{"type": "integer", "minimum": 0, "maximum": 100},
|
||||
{"type": "null"},
|
||||
]
|
||||
},
|
||||
"pasteur_quadrant": {"type": "string", "enum": sorted(QUADRANTS)},
|
||||
"confidence": {"type": "string", "enum": sorted(CONFIDENCE)},
|
||||
"signals_used": {
|
||||
"type": "array",
|
||||
"items": {"type": "string", "enum": sorted(SIGNALS)},
|
||||
},
|
||||
"insufficient_context": {"type": "boolean"},
|
||||
"rationale": {"type": "string", "minLength": 1},
|
||||
},
|
||||
"required": [
|
||||
"primary_category",
|
||||
"applied_orientation_score",
|
||||
"pasteur_quadrant",
|
||||
"confidence",
|
||||
"signals_used",
|
||||
"insufficient_context",
|
||||
"rationale",
|
||||
],
|
||||
"additionalProperties": False,
|
||||
}
|
||||
|
||||
|
||||
class StopPipeline(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def now() -> str:
|
||||
return (
|
||||
datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
|
||||
)
|
||||
|
||||
|
||||
def bare_id(value: Any) -> str:
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
raise StopPipeline("Work without OpenAlex id")
|
||||
return value.rstrip("/").rsplit("/", 1)[-1]
|
||||
|
||||
|
||||
def text(value: Any) -> bool:
|
||||
return isinstance(value, str) and bool(value.strip())
|
||||
|
||||
|
||||
def unique(values: list[Any], limit: int = 8) -> list[str]:
|
||||
result: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for value in values:
|
||||
if not text(value):
|
||||
continue
|
||||
clean = value.strip()
|
||||
key = clean.casefold()
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
result.append(clean)
|
||||
if len(result) == limit:
|
||||
break
|
||||
return result
|
||||
|
||||
|
||||
def venue(work: dict[str, Any]) -> str | None:
|
||||
source = (work.get("primary_location") or {}).get("source") or {}
|
||||
if text(source.get("display_name")):
|
||||
return source["display_name"]
|
||||
for location in work.get("locations") or []:
|
||||
source = (location or {}).get("source") or {}
|
||||
if text(source.get("display_name")):
|
||||
return source["display_name"]
|
||||
return None
|
||||
|
||||
|
||||
def topics(work: dict[str, Any]) -> list[str]:
|
||||
values: list[Any] = []
|
||||
for topic in work.get("topics") or []:
|
||||
if not isinstance(topic, dict):
|
||||
continue
|
||||
values.append(topic.get("display_name"))
|
||||
values.append((topic.get("subfield") or {}).get("display_name"))
|
||||
values.append((topic.get("field") or {}).get("display_name"))
|
||||
for concept in work.get("concepts") or []:
|
||||
if isinstance(concept, dict):
|
||||
values.append(concept.get("display_name"))
|
||||
return unique(values)
|
||||
|
||||
|
||||
def funders(work: dict[str, Any]) -> list[str]:
|
||||
values: list[Any] = []
|
||||
for funder in work.get("funders") or []:
|
||||
if isinstance(funder, dict):
|
||||
values.append(funder.get("display_name"))
|
||||
for award in work.get("awards") or []:
|
||||
if isinstance(award, dict):
|
||||
values.append(award.get("funder_display_name"))
|
||||
return unique(values)
|
||||
|
||||
|
||||
def make_input(work: dict[str, Any]) -> dict[str, Any]:
|
||||
abstract = work.get("abstract")
|
||||
return {
|
||||
"title": work.get("title") or work.get("display_name"),
|
||||
"abstract": abstract if text(abstract) else None,
|
||||
"venue": venue(work),
|
||||
"work_type": work.get("type"),
|
||||
"topics": topics(work),
|
||||
"funders": funders(work),
|
||||
"year": work.get("publication_year"),
|
||||
"language": work.get("language"),
|
||||
}
|
||||
|
||||
|
||||
def clean_json(content: str) -> str:
|
||||
content = content.strip()
|
||||
if content.startswith("```"):
|
||||
lines = content.splitlines()[1:]
|
||||
if lines and lines[-1].strip() == "```":
|
||||
lines.pop()
|
||||
content = "\n".join(lines).strip()
|
||||
return content
|
||||
|
||||
|
||||
def number(value: Any) -> bool:
|
||||
return isinstance(value, (int, float)) and not isinstance(value, bool)
|
||||
|
||||
|
||||
def validate(result: dict[str, Any]) -> list[str]:
|
||||
errors: list[str] = []
|
||||
category = result.get("primary_category")
|
||||
score = result.get("applied_orientation_score")
|
||||
quadrant = result.get("pasteur_quadrant")
|
||||
confidence = result.get("confidence")
|
||||
signals = result.get("signals_used")
|
||||
|
||||
if category not in CATEGORIES:
|
||||
errors.append("invalid_primary_category")
|
||||
if quadrant not in QUADRANTS:
|
||||
errors.append("invalid_pasteur_quadrant")
|
||||
if confidence not in CONFIDENCE:
|
||||
errors.append("invalid_confidence")
|
||||
if not isinstance(signals, list):
|
||||
errors.append("signals_used_must_be_list")
|
||||
else:
|
||||
if any(item not in SIGNALS for item in signals):
|
||||
errors.append("invalid_signals_used")
|
||||
if len(signals) != len(set(signals)):
|
||||
errors.append("signals_used_must_be_unique")
|
||||
if not isinstance(result.get("insufficient_context"), bool):
|
||||
errors.append("insufficient_context_must_be_boolean")
|
||||
if not text(result.get("rationale")):
|
||||
errors.append("rationale_missing_or_empty")
|
||||
|
||||
if category == "non_research":
|
||||
if score is not None:
|
||||
errors.append("non_research_score_must_be_null")
|
||||
if quadrant != "not_applicable":
|
||||
errors.append("non_research_quadrant_must_be_not_applicable")
|
||||
elif category == "basic_research":
|
||||
if not number(score):
|
||||
errors.append("basic_research_score_missing")
|
||||
elif quadrant == "pure_basic":
|
||||
if not 0 <= score <= 30:
|
||||
errors.append("basic_research_quadrant_score_mismatch")
|
||||
elif quadrant == "use_inspired_basic":
|
||||
if not 25 <= score <= 45:
|
||||
errors.append("basic_research_quadrant_score_mismatch")
|
||||
if quadrant not in {"pure_basic", "use_inspired_basic"}:
|
||||
errors.append("basic_research_quadrant_mismatch")
|
||||
elif category == "applied_research":
|
||||
if not number(score):
|
||||
errors.append("applied_research_score_missing")
|
||||
elif not 31 <= score <= 70:
|
||||
errors.append("applied_research_score_outside_expected_range")
|
||||
if quadrant != "pure_applied":
|
||||
errors.append("applied_research_quadrant_mismatch")
|
||||
elif category == "experimental_development":
|
||||
if not number(score):
|
||||
errors.append("experimental_development_score_missing")
|
||||
elif not 71 <= score <= 100:
|
||||
errors.append("experimental_development_score_outside_expected_range")
|
||||
if quadrant != "pure_applied":
|
||||
errors.append("experimental_development_quadrant_mismatch")
|
||||
return errors
|
||||
|
||||
|
||||
def ude_affiliation_filter() -> dict[str, Any]:
|
||||
return {
|
||||
"nested": {
|
||||
"path": "affiliations",
|
||||
"query": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{
|
||||
"bool": {
|
||||
"should": [
|
||||
{"term": {"affiliations.institution.id": UDE_ID}},
|
||||
{"term": {"affiliations.institution.ror": UDE_ROR}},
|
||||
{
|
||||
"match_phrase": {
|
||||
"affiliations.institution.display_name": UDE_NAME
|
||||
}
|
||||
},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
},
|
||||
{
|
||||
"range": {
|
||||
"affiliations.years": {"gte": AFFILIATION_YEAR_GTE}
|
||||
}
|
||||
},
|
||||
]
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def author_query(group: str, after: list[Any] | None) -> dict[str, Any]:
|
||||
last_known = {
|
||||
"nested": {
|
||||
"path": "last_known_institutions",
|
||||
"query": {
|
||||
"match_phrase": {"last_known_institutions.display_name": UDE_NAME}
|
||||
},
|
||||
}
|
||||
}
|
||||
last_known_exists = {
|
||||
"nested": {
|
||||
"path": "last_known_institutions",
|
||||
"query": {"exists": {"field": "last_known_institutions.display_name"}},
|
||||
}
|
||||
}
|
||||
query = (
|
||||
{"bool": {"filter": [last_known, ude_affiliation_filter()]}}
|
||||
if group == "known"
|
||||
else {
|
||||
"bool": {
|
||||
"filter": [ude_affiliation_filter()],
|
||||
"must_not": [last_known_exists],
|
||||
}
|
||||
}
|
||||
)
|
||||
body: dict[str, Any] = {
|
||||
"size": AUTHOR_PAGE_SIZE,
|
||||
"track_total_hits": True,
|
||||
"_source": ["id"],
|
||||
"query": query,
|
||||
"sort": [{"id": "asc"}],
|
||||
}
|
||||
if after is not None:
|
||||
body["search_after"] = after
|
||||
return body
|
||||
|
||||
|
||||
def work_query(author_ids: list[str], after: list[Any] | None) -> dict[str, Any]:
|
||||
body: dict[str, Any] = {
|
||||
"size": WORK_PAGE_SIZE,
|
||||
"track_total_hits": False,
|
||||
"_source": [
|
||||
"id",
|
||||
"title",
|
||||
"display_name",
|
||||
"abstract",
|
||||
"publication_year",
|
||||
"type",
|
||||
"language",
|
||||
"primary_location.source.display_name",
|
||||
"locations.source.display_name",
|
||||
"topics.display_name",
|
||||
"topics.subfield.display_name",
|
||||
"topics.field.display_name",
|
||||
"concepts.display_name",
|
||||
"funders.display_name",
|
||||
"awards.funder_display_name",
|
||||
],
|
||||
"query": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{"range": {"publication_year": {"gte": WORK_YEAR_GTE}}},
|
||||
{
|
||||
"nested": {
|
||||
"path": "authorships",
|
||||
"query": {"terms": {"authorships.author.id": author_ids}},
|
||||
}
|
||||
},
|
||||
]
|
||||
}
|
||||
},
|
||||
"sort": [{"id": "asc"}],
|
||||
}
|
||||
if after is not None:
|
||||
body["search_after"] = after
|
||||
return body
|
||||
|
||||
|
||||
class ES:
|
||||
def __init__(self) -> None:
|
||||
self.session = requests.Session()
|
||||
self.session.headers.update(
|
||||
{
|
||||
"Authorization": f"ApiKey {ES_API_KEY}",
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
}
|
||||
)
|
||||
|
||||
def call(
|
||||
self, method: str, path: str, body: dict[str, Any] | None = None
|
||||
) -> dict[str, Any]:
|
||||
error: Exception | None = None
|
||||
for attempt in range(RETRIES):
|
||||
try:
|
||||
response = self.session.request(
|
||||
method,
|
||||
f"{ES_BASE_URL}/{path.lstrip('/')}",
|
||||
json=body,
|
||||
timeout=120,
|
||||
)
|
||||
if response.ok:
|
||||
return response.json()
|
||||
message = RuntimeError(
|
||||
f"Elasticsearch {response.status_code}: {response.text}"
|
||||
)
|
||||
if response.status_code < 500 and response.status_code != 429:
|
||||
raise StopPipeline(str(message))
|
||||
error = message
|
||||
except StopPipeline:
|
||||
raise
|
||||
except requests.RequestException as exception:
|
||||
error = exception
|
||||
if attempt < RETRIES - 1:
|
||||
delay = RETRY_DELAYS[attempt]
|
||||
print(f"Elasticsearch retry in {delay:.0f}s: {error}")
|
||||
time.sleep(delay)
|
||||
raise StopPipeline(f"Elasticsearch unavailable: {error}")
|
||||
|
||||
def search(self, index: str, body: dict[str, Any]) -> dict[str, Any]:
|
||||
return self.call("POST", f"{index}/_search", body)
|
||||
|
||||
def mget(self, ids: list[str]) -> dict[str, dict[str, Any]]:
|
||||
result = self.call("POST", f"{TARGET_INDEX}/_mget", {"ids": ids})
|
||||
return {doc["_id"]: doc for doc in result.get("docs", [])}
|
||||
|
||||
def index(self, work_id: str, document: dict[str, Any]) -> None:
|
||||
self.call("PUT", f"{TARGET_INDEX}/_doc/{work_id}", document)
|
||||
|
||||
def preflight(self) -> None:
|
||||
self.call("GET", f"{AUTHORS_INDEX}/_count")
|
||||
self.call("GET", f"{WORKS_INDEX}/_count")
|
||||
mapping = self.call("GET", f"{TARGET_INDEX}/_mapping")
|
||||
current = mapping.get(TARGET_INDEX, {}).get("mappings", {})
|
||||
fields = current.get("properties", {})
|
||||
required = {"work_id", "classification", "validation", "classification_meta"}
|
||||
if current.get("dynamic") != "strict" or not required.issubset(fields):
|
||||
raise StopPipeline("Unexpected target index mapping")
|
||||
|
||||
|
||||
class DB:
|
||||
def __init__(self) -> None:
|
||||
self.conn = sqlite3.connect(SQLITE_FILE)
|
||||
self.conn.execute("PRAGMA journal_mode=WAL")
|
||||
self.conn.execute("PRAGMA synchronous=FULL")
|
||||
self.conn.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS works (
|
||||
work_id TEXT PRIMARY KEY,
|
||||
status TEXT NOT NULL,
|
||||
result_json TEXT,
|
||||
updated_at TEXT NOT NULL
|
||||
)
|
||||
"""
|
||||
)
|
||||
self.conn.commit()
|
||||
|
||||
def reset(self) -> None:
|
||||
count = self.conn.execute(
|
||||
"UPDATE works SET status='pending', updated_at=? WHERE status='processing'",
|
||||
(now(),),
|
||||
).rowcount
|
||||
self.conn.commit()
|
||||
if count:
|
||||
print(f"Reset interrupted rows: {count}")
|
||||
|
||||
def state(self, work_id: str) -> tuple[str, dict[str, Any] | None] | None:
|
||||
row = self.conn.execute(
|
||||
"SELECT status, result_json FROM works WHERE work_id=?", (work_id,)
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
document = json.loads(row[1]) if isinstance(row[1], str) else None
|
||||
return row[0], document
|
||||
|
||||
def claim(self, work_id: str) -> bool:
|
||||
state = self.state(work_id)
|
||||
if state is not None and state[0] not in {"pending", "indexed"}:
|
||||
return False
|
||||
if state is not None and state[0] == "indexed" and state[1] is not None:
|
||||
return False
|
||||
self.conn.execute(
|
||||
"""
|
||||
INSERT INTO works(work_id, status, result_json, updated_at)
|
||||
VALUES (?, 'processing', NULL, ?)
|
||||
ON CONFLICT(work_id) DO UPDATE SET status='processing', updated_at=excluded.updated_at
|
||||
""",
|
||||
(work_id, now()),
|
||||
)
|
||||
self.conn.commit()
|
||||
return True
|
||||
|
||||
def save(self, work_id: str, status: str, document: dict[str, Any] | None) -> None:
|
||||
raw = json.dumps(document, ensure_ascii=False) if document is not None else None
|
||||
self.conn.execute(
|
||||
"""
|
||||
INSERT INTO works(work_id, status, result_json, updated_at)
|
||||
VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT(work_id) DO UPDATE SET
|
||||
status=excluded.status,
|
||||
result_json=COALESCE(excluded.result_json, works.result_json),
|
||||
updated_at=excluded.updated_at
|
||||
""",
|
||||
(work_id, status, raw, now()),
|
||||
)
|
||||
self.conn.commit()
|
||||
|
||||
def ready(self) -> list[tuple[str, dict[str, Any]]]:
|
||||
rows = self.conn.execute(
|
||||
"SELECT work_id, result_json FROM works WHERE status='ready' ORDER BY work_id"
|
||||
).fetchall()
|
||||
return [(work_id, json.loads(raw)) for work_id, raw in rows]
|
||||
|
||||
def counts(self) -> dict[str, int]:
|
||||
return dict(
|
||||
self.conn.execute(
|
||||
"SELECT status, COUNT(*) FROM works GROUP BY status"
|
||||
).fetchall()
|
||||
)
|
||||
|
||||
def set_pending(self, ids: list[str]) -> None:
|
||||
self.conn.executemany(
|
||||
"UPDATE works SET status='pending', updated_at=? WHERE work_id=?",
|
||||
[(now(), work_id) for work_id in ids],
|
||||
)
|
||||
self.conn.commit()
|
||||
|
||||
def close(self) -> None:
|
||||
self.conn.close()
|
||||
|
||||
|
||||
def load_prompt() -> str:
|
||||
if not PROMPT_FILE.exists():
|
||||
raise StopPipeline(f"Prompt not found: {PROMPT_FILE}")
|
||||
prompt = PROMPT_FILE.read_text(encoding="utf-8").strip()
|
||||
if not prompt:
|
||||
raise StopPipeline("Prompt is empty")
|
||||
return prompt
|
||||
|
||||
|
||||
def response_usage(response: Any) -> dict[str, int]:
|
||||
usage = getattr(response, "usage", None)
|
||||
prompt_tokens = int(getattr(usage, "prompt_tokens", 0) or 0)
|
||||
completion_tokens = int(getattr(usage, "completion_tokens", 0) or 0)
|
||||
|
||||
details = getattr(usage, "prompt_tokens_details", None)
|
||||
if isinstance(details, dict):
|
||||
cached_prompt_tokens = int(details.get("cached_tokens", 0) or 0)
|
||||
else:
|
||||
cached_prompt_tokens = int(getattr(details, "cached_tokens", 0) or 0)
|
||||
|
||||
uncached_prompt_tokens = max(prompt_tokens - cached_prompt_tokens, 0)
|
||||
return {
|
||||
"prompt_tokens": prompt_tokens,
|
||||
"cached_prompt_tokens": cached_prompt_tokens,
|
||||
"uncached_prompt_tokens": uncached_prompt_tokens,
|
||||
"completion_tokens": completion_tokens,
|
||||
"real_total_usage": uncached_prompt_tokens + completion_tokens,
|
||||
}
|
||||
|
||||
|
||||
def new_run_report(limit: int | None, workers: int) -> dict[str, Any]:
|
||||
return {
|
||||
"run_id": datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S_%f"),
|
||||
"started_at": now(),
|
||||
"_started_monotonic": time.monotonic(),
|
||||
"finished_at": None,
|
||||
"duration_seconds": None,
|
||||
"status": "running",
|
||||
"error": None,
|
||||
"parameters": {
|
||||
"limit": limit,
|
||||
"workers": workers,
|
||||
"model": LLM_MODEL,
|
||||
"prompt_version": PROMPT_VERSION,
|
||||
},
|
||||
"classification": {
|
||||
"llm_completed": 0,
|
||||
"valid": 0,
|
||||
"invalid": 0,
|
||||
"categories": {},
|
||||
"validation_errors": {},
|
||||
},
|
||||
"indexing": {
|
||||
"newly_indexed": 0,
|
||||
"recovered_from_ready": 0,
|
||||
},
|
||||
"token_usage": {
|
||||
"prompt_tokens": 0,
|
||||
"cached_prompt_tokens": 0,
|
||||
"uncached_prompt_tokens": 0,
|
||||
"completion_tokens": 0,
|
||||
"real_total_usage": 0,
|
||||
},
|
||||
"throughput_indexed_per_hour": 0.0,
|
||||
"sqlite_counts_after_run": {},
|
||||
}
|
||||
|
||||
|
||||
def increment(counter: dict[str, int], key: str, amount: int = 1) -> None:
|
||||
counter[key] = counter.get(key, 0) + amount
|
||||
|
||||
|
||||
def add_result_to_report(
|
||||
report: dict[str, Any],
|
||||
document: dict[str, Any],
|
||||
usage: dict[str, int],
|
||||
) -> None:
|
||||
classification = report["classification"]
|
||||
classification["llm_completed"] += 1
|
||||
|
||||
validation = document.get("validation") or {}
|
||||
if validation.get("valid") is True:
|
||||
classification["valid"] += 1
|
||||
else:
|
||||
classification["invalid"] += 1
|
||||
|
||||
result = document.get("classification") or {}
|
||||
category = result.get("primary_category")
|
||||
if isinstance(category, str):
|
||||
increment(classification["categories"], category)
|
||||
|
||||
for error in validation.get("errors") or []:
|
||||
if isinstance(error, str):
|
||||
increment(classification["validation_errors"], error)
|
||||
|
||||
totals = report["token_usage"]
|
||||
for key, value in usage.items():
|
||||
totals[key] += int(value)
|
||||
|
||||
|
||||
def write_run_report(report: dict[str, Any]) -> Path:
|
||||
report["finished_at"] = now()
|
||||
started = float(report.pop("_started_monotonic", time.monotonic()))
|
||||
report["duration_seconds"] = round(time.monotonic() - started, 3)
|
||||
|
||||
duration = report["duration_seconds"]
|
||||
indexed = report["indexing"]["newly_indexed"]
|
||||
if duration > 0:
|
||||
report["throughput_indexed_per_hour"] = round(indexed * 3600 / duration, 2)
|
||||
|
||||
if SQLITE_FILE.exists():
|
||||
connection = sqlite3.connect(SQLITE_FILE)
|
||||
try:
|
||||
report["sqlite_counts_after_run"] = dict(
|
||||
connection.execute(
|
||||
"SELECT status, COUNT(*) FROM works GROUP BY status"
|
||||
).fetchall()
|
||||
)
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
REPORTS_DIR.mkdir(parents=True, exist_ok=True)
|
||||
path = REPORTS_DIR / f"run_{report['run_id']}.json"
|
||||
temporary = path.with_suffix(".tmp")
|
||||
temporary.write_text(
|
||||
json.dumps(report, ensure_ascii=False, indent=2),
|
||||
encoding="utf-8",
|
||||
)
|
||||
temporary.replace(path)
|
||||
return path
|
||||
|
||||
|
||||
def classify(
|
||||
client: OpenAI,
|
||||
prompt: str,
|
||||
work_id: str,
|
||||
input_data: dict[str, Any],
|
||||
) -> tuple[dict[str, Any], dict[str, int]]:
|
||||
error: Exception | None = None
|
||||
for attempt in range(RETRIES):
|
||||
try:
|
||||
response = client.chat.completions.create(
|
||||
model=LLM_MODEL,
|
||||
messages=[
|
||||
{"role": "system", "content": prompt},
|
||||
{
|
||||
"role": "user",
|
||||
"content": json.dumps(input_data, ensure_ascii=False, indent=2),
|
||||
},
|
||||
],
|
||||
temperature=0,
|
||||
max_tokens=MAX_TOKENS,
|
||||
top_p=1.0,
|
||||
response_format={
|
||||
"type": "json_schema",
|
||||
"json_schema": {
|
||||
"name": "frascati_research_orientation",
|
||||
"strict": True,
|
||||
"schema": RESPONSE_SCHEMA,
|
||||
},
|
||||
},
|
||||
extra_body={"top_k": 64},
|
||||
)
|
||||
if not response.choices:
|
||||
raise RuntimeError("LLM response has no choices")
|
||||
content = response.choices[0].message.content or ""
|
||||
result = json.loads(clean_json(content))
|
||||
if not isinstance(result, dict):
|
||||
raise RuntimeError("LLM response is not an object")
|
||||
errors = validate(result)
|
||||
result = dict(result)
|
||||
result["classification_reason"] = result.pop("rationale")
|
||||
document = {
|
||||
"work_id": work_id,
|
||||
"classification": result,
|
||||
"validation": {
|
||||
"valid": not errors,
|
||||
"errors": errors,
|
||||
"corrections": [],
|
||||
},
|
||||
"classification_meta": {
|
||||
"model": LLM_MODEL,
|
||||
"prompt_version": PROMPT_VERSION,
|
||||
"classified_at": now(),
|
||||
},
|
||||
}
|
||||
return document, response_usage(response)
|
||||
except Exception as exception:
|
||||
code = getattr(exception, "status_code", None)
|
||||
if code in {400, 401, 403, 404}:
|
||||
raise StopPipeline(
|
||||
f"LLM request failed for {work_id}: {exception}"
|
||||
) from exception
|
||||
error = exception
|
||||
if attempt < RETRIES - 1:
|
||||
delay = RETRY_DELAYS[attempt]
|
||||
print(f"LLM retry for {work_id} in {delay:.0f}s: {exception}")
|
||||
time.sleep(delay)
|
||||
raise StopPipeline(f"LLM unavailable for {work_id}: {error}")
|
||||
|
||||
|
||||
def collect_authors(es: ES) -> list[str]:
|
||||
ids: set[str] = set()
|
||||
for group in ("known", "empty"):
|
||||
after = None
|
||||
total = None
|
||||
read = 0
|
||||
while True:
|
||||
result = es.search(AUTHORS_INDEX, author_query(group, after))
|
||||
hits = result.get("hits", {}).get("hits", [])
|
||||
if total is None:
|
||||
value = result.get("hits", {}).get("total", 0)
|
||||
total = int(value.get("value", 0) if isinstance(value, dict) else value)
|
||||
print(f"Authors {group}: expected {total}")
|
||||
if not hits:
|
||||
break
|
||||
for hit in hits:
|
||||
author_id = (hit.get("_source") or {}).get("id")
|
||||
if isinstance(author_id, str):
|
||||
ids.add(author_id)
|
||||
read += len(hits)
|
||||
after = hits[-1].get("sort")
|
||||
if not isinstance(after, list):
|
||||
raise StopPipeline("Missing author search_after")
|
||||
print(f"Authors {group}: {read}/{total}")
|
||||
result = sorted(ids)
|
||||
print(f"Final UDE author count: {len(result)}")
|
||||
return result
|
||||
|
||||
|
||||
def index_saved(es: ES, db: DB, report: dict[str, Any]) -> None:
|
||||
ready = db.ready()
|
||||
if ready:
|
||||
print(f"Indexing saved results: {len(ready)}")
|
||||
for number, (work_id, document) in enumerate(ready, 1):
|
||||
es.index(work_id, document)
|
||||
db.save(work_id, "indexed", document)
|
||||
report["indexing"]["recovered_from_ready"] += 1
|
||||
print(f"Recovered {number}/{len(ready)}: {work_id}")
|
||||
|
||||
|
||||
def run_page(
|
||||
es: ES,
|
||||
db: DB,
|
||||
llm: OpenAI,
|
||||
prompt: str,
|
||||
items: list[tuple[str, dict[str, Any]]],
|
||||
workers: int,
|
||||
warm: bool,
|
||||
count: int,
|
||||
report: dict[str, Any],
|
||||
) -> tuple[bool, int]:
|
||||
if not items:
|
||||
return warm, count
|
||||
|
||||
if not warm:
|
||||
work_id, source = items.pop(0)
|
||||
print(f"Prefix cache warm-up: {work_id}")
|
||||
document, usage = classify(llm, prompt, work_id, make_input(source))
|
||||
add_result_to_report(report, document, usage)
|
||||
db.save(work_id, "ready", document)
|
||||
es.index(work_id, document)
|
||||
db.save(work_id, "indexed", document)
|
||||
report["indexing"]["newly_indexed"] += 1
|
||||
count += 1
|
||||
print(f"Indexed {count}: {work_id}")
|
||||
warm = True
|
||||
|
||||
if not items:
|
||||
return warm, count
|
||||
|
||||
error: Exception | None = None
|
||||
target_down = False
|
||||
with ThreadPoolExecutor(max_workers=min(workers, len(items))) as executor:
|
||||
futures = {
|
||||
executor.submit(classify, llm, prompt, work_id, make_input(source)): work_id
|
||||
for work_id, source in items
|
||||
}
|
||||
for future in as_completed(futures):
|
||||
work_id = futures[future]
|
||||
try:
|
||||
document, usage = future.result()
|
||||
add_result_to_report(report, document, usage)
|
||||
except Exception as exception:
|
||||
error = error or exception
|
||||
for other in futures:
|
||||
other.cancel()
|
||||
continue
|
||||
|
||||
db.save(work_id, "ready", document)
|
||||
if target_down:
|
||||
continue
|
||||
try:
|
||||
es.index(work_id, document)
|
||||
db.save(work_id, "indexed", document)
|
||||
report["indexing"]["newly_indexed"] += 1
|
||||
count += 1
|
||||
print(f"Indexed {count}: {work_id}")
|
||||
except Exception as exception:
|
||||
target_down = True
|
||||
error = error or exception
|
||||
|
||||
if error is not None:
|
||||
raise StopPipeline(str(error))
|
||||
return warm, count
|
||||
|
||||
|
||||
def run(limit: int | None, workers: int, report: dict[str, Any]) -> None:
|
||||
if not ES_API_KEY.strip():
|
||||
raise StopPipeline("ES_API_KEY is empty")
|
||||
if not LLM_API_KEY.strip():
|
||||
raise StopPipeline("LLM_API_KEY is empty")
|
||||
|
||||
db = DB()
|
||||
es = ES()
|
||||
try:
|
||||
db.reset()
|
||||
print("Preflight...")
|
||||
es.preflight()
|
||||
prompt = load_prompt()
|
||||
llm = OpenAI(
|
||||
base_url=LLM_BASE_URL, api_key=LLM_API_KEY, timeout=REQUEST_TIMEOUT
|
||||
)
|
||||
index_saved(es, db, report)
|
||||
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 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}")
|
||||
after = None
|
||||
page = 0
|
||||
|
||||
while True:
|
||||
if limit is not None and count >= limit:
|
||||
break
|
||||
result = es.search(WORKS_INDEX, work_query(batch, after))
|
||||
hits = result.get("hits", {}).get("hits", [])
|
||||
if not hits:
|
||||
break
|
||||
page += 1
|
||||
|
||||
ids: list[str] = []
|
||||
sources: dict[str, dict[str, Any]] = {}
|
||||
for hit in hits:
|
||||
source = hit.get("_source") or {}
|
||||
work_id = bare_id(hit.get("_id") or source.get("id"))
|
||||
ids.append(work_id)
|
||||
sources[work_id] = source
|
||||
|
||||
existing = es.mget(ids)
|
||||
items: list[tuple[str, dict[str, Any]]] = []
|
||||
|
||||
for work_id in ids:
|
||||
target = existing.get(work_id)
|
||||
if target and target.get("found"):
|
||||
target_source = target.get("_source")
|
||||
db.save(
|
||||
work_id,
|
||||
"indexed",
|
||||
target_source if isinstance(target_source, dict) else None,
|
||||
)
|
||||
continue
|
||||
|
||||
state = db.state(work_id)
|
||||
if (
|
||||
state
|
||||
and state[1] is not None
|
||||
and state[0] in {"ready", "indexed"}
|
||||
):
|
||||
es.index(work_id, state[1])
|
||||
db.save(work_id, "indexed", state[1])
|
||||
continue
|
||||
|
||||
if db.claim(work_id):
|
||||
items.append((work_id, sources[work_id]))
|
||||
|
||||
if limit is not None and len(items) > limit - count:
|
||||
keep = max(limit - count, 0)
|
||||
db.set_pending([work_id for work_id, _ in items[keep:]])
|
||||
items = items[:keep]
|
||||
|
||||
print(f"Page {page}: hits={len(hits)}, new_for_llm={len(items)}")
|
||||
warm, count = run_page(
|
||||
es, db, llm, prompt, items, workers, warm, count, report
|
||||
)
|
||||
|
||||
after = hits[-1].get("sort")
|
||||
if not isinstance(after, list):
|
||||
raise StopPipeline("Missing work search_after")
|
||||
|
||||
print("\nCompleted")
|
||||
print(f"Newly classified and indexed: {count}")
|
||||
print(f"SQLite: {SQLITE_FILE}")
|
||||
print(f"SQLite counts: {db.counts()}")
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def status() -> None:
|
||||
db = DB()
|
||||
try:
|
||||
print(f"SQLite: {SQLITE_FILE}")
|
||||
print(json.dumps(db.counts(), indent=2))
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--limit", type=int)
|
||||
parser.add_argument("--workers", type=int, default=MAX_WORKERS)
|
||||
parser.add_argument("--status", action="store_true")
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.status:
|
||||
status()
|
||||
return
|
||||
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")
|
||||
|
||||
report = new_run_report(args.limit, args.workers)
|
||||
exit_code = 0
|
||||
|
||||
try:
|
||||
run(args.limit, args.workers, report)
|
||||
report["status"] = "completed"
|
||||
except KeyboardInterrupt:
|
||||
report["status"] = "interrupted"
|
||||
report["error"] = "KeyboardInterrupt"
|
||||
print("\nInterrupted. Completed results are saved in SQLite.")
|
||||
exit_code = 130
|
||||
except StopPipeline as exception:
|
||||
report["status"] = "stopped_with_error"
|
||||
report["error"] = str(exception)
|
||||
print(f"\nPipeline stopped: {exception}")
|
||||
exit_code = 1
|
||||
except Exception as exception:
|
||||
report["status"] = "crashed"
|
||||
report["error"] = f"{type(exception).__name__}: {exception}"
|
||||
print(f"\nPipeline crashed: {exception}")
|
||||
exit_code = 1
|
||||
finally:
|
||||
report_path = write_run_report(report)
|
||||
print(f"Run report: {report_path}")
|
||||
|
||||
if exit_code:
|
||||
raise SystemExit(exit_code)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -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 collections.abc import Iterable
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
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)
|
||||
@@ -373,8 +373,8 @@ def interval_distance(value: float, minimum: float, maximum: float) -> float:
|
||||
|
||||
|
||||
def safe_rate(
|
||||
numerator: int | float,
|
||||
denominator: int | float,
|
||||
numerator: float,
|
||||
denominator: float,
|
||||
) -> float | None:
|
||||
if not denominator:
|
||||
return None
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+6
-26
@@ -7,8 +7,8 @@
|
||||
"interpretation": "Compatibility with a four-model consensus reference, not objective ground truth."
|
||||
},
|
||||
"reference_agreement": {
|
||||
"unanimous_4_0": 28,
|
||||
"majority_3_1": 13,
|
||||
"unanimous_4_0": 28,
|
||||
"split_2_2": 7,
|
||||
"low_consensus": 2
|
||||
},
|
||||
@@ -16,8 +16,7 @@
|
||||
"coverage": {
|
||||
"matched": 50,
|
||||
"total": 50,
|
||||
"rate": 1.0,
|
||||
"missing_ids": []
|
||||
"rate": 1.0
|
||||
},
|
||||
"category": {
|
||||
"overall_consensus_compatible": {
|
||||
@@ -57,16 +56,6 @@
|
||||
"inside_reference_range": 20,
|
||||
"outside_reference_range": 16,
|
||||
"inside_reference_range_rate": 0.5555555555555556,
|
||||
"within_5_points_of_range": {
|
||||
"matched": 28,
|
||||
"total": 36,
|
||||
"rate": 0.7777777777777778
|
||||
},
|
||||
"within_10_points_of_range": {
|
||||
"matched": 34,
|
||||
"total": 36,
|
||||
"rate": 0.9444444444444444
|
||||
},
|
||||
"mean_distance_to_range": 2.861111111111111,
|
||||
"median_distance_to_range": 0.0,
|
||||
"mean_absolute_error_to_reference_median": 6.583333333333333,
|
||||
@@ -92,13 +81,10 @@
|
||||
"invalid": 7,
|
||||
"valid_rate": 0.86
|
||||
},
|
||||
"schema_valid_rate": 1.0,
|
||||
"category_score_quadrant_consistency_rate": 0.94,
|
||||
"confidence_cap_compliance_rate": 0.92,
|
||||
"signals_used_valid_rate": 1.0
|
||||
"confidence_cap_compliance_rate": 0.92
|
||||
},
|
||||
"confidence": {
|
||||
"by_level": {
|
||||
"compatibility_by_confidence": {
|
||||
"high": {
|
||||
"count": 40,
|
||||
"compatible": 35,
|
||||
@@ -115,11 +101,7 @@
|
||||
"compatibility_rate": 1.0
|
||||
}
|
||||
},
|
||||
"high_confidence_incompatible": {
|
||||
"count": 5,
|
||||
"total": 40,
|
||||
"rate": 0.125
|
||||
}
|
||||
"high_confidence_incompatibility_rate": 0.125
|
||||
}
|
||||
},
|
||||
"issues": {
|
||||
@@ -248,8 +230,6 @@
|
||||
},
|
||||
"assessment": {
|
||||
"overall": "good",
|
||||
"summary": "43/50 classifications are compatible with the four-model consensus reference.",
|
||||
"category_mismatch_count": 7,
|
||||
"technical_issue_count": 7
|
||||
"summary": "Gemma is strongly aligned with the four-model reference. Weaknesses are concentrated in boundary cases, applied versus experimental distinctions, and confidence caps."
|
||||
}
|
||||
}
|
||||
+189
@@ -0,0 +1,189 @@
|
||||
{
|
||||
"summary": {
|
||||
"created_at": "2026-07-17T16:18:55.068127Z",
|
||||
"index": "work-classifications",
|
||||
"read_only": true,
|
||||
"expected_count": null,
|
||||
"documents": 45335,
|
||||
"initial_count": 45335,
|
||||
"final_count": 45335,
|
||||
"count_consistent": true,
|
||||
"expected_count_matches": true,
|
||||
"index_integrity_valid": true
|
||||
},
|
||||
"mapping": {
|
||||
"valid": true,
|
||||
"error_count": 0,
|
||||
"errors": []
|
||||
},
|
||||
"documents": {
|
||||
"schema_valid": 45335,
|
||||
"schema_invalid": 0,
|
||||
"field_order_valid": 45335,
|
||||
"field_order_invalid": 0,
|
||||
"unique_work_ids": 45335,
|
||||
"duplicate_work_id_count": 0,
|
||||
"duplicate_work_ids": {},
|
||||
"schema_error_counts": {},
|
||||
"field_order_error_counts": {}
|
||||
},
|
||||
"classification": {
|
||||
"categories": {
|
||||
"basic_research": {
|
||||
"count": 21568,
|
||||
"percentage": 47.57
|
||||
},
|
||||
"applied_research": {
|
||||
"count": 17243,
|
||||
"percentage": 38.03
|
||||
},
|
||||
"non_research": {
|
||||
"count": 3349,
|
||||
"percentage": 7.39
|
||||
},
|
||||
"experimental_development": {
|
||||
"count": 3175,
|
||||
"percentage": 7.0
|
||||
}
|
||||
},
|
||||
"quadrants": {
|
||||
"pure_applied": {
|
||||
"count": 20366,
|
||||
"percentage": 44.92
|
||||
},
|
||||
"use_inspired_basic": {
|
||||
"count": 14137,
|
||||
"percentage": 31.18
|
||||
},
|
||||
"pure_basic": {
|
||||
"count": 7446,
|
||||
"percentage": 16.42
|
||||
},
|
||||
"not_applicable": {
|
||||
"count": 3386,
|
||||
"percentage": 7.47
|
||||
}
|
||||
},
|
||||
"confidence": {
|
||||
"high": {
|
||||
"count": 29475,
|
||||
"percentage": 65.02
|
||||
},
|
||||
"medium": {
|
||||
"count": 15721,
|
||||
"percentage": 34.68
|
||||
},
|
||||
"low": {
|
||||
"count": 139,
|
||||
"percentage": 0.31
|
||||
}
|
||||
},
|
||||
"insufficient_context": {
|
||||
"false": {
|
||||
"count": 42171,
|
||||
"percentage": 93.02
|
||||
},
|
||||
"true": {
|
||||
"count": 3164,
|
||||
"percentage": 6.98
|
||||
}
|
||||
},
|
||||
"signals_used": {
|
||||
"title": 44781,
|
||||
"topics": 44742,
|
||||
"work_type": 42570,
|
||||
"venue": 35578,
|
||||
"abstract": 28450,
|
||||
"funders": 10144,
|
||||
"language": 2043,
|
||||
"year": 61
|
||||
},
|
||||
"applied_orientation_score": {
|
||||
"overall": {
|
||||
"count": 41986,
|
||||
"min": 0.0,
|
||||
"max": 92.0,
|
||||
"mean": 47.49,
|
||||
"median": 38.0
|
||||
},
|
||||
"by_category": {
|
||||
"applied_research": {
|
||||
"count": 17243,
|
||||
"min": 35.0,
|
||||
"max": 90.0,
|
||||
"mean": 67.07,
|
||||
"median": 70.0
|
||||
},
|
||||
"basic_research": {
|
||||
"count": 21568,
|
||||
"min": 0.0,
|
||||
"max": 55.0,
|
||||
"mean": 26.78,
|
||||
"median": 30.0
|
||||
},
|
||||
"experimental_development": {
|
||||
"count": 3175,
|
||||
"min": 60.0,
|
||||
"max": 92.0,
|
||||
"mean": 81.84,
|
||||
"median": 80.0
|
||||
},
|
||||
"non_research": {
|
||||
"count": 0,
|
||||
"min": null,
|
||||
"max": null,
|
||||
"mean": null,
|
||||
"median": null
|
||||
}
|
||||
}
|
||||
},
|
||||
"current_rule_consistency": {
|
||||
"consistent": 45335,
|
||||
"inconsistent": 0,
|
||||
"consistent_percentage": 100.0,
|
||||
"error_counts": {}
|
||||
},
|
||||
"stored_validation": {
|
||||
"states": {
|
||||
"valid": 42138,
|
||||
"invalid": 3197
|
||||
},
|
||||
"valid_state_consistent_with_error_list": 45335,
|
||||
"valid_state_inconsistent_with_error_list": 0,
|
||||
"error_occurrences": 3201,
|
||||
"error_counts": {
|
||||
"applied_research_score_outside_expected_range": 2842,
|
||||
"basic_research_quadrant_score_mismatch": 297,
|
||||
"applied_research_quadrant_mismatch": 32,
|
||||
"experimental_development_quadrant_mismatch": 20,
|
||||
"basic_research_quadrant_mismatch": 9,
|
||||
"experimental_development_score_outside_expected_range": 1
|
||||
}
|
||||
}
|
||||
},
|
||||
"metadata": {
|
||||
"missing_title": 24,
|
||||
"missing_doi": 4579,
|
||||
"missing_publication_year": 0,
|
||||
"empty_authors": 0,
|
||||
"empty_institutions": 10679,
|
||||
"empty_topics": 274,
|
||||
"publication_year": {
|
||||
"min": 1950,
|
||||
"max": 2026
|
||||
},
|
||||
"classified_at": {
|
||||
"min": "2026-07-10T18:42:03Z",
|
||||
"max": "2026-07-17T16:13:02Z"
|
||||
}
|
||||
},
|
||||
"provenance": {
|
||||
"models": {
|
||||
"gemma4-e4b": 45335
|
||||
},
|
||||
"prompt_versions": {
|
||||
"frascati_v1": 45215,
|
||||
"frascati_hard_ranges_v2": 120
|
||||
}
|
||||
}
|
||||
}
|
||||
+181
@@ -0,0 +1,181 @@
|
||||
{
|
||||
"summary": {
|
||||
"created_at": "2026-07-17T17:08:56.145037Z",
|
||||
"index": "work-classifications",
|
||||
"read_only": true,
|
||||
"expected_count": null,
|
||||
"documents": 45335,
|
||||
"initial_count": 45335,
|
||||
"final_count": 45335,
|
||||
"count_consistent": true,
|
||||
"expected_count_matches": true,
|
||||
"index_integrity_valid": true
|
||||
},
|
||||
"mapping": {
|
||||
"valid": true,
|
||||
"error_count": 0,
|
||||
"errors": []
|
||||
},
|
||||
"documents": {
|
||||
"schema_valid": 45335,
|
||||
"schema_invalid": 0,
|
||||
"field_order_valid": 45335,
|
||||
"field_order_invalid": 0,
|
||||
"unique_work_ids": 45335,
|
||||
"duplicate_work_id_count": 0,
|
||||
"duplicate_work_ids": {},
|
||||
"schema_error_counts": {},
|
||||
"field_order_error_counts": {}
|
||||
},
|
||||
"classification": {
|
||||
"categories": {
|
||||
"basic_research": {
|
||||
"count": 21583,
|
||||
"percentage": 47.61
|
||||
},
|
||||
"applied_research": {
|
||||
"count": 16789,
|
||||
"percentage": 37.03
|
||||
},
|
||||
"experimental_development": {
|
||||
"count": 3591,
|
||||
"percentage": 7.92
|
||||
},
|
||||
"non_research": {
|
||||
"count": 3372,
|
||||
"percentage": 7.44
|
||||
}
|
||||
},
|
||||
"quadrants": {
|
||||
"pure_applied": {
|
||||
"count": 20380,
|
||||
"percentage": 44.95
|
||||
},
|
||||
"use_inspired_basic": {
|
||||
"count": 14037,
|
||||
"percentage": 30.96
|
||||
},
|
||||
"pure_basic": {
|
||||
"count": 7546,
|
||||
"percentage": 16.64
|
||||
},
|
||||
"not_applicable": {
|
||||
"count": 3372,
|
||||
"percentage": 7.44
|
||||
}
|
||||
},
|
||||
"confidence": {
|
||||
"high": {
|
||||
"count": 29445,
|
||||
"percentage": 64.95
|
||||
},
|
||||
"medium": {
|
||||
"count": 15749,
|
||||
"percentage": 34.74
|
||||
},
|
||||
"low": {
|
||||
"count": 141,
|
||||
"percentage": 0.31
|
||||
}
|
||||
},
|
||||
"insufficient_context": {
|
||||
"false": {
|
||||
"count": 42248,
|
||||
"percentage": 93.19
|
||||
},
|
||||
"true": {
|
||||
"count": 3087,
|
||||
"percentage": 6.81
|
||||
}
|
||||
},
|
||||
"signals_used": {
|
||||
"title": 44781,
|
||||
"topics": 44739,
|
||||
"work_type": 42631,
|
||||
"venue": 35597,
|
||||
"abstract": 28479,
|
||||
"funders": 10203,
|
||||
"language": 2028,
|
||||
"year": 61
|
||||
},
|
||||
"applied_orientation_score": {
|
||||
"overall": {
|
||||
"count": 41963,
|
||||
"min": 0.0,
|
||||
"max": 92.0,
|
||||
"mean": 46.85,
|
||||
"median": 40.0
|
||||
},
|
||||
"by_category": {
|
||||
"applied_research": {
|
||||
"count": 16789,
|
||||
"min": 40.0,
|
||||
"max": 70.0,
|
||||
"mean": 64.99,
|
||||
"median": 65.0
|
||||
},
|
||||
"basic_research": {
|
||||
"count": 21583,
|
||||
"min": 0.0,
|
||||
"max": 45.0,
|
||||
"mean": 26.9,
|
||||
"median": 30.0
|
||||
},
|
||||
"experimental_development": {
|
||||
"count": 3591,
|
||||
"min": 75.0,
|
||||
"max": 92.0,
|
||||
"mean": 81.97,
|
||||
"median": 80.0
|
||||
},
|
||||
"non_research": {
|
||||
"count": 0,
|
||||
"min": null,
|
||||
"max": null,
|
||||
"mean": null,
|
||||
"median": null
|
||||
}
|
||||
}
|
||||
},
|
||||
"current_rule_consistency": {
|
||||
"consistent": 45335,
|
||||
"inconsistent": 0,
|
||||
"consistent_percentage": 100.0,
|
||||
"error_counts": {}
|
||||
},
|
||||
"stored_validation": {
|
||||
"states": {
|
||||
"valid": 45335
|
||||
},
|
||||
"valid_state_consistent_with_error_list": 45335,
|
||||
"valid_state_inconsistent_with_error_list": 0,
|
||||
"error_occurrences": 0,
|
||||
"error_counts": {}
|
||||
}
|
||||
},
|
||||
"metadata": {
|
||||
"missing_title": 24,
|
||||
"missing_doi": 4579,
|
||||
"missing_publication_year": 0,
|
||||
"empty_authors": 0,
|
||||
"empty_institutions": 10679,
|
||||
"empty_topics": 274,
|
||||
"publication_year": {
|
||||
"min": 1950,
|
||||
"max": 2026
|
||||
},
|
||||
"classified_at": {
|
||||
"min": "2026-07-10T18:42:03Z",
|
||||
"max": "2026-07-17T17:05:32Z"
|
||||
}
|
||||
},
|
||||
"provenance": {
|
||||
"models": {
|
||||
"gemma4-e4b": 45335
|
||||
},
|
||||
"prompt_versions": {
|
||||
"frascati_v1": 42018,
|
||||
"frascati_hard_ranges_v2": 3317
|
||||
}
|
||||
}
|
||||
}
|
||||
+181
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
-1227
File diff suppressed because it is too large
Load Diff
+3723
File diff suppressed because it is too large
Load Diff
+1143
File diff suppressed because it is too large
Load Diff
+44343
File diff suppressed because it is too large
Load Diff
+44343
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,243 +0,0 @@
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5075663980",
|
||||
"display_name": "Ursula Neumann"
|
||||
},
|
||||
"config": {
|
||||
"base_url": "https://project.nes.uni-due.de/llm2/v1/",
|
||||
"model": "gemma4-e4b",
|
||||
"prompt_file": "prompt_frascati.txt",
|
||||
"classification_data_dir": "classification_data",
|
||||
"output_dir": "llm_results",
|
||||
"temperature": 0,
|
||||
"max_tokens": 2048,
|
||||
"top_p": 1.0,
|
||||
"top_k": 64,
|
||||
"max_workers": 10,
|
||||
"skip_if_already_exists": true,
|
||||
"response_format": "json_schema",
|
||||
"schema_name": "frascati_research_orientation",
|
||||
"strict_schema": true
|
||||
},
|
||||
"summary": {
|
||||
"works_total": 4,
|
||||
"parsed_ok": 4,
|
||||
"api_errors": 0,
|
||||
"validation_errors": 0,
|
||||
"usage": {
|
||||
"prompt_tokens": 12867,
|
||||
"uncached_prompt_tokens": 1219,
|
||||
"completion_tokens": 3531,
|
||||
"real_total_usage": 4750
|
||||
},
|
||||
"average_usage_per_work": {
|
||||
"prompt_tokens": 3216.75,
|
||||
"uncached_prompt_tokens": 304.75,
|
||||
"completion_tokens": 882.75,
|
||||
"real_total_usage": 1187.5
|
||||
},
|
||||
"duration_seconds_sum_of_requests": 58.649,
|
||||
"average_duration_seconds_per_work": 14.662
|
||||
},
|
||||
"results": [
|
||||
{
|
||||
"work_id": "https://openalex.org/W7125710157",
|
||||
"doi": "https://doi.org/10.1055/s-0045-1814333",
|
||||
"input": {
|
||||
"title": "GALAD Score predicts Recurrence Risk and Mortality after Curative Resection of Hepatocellular Carcinoma",
|
||||
"abstract": null,
|
||||
"venue": "Zeitschrift für Gastroenterologie",
|
||||
"work_type": "article",
|
||||
"topics": [
|
||||
"Liver Disease Diagnosis and Treatment",
|
||||
"Epidemiology",
|
||||
"Medicine",
|
||||
"Peptidase Inhibition and Analysis",
|
||||
"Oncology",
|
||||
"Hepatocellular Carcinoma Treatment and Prognosis",
|
||||
"Hepatology",
|
||||
"Hepatocellular carcinoma"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2026,
|
||||
"language": null
|
||||
},
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 70,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "venue", "topics", "work_type"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The title indicates the development and validation of a predictive score (GALAD Score) for a specific clinical aim (risk/mortality prediction)."
|
||||
},
|
||||
"llm_debug": {
|
||||
"status": "ok",
|
||||
"content": "{\n \"primary_category\": \"applied_research\",\n \"applied_orientation_score\": 70,\n \"pasteur_quadrant\": \"pure_applied\",\n \"confidence\": \"medium\",\n \"signals_used\": [\n \"title\",\n \"venue\",\n \"topics\",\n \"work_type\"\n ],\n \"insufficient_context\": false,\n \"rationale\": \"The title indicates the development and validation of a predictive score (GALAD Score) for a specific clinical aim (risk/mortality prediction).\"\n}",
|
||||
"finish_reason": "stop",
|
||||
"duration_seconds": 11.818,
|
||||
"attempt_count": 1,
|
||||
"attempt_errors": [],
|
||||
"usage": {
|
||||
"prompt_tokens": 3093,
|
||||
"uncached_prompt_tokens": 181,
|
||||
"completion_tokens": 711,
|
||||
"real_total_usage": 892
|
||||
},
|
||||
"error": null,
|
||||
"validation_errors": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "https://openalex.org/W4409704961",
|
||||
"doi": "https://doi.org/10.1007/978-3-658-46233-8_10",
|
||||
"input": {
|
||||
"title": "Multiprofessionelle Kooperation und Schulabsentismus: Theoriezugänge und Befunde aus Sicht der Kinder- und Jugendpsychiatrie",
|
||||
"abstract": null,
|
||||
"venue": "Absentismus und Dropout",
|
||||
"work_type": "book-chapter",
|
||||
"topics": [
|
||||
"Youth Substance Use and School Attendance",
|
||||
"Education",
|
||||
"Social Sciences",
|
||||
"Child and Adolescent Psychosocial and Emotional Development",
|
||||
"Clinical Psychology",
|
||||
"Psychology",
|
||||
"Early Childhood Education and Development",
|
||||
"Political science"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2025,
|
||||
"language": "de"
|
||||
},
|
||||
"classification": {
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 35,
|
||||
"pasteur_quadrant": "use_inspired_basic",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "venue", "topics", "work_type"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The title indicates a theoretical review of findings regarding school absenteeism, fitting the use-inspired basic research model."
|
||||
},
|
||||
"llm_debug": {
|
||||
"status": "ok",
|
||||
"content": "{\n \"primary_category\": \"basic_research\",\n \"applied_orientation_score\": 35,\n \"pasteur_quadrant\": \"use_inspired_basic\",\n \"confidence\": \"medium\",\n \"signals_used\": [\n \"title\",\n \"venue\",\n \"topics\",\n \"work_type\"\n ],\n \"insufficient_context\": false,\n \"rationale\": \"The title indicates a theoretical review of findings regarding school absenteeism, fitting the use-inspired basic research model.\"\n}",
|
||||
"finish_reason": "stop",
|
||||
"duration_seconds": 15.485,
|
||||
"attempt_count": 1,
|
||||
"attempt_errors": [],
|
||||
"usage": {
|
||||
"prompt_tokens": 3104,
|
||||
"uncached_prompt_tokens": 192,
|
||||
"completion_tokens": 933,
|
||||
"real_total_usage": 1125
|
||||
},
|
||||
"error": null,
|
||||
"validation_errors": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "https://openalex.org/W4283385417",
|
||||
"doi": "https://doi.org/10.1024/1422-4917/a000884",
|
||||
"input": {
|
||||
"title": "Verlauf von Schulabsentismus 1.5 bis 3 Jahre nach Erstvorstellung: Prädiktoren, psychosoziales Funktionsniveau und Inanspruchnahme von Hilfen",
|
||||
"abstract": "Course of School Absenteeism 1.5-3 Years After Initial Evaluation: Symptoms, Psychosocial Functioning, and Help-Seeking Behavior <b>Abstract.</b> <i>Objective:</i> To explore the course of patients with school absenteeism 1.5-3 years after their initial evaluation, including symptoms, school attendance, psychosocial functioning, and help-seeking behavior. <i>Method:</i> Of the 237 patients from specialized psychiatric units for youths displaying school absenteeism, we successfully contacted 108 of them 1.5-3 years after initial admission. We conducted a telephone interview with their parents (SDQ, school situation, help-seeking behavior). Among others, we analyzed the extent of school absenteeism, the scales of the Inventory of School Attendance Problems (ISAP; Knollmann et al., 2019), and the quality of school absenteeism (school refusal vs. truancy vs. mixed group) at admission as possible predictors. <i>Results:</i> The patients had received an extensive amount of youth-welfare measures and inpatient, daycare, and outpatient therapy. 46.3 % had elevated values in the SDQ total score at follow-up, mostly because of emotional problems or problems with peers. Psychosocial functioning, including school attendance, was described as poor for only about 30 %. School attendance problems were significantly predicted by having a conduct disorder and elevated scores on the ISAP-scales Aggression, Teacher Problems, and Peer Problems, though the effect sizes were weak. <i>Conclusions:</i> Externalizing symptoms and associated psychosocial problems seem to be predictive of a negative course of school absenteeism. Implications for prospective longitudinal studies are discussed.",
|
||||
"venue": "Zeitschrift für Kinder- und Jugendpsychiatrie und Psychotherapie",
|
||||
"work_type": "article",
|
||||
"topics": [
|
||||
"Youth Substance Use and School Attendance",
|
||||
"Education",
|
||||
"Social Sciences",
|
||||
"Child and Adolescent Psychosocial and Emotional Development",
|
||||
"Clinical Psychology",
|
||||
"Psychology",
|
||||
"Educational and Psychological Assessments",
|
||||
"Developmental and Educational Psychology"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2022,
|
||||
"language": "de"
|
||||
},
|
||||
"classification": {
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 30,
|
||||
"pasteur_quadrant": "use_inspired_basic",
|
||||
"confidence": "high",
|
||||
"signals_used": [
|
||||
"title",
|
||||
"abstract",
|
||||
"venue",
|
||||
"topics",
|
||||
"work_type",
|
||||
"language"
|
||||
],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The study explores the course and predictors of a phenomenon (school absenteeism), aiming for fundamental knowledge, despite having clinical implications."
|
||||
},
|
||||
"llm_debug": {
|
||||
"status": "ok",
|
||||
"content": "{\n \"primary_category\": \"basic_research\",\n \"applied_orientation_score\": 30,\n \"pasteur_quadrant\": \"use_inspired_basic\",\n \"confidence\": \"high\",\n \"signals_used\": [\n \"title\",\n \"abstract\",\n \"venue\",\n \"topics\",\n \"work_type\",\n \"language\"\n ],\n \"insufficient_context\": false,\n \"rationale\": \"The study explores the course and predictors of a phenomenon (school absenteeism), aiming for fundamental knowledge, despite having clinical implications.\"\n}",
|
||||
"finish_reason": "stop",
|
||||
"duration_seconds": 17.212,
|
||||
"attempt_count": 1,
|
||||
"attempt_errors": [],
|
||||
"usage": {
|
||||
"prompt_tokens": 3476,
|
||||
"uncached_prompt_tokens": 564,
|
||||
"completion_tokens": 1037,
|
||||
"real_total_usage": 1601
|
||||
},
|
||||
"error": null,
|
||||
"validation_errors": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "https://openalex.org/W4283385776",
|
||||
"doi": "https://doi.org/10.1024/1422-4917/a000882",
|
||||
"input": {
|
||||
"title": "Stationäre Schematherapie bei Schulvermeidung – ein Fallbeispiel",
|
||||
"abstract": "Inpatient Schema Therapy for School Avoidance - A Case Study <b>Abstract.</b> After a short overview of the basic concepts and methods of schema therapy, we report a case study on the inpatient treatment of a 16-year-old youth with depression and chronic school avoidance. The scores on the Schema inventories and Depression questionnaires are compared before vs. after the treatment, and we then discuss the opportunities and limitations of schema therapy with school-avoiding youths.",
|
||||
"venue": "Zeitschrift für Kinder- und Jugendpsychiatrie und Psychotherapie",
|
||||
"work_type": "article",
|
||||
"topics": [
|
||||
"Youth Substance Use and School Attendance",
|
||||
"Education",
|
||||
"Social Sciences",
|
||||
"Child and Adolescent Psychosocial and Emotional Development",
|
||||
"Clinical Psychology",
|
||||
"Psychology",
|
||||
"Educational and Psychological Assessments",
|
||||
"Developmental and Educational Psychology"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2022,
|
||||
"language": "de"
|
||||
},
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 70,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics", "work_type"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The abstract reports a case study applying a specific therapy to treat a defined clinical problem (school avoidance), meeting the criteria for applied research."
|
||||
},
|
||||
"llm_debug": {
|
||||
"status": "ok",
|
||||
"content": "{\n \"primary_category\": \"applied_research\",\n \"applied_orientation_score\": 70,\n \"pasteur_quadrant\": \"pure_applied\",\n \"confidence\": \"high\",\n \"signals_used\": [\n \"title\",\n \"abstract\",\n \"venue\",\n \"topics\",\n \"work_type\"\n ],\n \"insufficient_context\": false,\n \"rationale\": \"The abstract reports a case study applying a specific therapy to treat a defined clinical problem (school avoidance), meeting the criteria for applied research.\"\n}",
|
||||
"finish_reason": "stop",
|
||||
"duration_seconds": 14.134,
|
||||
"attempt_count": 1,
|
||||
"attempt_errors": [],
|
||||
"usage": {
|
||||
"prompt_tokens": 3194,
|
||||
"uncached_prompt_tokens": 282,
|
||||
"completion_tokens": 850,
|
||||
"real_total_usage": 1132
|
||||
},
|
||||
"error": null,
|
||||
"validation_errors": []
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,337 +0,0 @@
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5093075883",
|
||||
"display_name": "Arman Arzani"
|
||||
},
|
||||
"config": {
|
||||
"base_url": "https://project.nes.uni-due.de/llm2/v1/",
|
||||
"model": "gemma4-e4b",
|
||||
"prompt_file": "prompt_frascati.txt",
|
||||
"classification_data_dir": "classification_data",
|
||||
"output_dir": "llm_results",
|
||||
"temperature": 0,
|
||||
"max_tokens": 2048,
|
||||
"top_p": 1.0,
|
||||
"top_k": 64,
|
||||
"max_workers": 10,
|
||||
"skip_if_already_exists": true,
|
||||
"response_format": "json_schema",
|
||||
"schema_name": "frascati_research_orientation",
|
||||
"strict_schema": true
|
||||
},
|
||||
"summary": {
|
||||
"works_total": 6,
|
||||
"parsed_ok": 4,
|
||||
"api_errors": 0,
|
||||
"validation_errors": 2,
|
||||
"usage": {
|
||||
"prompt_tokens": 18992,
|
||||
"uncached_prompt_tokens": 368,
|
||||
"completion_tokens": 4790,
|
||||
"real_total_usage": 5158
|
||||
},
|
||||
"average_usage_per_work": {
|
||||
"prompt_tokens": 3165.33,
|
||||
"uncached_prompt_tokens": 61.33,
|
||||
"completion_tokens": 798.33,
|
||||
"real_total_usage": 859.67
|
||||
},
|
||||
"duration_seconds_sum_of_requests": 80.141,
|
||||
"average_duration_seconds_per_work": 13.357
|
||||
},
|
||||
"results": [
|
||||
{
|
||||
"work_id": "https://openalex.org/W4415655215",
|
||||
"doi": "https://doi.org/10.5220/0013658600004000",
|
||||
"input": {
|
||||
"title": "A Hybrid Approach for Mining the Organizational Structure from University Websites",
|
||||
"abstract": null,
|
||||
"venue": null,
|
||||
"work_type": "article",
|
||||
"topics": [
|
||||
"Data Mining Algorithms and Applications",
|
||||
"Information Systems",
|
||||
"Computer Science",
|
||||
"Advanced Text Analysis Techniques",
|
||||
"Artificial Intelligence",
|
||||
"Web visibility and informetrics",
|
||||
"Organizational structure",
|
||||
"Knowledge management"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2025,
|
||||
"language": null
|
||||
},
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 60,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "topics", "work_type"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The title and topics indicate the application of a specific data mining approach to solve a practical information systems problem."
|
||||
},
|
||||
"llm_debug": {
|
||||
"status": "ok",
|
||||
"content": "{\n \"primary_category\": \"applied_research\",\n \"applied_orientation_score\": 60,\n \"pasteur_quadrant\": \"pure_applied\",\n \"confidence\": \"medium\",\n \"signals_used\": [\n \"title\",\n \"topics\",\n \"work_type\"\n ],\n \"insufficient_context\": false,\n \"rationale\": \"The title and topics indicate the application of a specific data mining approach to solve a practical information systems problem.\"\n}",
|
||||
"finish_reason": "stop",
|
||||
"duration_seconds": 11.397,
|
||||
"attempt_count": 1,
|
||||
"attempt_errors": [],
|
||||
"usage": {
|
||||
"prompt_tokens": 3074,
|
||||
"uncached_prompt_tokens": 2,
|
||||
"completion_tokens": 697,
|
||||
"real_total_usage": 699
|
||||
},
|
||||
"error": null,
|
||||
"validation_errors": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "https://openalex.org/W4402284842",
|
||||
"doi": "https://doi.org/10.2139/ssrn.4947351",
|
||||
"input": {
|
||||
"title": "Ai-Based Pattern Recognition in Limited, Unstructured Information: Improving Joint Value Creation in Mobility as a Service",
|
||||
"abstract": null,
|
||||
"venue": "SSRN Electronic Journal",
|
||||
"work_type": "preprint",
|
||||
"topics": [
|
||||
"Big Data and Business Intelligence",
|
||||
"Management Information Systems",
|
||||
"Business, Management and Accounting",
|
||||
"Customer churn and segmentation",
|
||||
"Marketing",
|
||||
"Semantic Web and Ontologies",
|
||||
"Artificial Intelligence",
|
||||
"Computer Science"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2024,
|
||||
"language": "en"
|
||||
},
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 70,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "topics", "venue", "work_type"],
|
||||
"insufficient_context": true,
|
||||
"classification_reason": "The title specifies a practical objective: improving joint value creation in Mobility as a Service using AI pattern recognition."
|
||||
},
|
||||
"llm_debug": {
|
||||
"status": "ok",
|
||||
"content": "{\n \"primary_category\": \"applied_research\",\n \"applied_orientation_score\": 70,\n \"pasteur_quadrant\": \"pure_applied\",\n \"confidence\": \"medium\",\n \"signals_used\": [\n \"title\",\n \"topics\",\n \"venue\",\n \"work_type\"\n ],\n \"insufficient_context\": true,\n \"rationale\": \"The title specifies a practical objective: improving joint value creation in Mobility as a Service using AI pattern recognition.\"\n}",
|
||||
"finish_reason": "stop",
|
||||
"duration_seconds": 13.283,
|
||||
"attempt_count": 1,
|
||||
"attempt_errors": [],
|
||||
"usage": {
|
||||
"prompt_tokens": 3094,
|
||||
"uncached_prompt_tokens": 22,
|
||||
"completion_tokens": 796,
|
||||
"real_total_usage": 818
|
||||
},
|
||||
"error": null,
|
||||
"validation_errors": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "https://openalex.org/W4403369135",
|
||||
"doi": "https://doi.org/10.1007/s41060-024-00663-1",
|
||||
"input": {
|
||||
"title": "Discovering potential founders within academic institutions",
|
||||
"abstract": "Abstract Technology transfer is central to the development of an iconic entrepreneurial university. To foster knowledge transfer, many universities undergo a scouting process by their innovation coaches. The goal is to find staff members and students, who have the knowledge, expertise, and the potential to found startups by transforming their research results into a product. Since there is no systematic approach to measure the innovation potential of university members based on their academic activities, the scouting process is typically subjective and relies heavily on the experience of the innovation coaches. In this paper, we study the discovery of potential founders to support the scouting process using a data-driven approach. We create a novel data set by integrating the founder profiles with the academic activities from 8 universities across 5 countries. We explain the process of data integration as well as feature engineering. By applying machine learning methods, we investigate the classification accuracy of founders based on their academic background. Our analysis shows that using a random forest (RF), it is possible to differentiate founders and non-founders with an average accuracy of 79%. This accuracy remains mostly stable when applying an RF trained on one university to another, suggesting the existence of a generic founder profile. The detailed analysis indicates a high significance of the career path as well as patent- and grant-related features among others. Furthermore, we show that using a RF, it is possible to exploit these features to predict the future founding probability up to 3 years in advance with an accuracy of 80%. Finally, by analyzing the academic disciplines of founders we show that the patent documents have more influence on the startup’s core orientation than the publications.",
|
||||
"venue": "International Journal of Data Science and Analytics",
|
||||
"work_type": "article",
|
||||
"topics": [
|
||||
"Entrepreneurship Studies and Influences",
|
||||
"Management of Technology and Innovation",
|
||||
"Business, Management and Accounting",
|
||||
"Genetics, Bioinformatics, and Biomedical Research",
|
||||
"Molecular Biology",
|
||||
"Biochemistry, Genetics and Molecular Biology",
|
||||
"Biomedical and Engineering Education",
|
||||
"Biomedical Engineering"
|
||||
],
|
||||
"funders": [
|
||||
"Bundesministerium für Wirtschaft und Energie",
|
||||
"Universität Duisburg-Essen"
|
||||
],
|
||||
"year": 2024,
|
||||
"language": "en"
|
||||
},
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 75,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": [
|
||||
"title",
|
||||
"abstract",
|
||||
"venue",
|
||||
"topics",
|
||||
"funders",
|
||||
"work_type"
|
||||
],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The abstract defines a specific practical aim: supporting the university scouting process by developing a data-driven prediction model."
|
||||
},
|
||||
"llm_debug": {
|
||||
"status": "ok",
|
||||
"content": "{\n \"primary_category\": \"applied_research\",\n \"applied_orientation_score\": 75,\n \"pasteur_quadrant\": \"pure_applied\",\n \"confidence\": \"high\",\n \"signals_used\": [\n \"title\",\n \"abstract\",\n \"venue\",\n \"topics\",\n \"funders\",\n \"work_type\"\n ],\n \"insufficient_context\": false,\n \"rationale\": \"The abstract defines a specific practical aim: supporting the university scouting process by developing a data-driven prediction model.\"\n}",
|
||||
"finish_reason": "stop",
|
||||
"duration_seconds": 17.107,
|
||||
"attempt_count": 1,
|
||||
"attempt_errors": [],
|
||||
"usage": {
|
||||
"prompt_tokens": 3442,
|
||||
"uncached_prompt_tokens": 18,
|
||||
"completion_tokens": 1022,
|
||||
"real_total_usage": 1040
|
||||
},
|
||||
"error": null,
|
||||
"validation_errors": ["applied_research_score_outside_expected_range"]
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "https://openalex.org/W4387698137",
|
||||
"doi": "https://doi.org/10.1145/3603765.3603774",
|
||||
"input": {
|
||||
"title": "Exploiting Topic Modelling for the Identification of Untapped Scientific Collaborations",
|
||||
"abstract": "Finding potential collaborators has become a challenge due to the growing number of scientists in organizations such as universities, research institutes, or companies. Collaboration Recommendation Systems (CRSs) have been developed to help researchers identify possible collaboration partners, but they often rely on citation graphs or paper abstracts which may not be readily available in organizational databases or online sources. However, scientific publication titles provide consistent bibliometric data that can provide insights into research areas. TOMOSCO is a topic modelling framework that uses transformer-based methods to extract research area information from small amounts of text, such as publication titles or brief project descriptions. TOMOSCO can classify, cluster, and match research topics across different disciplines, uncovering relationships among scientists and suggesting potential interdisciplinary collaborations. In experiments, TOMOSCO was able to identify existing collaborations with over 90% accuracy based solely on publication titles and propose new collaborations based on previously unseen publications and project descriptions.",
|
||||
"venue": null,
|
||||
"work_type": "article",
|
||||
"topics": [
|
||||
"Topic Modeling",
|
||||
"Artificial Intelligence",
|
||||
"Computer Science",
|
||||
"Complex Network Analysis Techniques",
|
||||
"Statistical and Nonlinear Physics",
|
||||
"Physics and Astronomy",
|
||||
"Computational and Text Analysis Methods",
|
||||
"General Social Sciences"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2023,
|
||||
"language": "en"
|
||||
},
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 75,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "topics", "work_type"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The abstract describes developing and testing TOMOSCO, a framework aimed at solving the specific practical problem of identifying untapped scientific collaborations."
|
||||
},
|
||||
"llm_debug": {
|
||||
"status": "ok",
|
||||
"content": "{\n \"primary_category\": \"applied_research\",\n \"applied_orientation_score\": 75,\n \"pasteur_quadrant\": \"pure_applied\",\n \"confidence\": \"high\",\n \"signals_used\": [\n \"title\",\n \"abstract\",\n \"topics\",\n \"work_type\"\n ],\n \"insufficient_context\": false,\n \"rationale\": \"The abstract describes developing and testing TOMOSCO, a framework aimed at solving the specific practical problem of identifying untapped scientific collaborations.\"\n}",
|
||||
"finish_reason": "stop",
|
||||
"duration_seconds": 12.803,
|
||||
"attempt_count": 1,
|
||||
"attempt_errors": [],
|
||||
"usage": {
|
||||
"prompt_tokens": 3261,
|
||||
"uncached_prompt_tokens": 29,
|
||||
"completion_tokens": 760,
|
||||
"real_total_usage": 789
|
||||
},
|
||||
"error": null,
|
||||
"validation_errors": ["applied_research_score_outside_expected_range"]
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "https://openalex.org/W4388860852",
|
||||
"doi": "https://doi.org/10.5220/0012156200003598",
|
||||
"input": {
|
||||
"title": "Discovering Potential Founders Based on Academic Background",
|
||||
"abstract": null,
|
||||
"venue": null,
|
||||
"work_type": "article",
|
||||
"topics": [
|
||||
"Education and Critical Thinking Development",
|
||||
"Education",
|
||||
"Social Sciences",
|
||||
"Computer science",
|
||||
"Data science"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2023,
|
||||
"language": "en"
|
||||
},
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 60,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "topics", "work_type"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The title indicates a specific practical aim: identifying potential founders using academic background and data science."
|
||||
},
|
||||
"llm_debug": {
|
||||
"status": "ok",
|
||||
"content": "{\n \"primary_category\": \"applied_research\",\n \"applied_orientation_score\": 60,\n \"pasteur_quadrant\": \"pure_applied\",\n \"confidence\": \"medium\",\n \"signals_used\": [\n \"title\",\n \"topics\",\n \"work_type\"\n ],\n \"insufficient_context\": false,\n \"rationale\": \"The title indicates a specific practical aim: identifying potential founders using academic background and data science.\"\n}",
|
||||
"finish_reason": "stop",
|
||||
"duration_seconds": 13.181,
|
||||
"attempt_count": 1,
|
||||
"attempt_errors": [],
|
||||
"usage": {
|
||||
"prompt_tokens": 3048,
|
||||
"uncached_prompt_tokens": 136,
|
||||
"completion_tokens": 782,
|
||||
"real_total_usage": 918
|
||||
},
|
||||
"error": null,
|
||||
"validation_errors": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "https://openalex.org/W4388877173",
|
||||
"doi": "https://doi.org/10.5220/0012263100003598",
|
||||
"input": {
|
||||
"title": "Challenges in Implementing a University-Based Innovation Search Engine",
|
||||
"abstract": null,
|
||||
"venue": "Universitätsbibliographie, Universität Duisburg-Essen",
|
||||
"work_type": "article",
|
||||
"topics": [
|
||||
"Big Data and Business Intelligence",
|
||||
"Management Information Systems",
|
||||
"Business, Management and Accounting",
|
||||
"Computer science",
|
||||
"Search engine",
|
||||
"World Wide Web"
|
||||
],
|
||||
"funders": [],
|
||||
"year": 2023,
|
||||
"language": "en"
|
||||
},
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 65,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "venue", "topics", "work_type"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The title and topics indicate an investigation into the practical challenges of implementing a specific, useful system (Innovation Search Engine)."
|
||||
},
|
||||
"llm_debug": {
|
||||
"status": "ok",
|
||||
"content": "{\n \"primary_category\": \"applied_research\",\n \"applied_orientation_score\": 65,\n \"pasteur_quadrant\": \"pure_applied\",\n \"confidence\": \"medium\",\n \"signals_used\": [\n \"title\",\n \"venue\",\n \"topics\",\n \"work_type\"\n ],\n \"insufficient_context\": false,\n \"rationale\": \"The title and topics indicate an investigation into the practical challenges of implementing a specific, useful system (Innovation Search Engine).\"\n}",
|
||||
"finish_reason": "stop",
|
||||
"duration_seconds": 12.37,
|
||||
"attempt_count": 1,
|
||||
"attempt_errors": [],
|
||||
"usage": {
|
||||
"prompt_tokens": 3073,
|
||||
"uncached_prompt_tokens": 161,
|
||||
"completion_tokens": 733,
|
||||
"real_total_usage": 894
|
||||
},
|
||||
"error": null,
|
||||
"validation_errors": []
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,285 +0,0 @@
|
||||
{
|
||||
"config": {
|
||||
"base_url": "https://project.nes.uni-due.de/llm2/v1/",
|
||||
"model": "gemma4-e4b",
|
||||
"prompt_file": "prompt_frascati.txt",
|
||||
"classification_data_dir": "classification_data",
|
||||
"output_dir": "llm_results",
|
||||
"max_workers": 10,
|
||||
"skip_if_already_exists": true
|
||||
},
|
||||
"summary": {
|
||||
"persons_total": 8,
|
||||
"persons_skipped": 7,
|
||||
"works_total": 612,
|
||||
"works_reused": 582,
|
||||
"works_requested": 30,
|
||||
"parsed_ok": 607,
|
||||
"api_errors": 0,
|
||||
"validation_errors": 5,
|
||||
"usage": {
|
||||
"prompt_tokens": 1564344,
|
||||
"uncached_prompt_tokens": 1360056,
|
||||
"completion_tokens": 551417,
|
||||
"real_total_usage": 1911473
|
||||
},
|
||||
"average_usage_per_work": {
|
||||
"prompt_tokens": 2556.12,
|
||||
"uncached_prompt_tokens": 2222.31,
|
||||
"completion_tokens": 901.01,
|
||||
"real_total_usage": 3123.32
|
||||
},
|
||||
"duration_seconds_sum_of_requests": 9350.194,
|
||||
"average_duration_seconds_per_work": 15.278
|
||||
},
|
||||
"persons": [
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5035144962",
|
||||
"display_name": "Christine Arentz"
|
||||
},
|
||||
"source_file": "classification_data/A5035144962.json",
|
||||
"output_file": "llm_results/A5035144962_results.json",
|
||||
"summary": {
|
||||
"works_total": 30,
|
||||
"parsed_ok": 28,
|
||||
"api_errors": 0,
|
||||
"validation_errors": 2,
|
||||
"usage": {
|
||||
"prompt_tokens": 96289,
|
||||
"uncached_prompt_tokens": 10369,
|
||||
"completion_tokens": 27789,
|
||||
"real_total_usage": 38158
|
||||
},
|
||||
"average_usage_per_work": {
|
||||
"prompt_tokens": 3209.63,
|
||||
"uncached_prompt_tokens": 345.63,
|
||||
"completion_tokens": 926.3,
|
||||
"real_total_usage": 1271.93
|
||||
},
|
||||
"duration_seconds_sum_of_requests": 492.874,
|
||||
"average_duration_seconds_per_work": 16.429
|
||||
},
|
||||
"skipped": true,
|
||||
"works_reused": 30,
|
||||
"works_requested": 0
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5048213587",
|
||||
"display_name": "Frederik Ahlemann"
|
||||
},
|
||||
"source_file": "classification_data/A5048213587.json",
|
||||
"output_file": "llm_results/A5048213587_results.json",
|
||||
"summary": {
|
||||
"works_total": 171,
|
||||
"parsed_ok": 171,
|
||||
"api_errors": 0,
|
||||
"validation_errors": 0,
|
||||
"usage": {
|
||||
"prompt_tokens": 411263,
|
||||
"uncached_prompt_tokens": 411263,
|
||||
"completion_tokens": 154527,
|
||||
"real_total_usage": 565790
|
||||
},
|
||||
"average_usage_per_work": {
|
||||
"prompt_tokens": 2405.05,
|
||||
"uncached_prompt_tokens": 2405.05,
|
||||
"completion_tokens": 903.67,
|
||||
"real_total_usage": 3308.71
|
||||
},
|
||||
"duration_seconds_sum_of_requests": 2600.951,
|
||||
"average_duration_seconds_per_work": 15.21
|
||||
},
|
||||
"skipped": true,
|
||||
"works_reused": 171,
|
||||
"works_requested": 0
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5058038339",
|
||||
"display_name": "Pascal Dreher"
|
||||
},
|
||||
"source_file": "classification_data/A5058038339.json",
|
||||
"output_file": "llm_results/A5058038339_results.json",
|
||||
"summary": {
|
||||
"works_total": 30,
|
||||
"parsed_ok": 30,
|
||||
"api_errors": 0,
|
||||
"validation_errors": 0,
|
||||
"usage": {
|
||||
"prompt_tokens": 98341,
|
||||
"uncached_prompt_tokens": 10245,
|
||||
"completion_tokens": 26388,
|
||||
"real_total_usage": 36633
|
||||
},
|
||||
"average_usage_per_work": {
|
||||
"prompt_tokens": 3278.03,
|
||||
"uncached_prompt_tokens": 341.5,
|
||||
"completion_tokens": 879.6,
|
||||
"real_total_usage": 1221.1
|
||||
},
|
||||
"duration_seconds_sum_of_requests": 472.658,
|
||||
"average_duration_seconds_per_work": 15.755
|
||||
},
|
||||
"skipped": false,
|
||||
"works_reused": 0,
|
||||
"works_requested": 30
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5075352419",
|
||||
"display_name": "Markus Winterer"
|
||||
},
|
||||
"source_file": "classification_data/A5075352419.json",
|
||||
"output_file": "llm_results/A5075352419_results.json",
|
||||
"summary": {
|
||||
"works_total": 150,
|
||||
"parsed_ok": 149,
|
||||
"api_errors": 0,
|
||||
"validation_errors": 1,
|
||||
"usage": {
|
||||
"prompt_tokens": 368720,
|
||||
"uncached_prompt_tokens": 368720,
|
||||
"completion_tokens": 132353,
|
||||
"real_total_usage": 501073
|
||||
},
|
||||
"average_usage_per_work": {
|
||||
"prompt_tokens": 2458.13,
|
||||
"uncached_prompt_tokens": 2458.13,
|
||||
"completion_tokens": 882.35,
|
||||
"real_total_usage": 3340.49
|
||||
},
|
||||
"duration_seconds_sum_of_requests": 2226.125,
|
||||
"average_duration_seconds_per_work": 14.841
|
||||
},
|
||||
"skipped": true,
|
||||
"works_reused": 150,
|
||||
"works_requested": 0
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5075663980",
|
||||
"display_name": "Ursula Neumann"
|
||||
},
|
||||
"source_file": "classification_data/A5075663980.json",
|
||||
"output_file": "llm_results/A5075663980_results.json",
|
||||
"summary": {
|
||||
"works_total": 4,
|
||||
"parsed_ok": 4,
|
||||
"api_errors": 0,
|
||||
"validation_errors": 0,
|
||||
"usage": {
|
||||
"prompt_tokens": 12867,
|
||||
"uncached_prompt_tokens": 1219,
|
||||
"completion_tokens": 3531,
|
||||
"real_total_usage": 4750
|
||||
},
|
||||
"average_usage_per_work": {
|
||||
"prompt_tokens": 3216.75,
|
||||
"uncached_prompt_tokens": 304.75,
|
||||
"completion_tokens": 882.75,
|
||||
"real_total_usage": 1187.5
|
||||
},
|
||||
"duration_seconds_sum_of_requests": 58.649,
|
||||
"average_duration_seconds_per_work": 14.662
|
||||
},
|
||||
"skipped": true,
|
||||
"works_reused": 4,
|
||||
"works_requested": 0
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5088184531",
|
||||
"display_name": "Alf Kimms"
|
||||
},
|
||||
"source_file": "classification_data/A5088184531.json",
|
||||
"output_file": "llm_results/A5088184531_results.json",
|
||||
"summary": {
|
||||
"works_total": 86,
|
||||
"parsed_ok": 86,
|
||||
"api_errors": 0,
|
||||
"validation_errors": 0,
|
||||
"usage": {
|
||||
"prompt_tokens": 217185,
|
||||
"uncached_prompt_tokens": 217185,
|
||||
"completion_tokens": 73706,
|
||||
"real_total_usage": 290891
|
||||
},
|
||||
"average_usage_per_work": {
|
||||
"prompt_tokens": 2525.41,
|
||||
"uncached_prompt_tokens": 2525.41,
|
||||
"completion_tokens": 857.05,
|
||||
"real_total_usage": 3382.45
|
||||
},
|
||||
"duration_seconds_sum_of_requests": 1245.584,
|
||||
"average_duration_seconds_per_work": 14.484
|
||||
},
|
||||
"skipped": true,
|
||||
"works_reused": 86,
|
||||
"works_requested": 0
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5089242868",
|
||||
"display_name": "Lucas Davi"
|
||||
},
|
||||
"source_file": "classification_data/A5089242868.json",
|
||||
"output_file": "llm_results/A5089242868_results.json",
|
||||
"summary": {
|
||||
"works_total": 135,
|
||||
"parsed_ok": 135,
|
||||
"api_errors": 0,
|
||||
"validation_errors": 0,
|
||||
"usage": {
|
||||
"prompt_tokens": 340687,
|
||||
"uncached_prompt_tokens": 340687,
|
||||
"completion_tokens": 128333,
|
||||
"real_total_usage": 469020
|
||||
},
|
||||
"average_usage_per_work": {
|
||||
"prompt_tokens": 2523.61,
|
||||
"uncached_prompt_tokens": 2523.61,
|
||||
"completion_tokens": 950.61,
|
||||
"real_total_usage": 3474.22
|
||||
},
|
||||
"duration_seconds_sum_of_requests": 2173.212,
|
||||
"average_duration_seconds_per_work": 16.098
|
||||
},
|
||||
"skipped": true,
|
||||
"works_reused": 135,
|
||||
"works_requested": 0
|
||||
},
|
||||
{
|
||||
"person": {
|
||||
"id": "https://openalex.org/A5093075883",
|
||||
"display_name": "Arman Arzani"
|
||||
},
|
||||
"source_file": "classification_data/A5093075883.json",
|
||||
"output_file": "llm_results/A5093075883_results.json",
|
||||
"summary": {
|
||||
"works_total": 6,
|
||||
"parsed_ok": 4,
|
||||
"api_errors": 0,
|
||||
"validation_errors": 2,
|
||||
"usage": {
|
||||
"prompt_tokens": 18992,
|
||||
"uncached_prompt_tokens": 368,
|
||||
"completion_tokens": 4790,
|
||||
"real_total_usage": 5158
|
||||
},
|
||||
"average_usage_per_work": {
|
||||
"prompt_tokens": 3165.33,
|
||||
"uncached_prompt_tokens": 61.33,
|
||||
"completion_tokens": 798.33,
|
||||
"real_total_usage": 859.67
|
||||
},
|
||||
"duration_seconds_sum_of_requests": 80.141,
|
||||
"average_duration_seconds_per_work": 13.357
|
||||
},
|
||||
"skipped": true,
|
||||
"works_reused": 6,
|
||||
"works_requested": 0
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,410 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
|
||||
PROJECT_ROOT = Path(__file__).resolve().parent
|
||||
|
||||
ES_BASE_URL = "https://project.nes.uni-due.de/elastic".rstrip("/")
|
||||
ES_API_KEY = "am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ=="
|
||||
|
||||
HEADERS = {
|
||||
"Authorization": f"ApiKey {ES_API_KEY}",
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
}
|
||||
|
||||
SELECTED_PERSONS_FILE = PROJECT_ROOT / "selected_persons.json"
|
||||
CLASSIFICATION_DATA_DIR = PROJECT_ROOT / "classification_data"
|
||||
CLASSIFICATION_REPORT_FILE = (
|
||||
CLASSIFICATION_DATA_DIR / "selected_persons_classification_report.json"
|
||||
)
|
||||
|
||||
WORKS_INDEX = "openalex-works*"
|
||||
WORK_YEAR_GTE = 1950
|
||||
PAGE_SIZE = 500
|
||||
|
||||
EXCLUDED_TYPES = {
|
||||
"editorial",
|
||||
"erratum",
|
||||
"paratext",
|
||||
"retraction",
|
||||
}
|
||||
|
||||
|
||||
def es_search(index: str, body: dict[str, Any]) -> dict[str, Any]:
|
||||
url = f"{ES_BASE_URL}/{index}/_search"
|
||||
response = requests.post(url, headers=HEADERS, json=body, timeout=120)
|
||||
|
||||
if not response.ok:
|
||||
raise RuntimeError(
|
||||
f"Elasticsearch error {response.status_code} for index {index}:\n"
|
||||
f"{response.text}"
|
||||
)
|
||||
|
||||
return response.json()
|
||||
|
||||
|
||||
def read_json(path: Path) -> Any:
|
||||
with path.open("r", encoding="utf-8") as file:
|
||||
return json.load(file)
|
||||
|
||||
|
||||
def write_json(path: Path, data: Any) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temp_path = path.with_suffix(path.suffix + ".tmp")
|
||||
temp_path.write_text(
|
||||
json.dumps(data, ensure_ascii=False, indent=2),
|
||||
encoding="utf-8",
|
||||
)
|
||||
temp_path.replace(path)
|
||||
|
||||
|
||||
def text_present(value: Any) -> bool:
|
||||
return isinstance(value, str) and bool(value.strip())
|
||||
|
||||
|
||||
def person_filename(person_id: str) -> str:
|
||||
return person_id.rstrip("/").rsplit("/", 1)[-1]
|
||||
|
||||
|
||||
def unique_clean(values: list[Any], limit: int = 8) -> list[str]:
|
||||
result: list[str] = []
|
||||
seen: set[str] = set()
|
||||
|
||||
for value in values:
|
||||
if not text_present(value):
|
||||
continue
|
||||
|
||||
clean = value.strip()
|
||||
normalized = clean.casefold()
|
||||
|
||||
if normalized in seen:
|
||||
continue
|
||||
|
||||
seen.add(normalized)
|
||||
result.append(clean)
|
||||
|
||||
if len(result) >= limit:
|
||||
break
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def get_venue(work: dict[str, Any]) -> str | None:
|
||||
primary_location = work.get("primary_location") or {}
|
||||
primary_source = primary_location.get("source") or {}
|
||||
|
||||
if text_present(primary_source.get("display_name")):
|
||||
return primary_source["display_name"]
|
||||
|
||||
for location in work.get("locations") or []:
|
||||
if not isinstance(location, dict):
|
||||
continue
|
||||
|
||||
source = location.get("source") or {}
|
||||
|
||||
if text_present(source.get("display_name")):
|
||||
return source["display_name"]
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def get_topics(work: dict[str, Any]) -> list[str]:
|
||||
values: list[Any] = []
|
||||
|
||||
for topic in work.get("topics") or []:
|
||||
if not isinstance(topic, dict):
|
||||
continue
|
||||
|
||||
values.append(topic.get("display_name"))
|
||||
|
||||
subfield = topic.get("subfield") or {}
|
||||
field = topic.get("field") or {}
|
||||
|
||||
if isinstance(subfield, dict):
|
||||
values.append(subfield.get("display_name"))
|
||||
|
||||
if isinstance(field, dict):
|
||||
values.append(field.get("display_name"))
|
||||
|
||||
for concept in work.get("concepts") or []:
|
||||
if isinstance(concept, dict):
|
||||
values.append(concept.get("display_name"))
|
||||
|
||||
return unique_clean(values, limit=8)
|
||||
|
||||
|
||||
def get_funders(work: dict[str, Any]) -> list[str]:
|
||||
values: list[Any] = []
|
||||
|
||||
for funder in work.get("funders") or []:
|
||||
if isinstance(funder, dict):
|
||||
values.append(funder.get("display_name"))
|
||||
|
||||
for award in work.get("awards") or []:
|
||||
if isinstance(award, dict):
|
||||
values.append(award.get("funder_display_name"))
|
||||
|
||||
return unique_clean(values, limit=8)
|
||||
|
||||
|
||||
def to_classification_record(
|
||||
person: dict[str, Any],
|
||||
work: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
work_type = work.get("type")
|
||||
abstract = work.get("abstract")
|
||||
|
||||
return {
|
||||
"person": {
|
||||
"id": person.get("id"),
|
||||
"display_name": person.get("display_name"),
|
||||
},
|
||||
"work_id": work.get("id"),
|
||||
"doi": work.get("doi"),
|
||||
"input": {
|
||||
"title": work.get("title") or work.get("display_name"),
|
||||
"abstract": abstract if text_present(abstract) else None,
|
||||
"venue": get_venue(work),
|
||||
"work_type": work_type,
|
||||
"topics": get_topics(work),
|
||||
"funders": get_funders(work),
|
||||
"year": work.get("publication_year"),
|
||||
"language": work.get("language"),
|
||||
},
|
||||
"debug": {
|
||||
"publication_date": work.get("publication_date"),
|
||||
"has_abstract": text_present(abstract),
|
||||
"excluded_type": work_type in EXCLUDED_TYPES,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def works_by_author_query(
|
||||
author_id: str,
|
||||
search_after: list[Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
body: dict[str, Any] = {
|
||||
"size": PAGE_SIZE,
|
||||
"track_total_hits": True,
|
||||
"_source": [
|
||||
"id",
|
||||
"doi",
|
||||
"title",
|
||||
"display_name",
|
||||
"abstract",
|
||||
"publication_year",
|
||||
"publication_date",
|
||||
"type",
|
||||
"language",
|
||||
"primary_location.source.display_name",
|
||||
"primary_location.source.type",
|
||||
"locations.source.display_name",
|
||||
"locations.source.type",
|
||||
"topics.display_name",
|
||||
"topics.subfield.display_name",
|
||||
"topics.field.display_name",
|
||||
"concepts.display_name",
|
||||
"concepts.score",
|
||||
"funders.display_name",
|
||||
"awards.funder_display_name",
|
||||
],
|
||||
"query": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{"range": {"publication_year": {"gte": WORK_YEAR_GTE}}},
|
||||
{
|
||||
"nested": {
|
||||
"path": "authorships",
|
||||
"query": {
|
||||
"term": {
|
||||
"authorships.author.id": author_id,
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
]
|
||||
}
|
||||
},
|
||||
"sort": [
|
||||
{"publication_year": {"order": "desc"}},
|
||||
{"id": {"order": "asc"}},
|
||||
],
|
||||
}
|
||||
|
||||
if search_after is not None:
|
||||
body["search_after"] = search_after
|
||||
|
||||
return body
|
||||
|
||||
|
||||
def fetch_all_works_for_author(
|
||||
author_id: str,
|
||||
) -> tuple[list[dict[str, Any]], int, int]:
|
||||
works_by_id: dict[str, dict[str, Any]] = {}
|
||||
duplicate_hits_ignored = 0
|
||||
search_after: list[Any] | None = None
|
||||
total_hits = 0
|
||||
hits_read = 0
|
||||
|
||||
while True:
|
||||
result = es_search(
|
||||
WORKS_INDEX,
|
||||
works_by_author_query(author_id, search_after),
|
||||
)
|
||||
hits = result.get("hits", {}).get("hits", [])
|
||||
|
||||
if hits_read == 0:
|
||||
total = result.get("hits", {}).get("total", 0)
|
||||
total_hits = int(
|
||||
total.get("value", 0) if isinstance(total, dict) else total
|
||||
)
|
||||
|
||||
if not hits:
|
||||
break
|
||||
|
||||
for hit in hits:
|
||||
source = hit.get("_source") or {}
|
||||
work_id = source.get("id")
|
||||
|
||||
if not isinstance(work_id, str) or not work_id:
|
||||
raise ValueError("Encountered a work without an OpenAlex id")
|
||||
|
||||
existing = works_by_id.get(work_id)
|
||||
|
||||
if existing is None:
|
||||
works_by_id[work_id] = source
|
||||
elif existing == source:
|
||||
duplicate_hits_ignored += 1
|
||||
else:
|
||||
raise ValueError(f"Conflicting records for work_id {work_id}")
|
||||
|
||||
hits_read += len(hits)
|
||||
search_after = hits[-1].get("sort")
|
||||
|
||||
if not isinstance(search_after, list):
|
||||
raise RuntimeError("Missing search_after values in Elasticsearch response")
|
||||
|
||||
print(
|
||||
f" hits read: {hits_read} / {total_hits}; unique works: {len(works_by_id)}"
|
||||
)
|
||||
time.sleep(0.05)
|
||||
|
||||
return list(works_by_id.values()), total_hits, duplicate_hits_ignored
|
||||
|
||||
|
||||
def validate_selected_persons(data: Any) -> list[dict[str, Any]]:
|
||||
if not isinstance(data, list):
|
||||
raise ValueError("selected_persons.json must contain a list")
|
||||
|
||||
persons: list[dict[str, Any]] = []
|
||||
seen_ids: set[str] = set()
|
||||
|
||||
for item in data:
|
||||
if not isinstance(item, dict):
|
||||
raise ValueError("Each selected person must be an object")
|
||||
|
||||
person_id = item.get("id")
|
||||
|
||||
if not isinstance(person_id, str) or not person_id:
|
||||
raise ValueError("Each selected person must have a non-empty id")
|
||||
|
||||
if person_id in seen_ids:
|
||||
raise ValueError(f"Duplicate selected person id: {person_id}")
|
||||
|
||||
seen_ids.add(person_id)
|
||||
persons.append(item)
|
||||
|
||||
return persons
|
||||
|
||||
|
||||
def main() -> None:
|
||||
if ES_API_KEY == "тут код" or not ES_API_KEY.strip():
|
||||
raise RuntimeError("Set ES_API_KEY in prepare_classification_data.py")
|
||||
|
||||
if not SELECTED_PERSONS_FILE.exists():
|
||||
raise FileNotFoundError(SELECTED_PERSONS_FILE)
|
||||
|
||||
CLASSIFICATION_DATA_DIR.mkdir(parents=True, exist_ok=True)
|
||||
selected_persons = validate_selected_persons(read_json(SELECTED_PERSONS_FILE))
|
||||
|
||||
report: dict[str, Any] = {
|
||||
"config": {
|
||||
"selected_persons_file": SELECTED_PERSONS_FILE.name,
|
||||
"classification_data_dir": CLASSIFICATION_DATA_DIR.name,
|
||||
"works_index": WORKS_INDEX,
|
||||
"work_year_gte": WORK_YEAR_GTE,
|
||||
"excluded_types": sorted(EXCLUDED_TYPES),
|
||||
},
|
||||
"persons": [],
|
||||
}
|
||||
|
||||
for index, person in enumerate(selected_persons, start=1):
|
||||
person_id = person["id"]
|
||||
person_name = person.get("display_name")
|
||||
short_id = person_filename(person_id)
|
||||
|
||||
print(f"\n[{index}/{len(selected_persons)}] {person_name} - {person_id}")
|
||||
|
||||
raw_works, total_hits, duplicates_ignored = fetch_all_works_for_author(
|
||||
person_id
|
||||
)
|
||||
classification_records = [
|
||||
to_classification_record(person, work) for work in raw_works
|
||||
]
|
||||
|
||||
output_path = CLASSIFICATION_DATA_DIR / f"{short_id}.json"
|
||||
write_json(
|
||||
output_path,
|
||||
{
|
||||
"person": person,
|
||||
"works": classification_records,
|
||||
},
|
||||
)
|
||||
|
||||
works_with_abstract = sum(
|
||||
record["debug"]["has_abstract"] is True for record in classification_records
|
||||
)
|
||||
works_excluded_type = sum(
|
||||
record["debug"]["excluded_type"] is True
|
||||
for record in classification_records
|
||||
)
|
||||
|
||||
report["persons"].append(
|
||||
{
|
||||
"id": person_id,
|
||||
"display_name": person_name,
|
||||
"output_file": output_path.relative_to(PROJECT_ROOT).as_posix(),
|
||||
"elasticsearch_hits_total": total_hits,
|
||||
"duplicate_hits_ignored": duplicates_ignored,
|
||||
"works_total": len(classification_records),
|
||||
"works_with_abstract": works_with_abstract,
|
||||
"works_without_abstract": (
|
||||
len(classification_records) - works_with_abstract
|
||||
),
|
||||
"works_excluded_type": works_excluded_type,
|
||||
}
|
||||
)
|
||||
|
||||
print(f" written: {output_path.relative_to(PROJECT_ROOT).as_posix()}")
|
||||
print(f" unique works: {len(classification_records)}")
|
||||
print(f" duplicate hits ignored: {duplicates_ignored}")
|
||||
print(f" with abstract: {works_with_abstract}")
|
||||
print(f" excluded type: {works_excluded_type}")
|
||||
|
||||
write_json(CLASSIFICATION_REPORT_FILE, report)
|
||||
|
||||
print("\nDone.")
|
||||
print(
|
||||
"Report written: "
|
||||
f"{CLASSIFICATION_REPORT_FILE.relative_to(PROJECT_ROOT).as_posix()}"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,331 @@
|
||||
You are a research-policy analyst classifying the **orientation** of a single
|
||||
scholarly work. Use *only* the definitions and rules below. Do not invent your
|
||||
own notion of "applied" — apply the Frascati Manual definitions exactly.
|
||||
|
||||
### Frascati Manual (OECD, 2015) definitions — authoritative
|
||||
|
||||
**Basic research / Grundlagenforschung**
|
||||
Experimental or theoretical work undertaken primarily to acquire new knowledge
|
||||
of the underlying foundations of phenomena and observable facts, **without any
|
||||
particular application or use in view.**
|
||||
|
||||
**Applied research / Angewandte Forschung**
|
||||
Original investigation undertaken to acquire new knowledge, **directed primarily
|
||||
towards a specific, practical aim or objective.**
|
||||
|
||||
**Experimental development / Experimentelle Entwicklung**
|
||||
Systematic work, drawing on knowledge gained from research and practical
|
||||
experience and producing additional knowledge, **directed to producing new
|
||||
products or processes, or to improving existing ones** (includes prototyping,
|
||||
piloting, scale-up, demonstrators).
|
||||
|
||||
The three form a spectrum of increasing practical/product orientation:
|
||||
`basic_research → applied_research → experimental_development`.
|
||||
|
||||
### The Pasteur's-quadrant caveat (read carefully)
|
||||
|
||||
A work can *seek fundamental understanding* **and** *be motivated by an
|
||||
eventual use*. Frascati keeps such work in **basic research** when the immediate
|
||||
aim is fundamental knowledge, even if a use is mentioned. Do **not** upgrade a
|
||||
mechanistic/theoretical study to "applied" merely because it names a possible
|
||||
future application ("...to enable next-generation batteries", "...with potential
|
||||
clinical relevance"). Record this via the `pasteur_quadrant` field:
|
||||
|
||||
- `pure_basic` — fundamental understanding, no use mentioned.
|
||||
- `use_inspired_basic` — fundamental understanding, motivated by a use →
|
||||
still classified `basic_research`.
|
||||
- `pure_applied` — driven by a specific practical aim.
|
||||
- `not_applicable` — non-research item.
|
||||
|
||||
### Classification procedure
|
||||
|
||||
1. Determine whether the item is research at all. Editorials, corrections,
|
||||
prefaces, tables of contents, book reviews, pure datasets/software with no
|
||||
research narrative → `non_research`.
|
||||
2. Read every provided signal (see INPUT). Weight the abstract most; then
|
||||
venue, topics, funders, work type; the title last on its own.
|
||||
3. Decide the `primary_category` from the three Frascati definitions, applying
|
||||
the Pasteur caveat.
|
||||
4. Set `pasteur_quadrant` from the immediate orientation of the work.
|
||||
5. Assign `applied_orientation_score` only after the category and quadrant are
|
||||
fixed. The score is a dependent summary field, not independent evidence.
|
||||
Use only the hard category-score ranges below.
|
||||
6. Set `confidence` — **capped by the signals available** (see next section).
|
||||
|
||||
### Hard category-score consistency rules
|
||||
|
||||
Choose `primary_category` from the Frascati definitions first. Never change a
|
||||
semantically chosen category merely to fit a preferred score. Then choose the
|
||||
score only from the permitted range for that category and quadrant:
|
||||
|
||||
- `basic_research` + `pure_basic` → integer score **0–30**.
|
||||
- `basic_research` + `use_inspired_basic` → integer score **25–45**.
|
||||
- `applied_research` + `pure_applied` → integer score **31–70**.
|
||||
- `experimental_development` + `pure_applied` → integer score **71–100**.
|
||||
- `non_research` + `not_applicable` → score **null**.
|
||||
|
||||
These are hard output constraints, not rough anchors.
|
||||
|
||||
A highly practical work that has a specific practical objective but does not
|
||||
produce or improve a product/process, prototype, pilot, demonstrator, deployed
|
||||
system, or tested intervention remains `applied_research` and must receive a
|
||||
score of at most 70.
|
||||
|
||||
Use `experimental_development` only when the work itself reports systematic
|
||||
product/process development or improvement, prototyping, piloting, scale-up,
|
||||
demonstration, deployment, or an interventional clinical/field trial. A review,
|
||||
case report, observational analysis, diagnostic association study, or evaluation
|
||||
of an already established treatment is not experimental development merely
|
||||
because it is clinically important or strongly practical.
|
||||
|
||||
### Confidence caps (hard rules — do not exceed)
|
||||
|
||||
- Abstract present (+ any other signal) → up to **high**.
|
||||
- No abstract, but venue **and/or** topics present → at most **medium**.
|
||||
- Title only, nothing else usable → at most **low**, and set
|
||||
`insufficient_context: true`.
|
||||
Lower the confidence further whenever the signals are genuinely ambiguous
|
||||
(opaque/"cute" titles, interdisciplinary venues, one-word topics).
|
||||
|
||||
### Field-specific guidance
|
||||
|
||||
- **Humanities / social sciences:** default expectation is basic research;
|
||||
"applied" requires a clear practical aim (policy design, intervention,
|
||||
clinical/legal practice, engineering of a tool). Do not treat empirical or
|
||||
data-driven work as "applied" by itself — empiricism ≠ practical aim.
|
||||
- **Engineering / medicine / CS:** watch for the opposite bias; a system,
|
||||
device, protocol, pilot, or benchmark aimed at a working artifact is usually
|
||||
applied or experimental development, not basic. Distinguish a practical
|
||||
investigation from actual product/process development: practical importance
|
||||
alone does not make a work experimental development.
|
||||
- **Reviews / surveys:** classify by the orientation of the body of work
|
||||
reviewed; if unclear, `basic_research`, `low`/`medium` confidence.
|
||||
- **German titles:** classify identically; the definitions apply regardless of
|
||||
language. Do not penalize confidence merely because the text is German.
|
||||
|
||||
### Edge cases
|
||||
|
||||
- Named future application but fundamental method → `use_inspired_basic` /
|
||||
`basic_research`.
|
||||
- Methodological/theoretical paper *about* a technique with no target problem →
|
||||
`basic_research`.
|
||||
- Interventional clinical trial, field trial, prototype, pilot, scale-up,
|
||||
demonstrator, or deployment → `experimental_development`.
|
||||
- Review, case report, observational cohort/registry analysis, or evaluation of
|
||||
an established treatment without development of a new product/process →
|
||||
normally `applied_research` when it has a specific practical aim.
|
||||
- Cannot decide research vs. non-research from a bare title → `non_research`
|
||||
only if strongly indicated; otherwise best research guess + `low` confidence.
|
||||
|
||||
---
|
||||
|
||||
## INPUT
|
||||
|
||||
Provide any subset of the following. Absent fields are omitted (do not fabricate).
|
||||
|
||||
```
|
||||
title: {{title}}
|
||||
abstract: {{abstract}} # may be empty
|
||||
venue: {{venue_name}} # journal / book / conference / repository
|
||||
work_type: {{work_type}} # article, book-chapter, preprint, dataset, ...
|
||||
topics: {{topics}} # OpenAlex topics/concepts, comma-separated
|
||||
funders: {{funders}} # if available
|
||||
year: {{publication_year}}
|
||||
language: {{language}}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## OUTPUT
|
||||
|
||||
Return **only** a single JSON object, no prose, no markdown fences:
|
||||
|
||||
```json
|
||||
{
|
||||
"primary_category": "basic_research | applied_research | experimental_development | non_research",
|
||||
"applied_orientation_score": 0,
|
||||
"pasteur_quadrant": "pure_basic | use_inspired_basic | pure_applied | not_applicable",
|
||||
"confidence": "high | medium | low",
|
||||
"signals_used": ["title", "abstract", "venue", "topics", "funders", "work_type"],
|
||||
"insufficient_context": false,
|
||||
"rationale": "<= 40 words, cite the decisive signal"
|
||||
}
|
||||
```
|
||||
|
||||
Rules: `applied_orientation_score` must be consistent with `primary_category`
|
||||
and `pasteur_quadrant` according to the hard ranges above.
|
||||
`non_research` → score `null`, `pasteur_quadrant: not_applicable`.
|
||||
`confidence` must respect the caps above. `signals_used` lists only fields that
|
||||
actually informed the decision.
|
||||
|
||||
Before returning JSON, perform this final self-check:
|
||||
1. Is `primary_category` supported by the immediate aim of the work?
|
||||
2. Is `pasteur_quadrant` compatible with that category?
|
||||
3. Is the score inside the hard permitted range?
|
||||
If step 3 fails, keep the semantically chosen category and choose a valid score
|
||||
inside its range. Do not change the category merely to preserve an invalid score.
|
||||
|
||||
---
|
||||
|
||||
## Few-shot examples
|
||||
|
||||
Example 1 — Basic research
|
||||
|
||||
INPUT:
|
||||
title: "Mechanisms of protein folding under molecular crowding"
|
||||
abstract: "We investigate the physical principles governing protein folding dynamics under different molecular crowding conditions using theoretical modeling and spectroscopy. The study aims to improve understanding of the underlying mechanisms of biomolecular structure formation."
|
||||
venue: "Journal of Molecular Biology"
|
||||
work_type: "article"
|
||||
topics: ["Protein folding", "Molecular biology", "Biophysics"]
|
||||
funders: []
|
||||
year: 2023
|
||||
language: "en"
|
||||
|
||||
OUTPUT:
|
||||
{
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 15,
|
||||
"pasteur_quadrant": "pure_basic",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "topics", "work_type"],
|
||||
"insufficient_context": false,
|
||||
"rationale": "The abstract seeks underlying mechanisms of biomolecular structure formation without a specific practical objective."
|
||||
}
|
||||
|
||||
Example 2 — Use-inspired basic research
|
||||
|
||||
INPUT:
|
||||
title: "Understanding degradation mechanisms in perovskite solar-cell materials"
|
||||
abstract: "We study atomic-scale degradation pathways in perovskite materials under humidity and heat. The work aims to explain the fundamental mechanisms that limit stability, providing knowledge relevant to future solar-cell materials."
|
||||
venue: "Advanced Energy Materials"
|
||||
work_type: "article"
|
||||
topics: ["Materials science", "Perovskites", "Solar cells"]
|
||||
funders: []
|
||||
year: 2024
|
||||
language: "en"
|
||||
|
||||
OUTPUT:
|
||||
{
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 35,
|
||||
"pasteur_quadrant": "use_inspired_basic",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics", "work_type"],
|
||||
"insufficient_context": false,
|
||||
"rationale": "The immediate aim is mechanistic understanding, although the knowledge is motivated by future solar-cell applications."
|
||||
}
|
||||
|
||||
Example 3 — Applied research
|
||||
|
||||
INPUT:
|
||||
title: "A prediction model for hospital readmission risk in heart-failure patients"
|
||||
abstract: "We develop and evaluate a statistical model to predict 30-day readmission risk in heart-failure patients using electronic health records. The objective is to support clinical decision-making and identify high-risk patients."
|
||||
venue: "BMC Medical Informatics and Decision Making"
|
||||
work_type: "article"
|
||||
topics: ["Clinical prediction", "Health informatics", "Heart failure"]
|
||||
funders: []
|
||||
year: 2022
|
||||
language: "en"
|
||||
|
||||
OUTPUT:
|
||||
{
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 65,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics", "work_type"],
|
||||
"insufficient_context": false,
|
||||
"rationale": "The abstract states a specific practical objective: predicting readmission risk to support clinical decision-making."
|
||||
}
|
||||
|
||||
Example 4 — Applied research, not experimental development
|
||||
|
||||
INPUT:
|
||||
title: "A mathematical model for optimizing emergency vehicle routing"
|
||||
abstract: "We formulate and test an optimization model for emergency vehicle routing under time-dependent traffic conditions. The work addresses a practical planning problem, but does not report deployment, prototyping, or creation of a new operational system."
|
||||
venue: "European Journal of Operational Research"
|
||||
work_type: "article"
|
||||
topics: ["Optimization", "Vehicle routing", "Operations research"]
|
||||
funders: []
|
||||
year: 2021
|
||||
language: "en"
|
||||
|
||||
OUTPUT:
|
||||
{
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 70,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics", "work_type"],
|
||||
"insufficient_context": false,
|
||||
"rationale": "The work targets a specific routing problem, but lacks prototype, deployment, or system-building signals."
|
||||
}
|
||||
|
||||
Example 5 — Experimental development
|
||||
|
||||
INPUT:
|
||||
title: "A deployed sensor platform for real-time flood monitoring"
|
||||
abstract: "We design, implement, and field-test a sensor platform for real-time flood monitoring. The system integrates wireless sensors, a data-processing pipeline, and a dashboard, and is evaluated during a pilot deployment with emergency services."
|
||||
venue: "Sensors"
|
||||
work_type: "article"
|
||||
topics: ["Sensor networks", "Flood monitoring", "Emergency management"]
|
||||
funders: []
|
||||
year: 2024
|
||||
language: "en"
|
||||
|
||||
OUTPUT:
|
||||
{
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 85,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics", "work_type"],
|
||||
"insufficient_context": false,
|
||||
"rationale": "The abstract describes design, implementation, and pilot deployment of a working monitoring platform."
|
||||
}
|
||||
|
||||
Example 6 — Title-only / insufficient context
|
||||
|
||||
INPUT:
|
||||
title: "Blockchain-based access control for digital services"
|
||||
abstract: null
|
||||
venue: "Lecture Notes in Computer Science"
|
||||
work_type: "book-chapter"
|
||||
topics: ["Blockchain", "Access control", "Computer security"]
|
||||
funders: []
|
||||
year: 2023
|
||||
language: "en"
|
||||
|
||||
OUTPUT:
|
||||
{
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 60,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "venue", "topics", "work_type"],
|
||||
"insufficient_context": true,
|
||||
"rationale": "The title and topics suggest a practical security aim, but no abstract is available."
|
||||
}
|
||||
|
||||
Example 7 — Non-research
|
||||
|
||||
INPUT:
|
||||
title: "Correction to: A prediction model for hospital readmission risk"
|
||||
abstract: null
|
||||
venue: "BMC Medical Informatics and Decision Making"
|
||||
work_type: "article"
|
||||
topics: []
|
||||
funders: []
|
||||
year: 2023
|
||||
language: "en"
|
||||
|
||||
OUTPUT:
|
||||
{
|
||||
"primary_category": "non_research",
|
||||
"applied_orientation_score": null,
|
||||
"pasteur_quadrant": "not_applicable",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title"],
|
||||
"insufficient_context": false,
|
||||
"rationale": "The title explicitly identifies the item as a correction, not an original research contribution."
|
||||
}
|
||||
+3197
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
Load Diff
+926
@@ -0,0 +1,926 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from collections import Counter
|
||||
from collections.abc import Callable, Iterable
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
|
||||
ES_BASE_URL = "https://project.nes.uni-due.de/elastic"
|
||||
ES_API_KEY = "am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ=="
|
||||
|
||||
TARGET_INDEX = "work-classifications"
|
||||
WORKS_INDEX = "openalex-works*"
|
||||
WORK_YEAR_GTE = 1950
|
||||
|
||||
DEFAULT_AUTHORS_FILE = ROOT / "ude_authors_set.jsonl"
|
||||
DEFAULT_OUTPUT_DIR = ROOT / "evaluation"
|
||||
|
||||
REQUEST_TIMEOUT = 120.0
|
||||
SEARCH_PAGE_SIZE = 1000
|
||||
SCROLL_KEEP_ALIVE = "5m"
|
||||
SAMPLE_SIZE = 100
|
||||
|
||||
|
||||
def utc_now() -> str:
|
||||
return (
|
||||
datetime.now(timezone.utc)
|
||||
.isoformat()
|
||||
.replace(
|
||||
"+00:00",
|
||||
"Z",
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def timestamp() -> str:
|
||||
return datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
||||
|
||||
|
||||
def auth_header() -> str:
|
||||
value = ES_API_KEY.strip()
|
||||
|
||||
if not value:
|
||||
raise RuntimeError("ES_API_KEY is empty.")
|
||||
|
||||
if value.startswith("ApiKey "):
|
||||
return value
|
||||
|
||||
return f"ApiKey {value}"
|
||||
|
||||
|
||||
def normalize_openalex_id(
|
||||
value: Any,
|
||||
prefix: str,
|
||||
) -> str | None:
|
||||
if not isinstance(value, str):
|
||||
return None
|
||||
|
||||
candidate = value.strip().rstrip("/")
|
||||
if not candidate:
|
||||
return None
|
||||
|
||||
short_id = candidate.rsplit("/", 1)[-1].upper()
|
||||
|
||||
if not short_id.startswith(prefix):
|
||||
return None
|
||||
|
||||
suffix = short_id[len(prefix) :]
|
||||
if not suffix.isdigit():
|
||||
return None
|
||||
|
||||
return f"https://openalex.org/{short_id}"
|
||||
|
||||
|
||||
def normalize_author_id(
|
||||
value: Any,
|
||||
) -> str | None:
|
||||
return normalize_openalex_id(
|
||||
value,
|
||||
"A",
|
||||
)
|
||||
|
||||
|
||||
def normalize_work_id(
|
||||
value: Any,
|
||||
) -> str | None:
|
||||
return normalize_openalex_id(
|
||||
value,
|
||||
"W",
|
||||
)
|
||||
|
||||
|
||||
def unwrap(
|
||||
record: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
for key in (
|
||||
"_source",
|
||||
"source",
|
||||
):
|
||||
nested = record.get(key)
|
||||
if isinstance(nested, dict):
|
||||
return nested
|
||||
|
||||
return record
|
||||
|
||||
|
||||
def iter_jsonl(
|
||||
path: Path,
|
||||
) -> Iterable[tuple[int, dict[str, Any]]]:
|
||||
if not path.exists():
|
||||
raise FileNotFoundError(f"File not found: {path}")
|
||||
|
||||
with path.open(
|
||||
"r",
|
||||
encoding="utf-8-sig",
|
||||
) as handle:
|
||||
for line_number, raw_line in enumerate(
|
||||
handle,
|
||||
start=1,
|
||||
):
|
||||
line = raw_line.strip()
|
||||
if not line:
|
||||
continue
|
||||
|
||||
try:
|
||||
value = json.loads(line)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise ValueError(
|
||||
f"Invalid JSON at {path}:{line_number}: {exc}"
|
||||
) from exc
|
||||
|
||||
if not isinstance(value, dict):
|
||||
raise ValueError(f"Expected a JSON object at {path}:{line_number}.")
|
||||
|
||||
yield line_number, value
|
||||
|
||||
|
||||
def extract_author(
|
||||
record: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
source = unwrap(record)
|
||||
|
||||
ids = source.get("ids") if isinstance(source.get("ids"), dict) else {}
|
||||
|
||||
author_id = (
|
||||
normalize_author_id(source.get("id"))
|
||||
or normalize_author_id(ids.get("openalex"))
|
||||
or normalize_author_id(record.get("_id"))
|
||||
)
|
||||
|
||||
if author_id is None:
|
||||
raise ValueError("Author record has no valid OpenAlex ID.")
|
||||
|
||||
display_name = source.get("display_name")
|
||||
if not isinstance(display_name, str):
|
||||
display_name = None
|
||||
|
||||
return {
|
||||
"author_id": author_id,
|
||||
"display_name": display_name,
|
||||
}
|
||||
|
||||
|
||||
def load_authors(
|
||||
path: Path,
|
||||
) -> tuple[dict[str, dict[str, Any]], int]:
|
||||
authors: dict[str, dict[str, Any]] = {}
|
||||
duplicate_records = 0
|
||||
|
||||
for line_number, record in iter_jsonl(path):
|
||||
try:
|
||||
author = extract_author(record)
|
||||
except ValueError as exc:
|
||||
raise ValueError(f"{path}:{line_number}: {exc}") from exc
|
||||
|
||||
author_id = author["author_id"]
|
||||
|
||||
if author_id in authors:
|
||||
duplicate_records += 1
|
||||
|
||||
if (
|
||||
authors[author_id].get("display_name") is None
|
||||
and author.get("display_name") is not None
|
||||
):
|
||||
authors[author_id]["display_name"] = author["display_name"]
|
||||
continue
|
||||
|
||||
authors[author_id] = author
|
||||
|
||||
if not authors:
|
||||
raise RuntimeError(f"No authors were loaded from {path}.")
|
||||
|
||||
return authors, duplicate_records
|
||||
|
||||
|
||||
def extract_authorship_author_ids(
|
||||
source: dict[str, Any],
|
||||
) -> set[str]:
|
||||
result: set[str] = set()
|
||||
authorships = source.get("authorships")
|
||||
|
||||
if not isinstance(authorships, list):
|
||||
return result
|
||||
|
||||
for authorship in authorships:
|
||||
if not isinstance(authorship, dict):
|
||||
continue
|
||||
|
||||
author = authorship.get("author")
|
||||
if not isinstance(author, dict):
|
||||
continue
|
||||
|
||||
author_id = normalize_author_id(author.get("id"))
|
||||
if author_id is not None:
|
||||
result.add(author_id)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
class ElasticsearchClient:
|
||||
def __init__(self) -> None:
|
||||
self.session = requests.Session()
|
||||
self.session.headers.update(
|
||||
{
|
||||
"Authorization": auth_header(),
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
}
|
||||
)
|
||||
|
||||
def request(
|
||||
self,
|
||||
method: str,
|
||||
path: str,
|
||||
body: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
response = self.session.request(
|
||||
method,
|
||||
(f"{ES_BASE_URL.rstrip('/')}/{path.lstrip('/')}"),
|
||||
json=body,
|
||||
timeout=REQUEST_TIMEOUT,
|
||||
)
|
||||
|
||||
if response.status_code >= 400:
|
||||
raise RuntimeError(
|
||||
f"Elasticsearch {response.status_code} "
|
||||
f"{method} {path}\n"
|
||||
f"{response.text[:4000]}"
|
||||
)
|
||||
|
||||
payload = response.json()
|
||||
if not isinstance(payload, dict):
|
||||
raise RuntimeError("Elasticsearch returned invalid JSON.")
|
||||
|
||||
return payload
|
||||
|
||||
|
||||
def index_count(
|
||||
client: ElasticsearchClient,
|
||||
index: str,
|
||||
) -> int:
|
||||
payload = client.request(
|
||||
"GET",
|
||||
f"{index}/_count",
|
||||
)
|
||||
count = payload.get("count")
|
||||
|
||||
if not isinstance(count, int):
|
||||
raise RuntimeError(f"Could not read count for index {index}.")
|
||||
|
||||
return count
|
||||
|
||||
|
||||
def total_hits_value(
|
||||
value: Any,
|
||||
) -> int:
|
||||
if isinstance(value, int):
|
||||
return value
|
||||
|
||||
if isinstance(value, dict):
|
||||
nested = value.get("value")
|
||||
if isinstance(nested, int):
|
||||
return nested
|
||||
|
||||
raise RuntimeError("Could not read Elasticsearch total hits.")
|
||||
|
||||
|
||||
def scan_scroll(
|
||||
client: ElasticsearchClient,
|
||||
index: str,
|
||||
body: dict[str, Any],
|
||||
label: str,
|
||||
handle_hit: Callable[[dict[str, Any]], None],
|
||||
) -> dict[str, int]:
|
||||
scroll_id: str | None = None
|
||||
fetched = 0
|
||||
reported_total: int | None = None
|
||||
|
||||
request_body = dict(body)
|
||||
request_body["size"] = SEARCH_PAGE_SIZE
|
||||
request_body["track_total_hits"] = True
|
||||
request_body["sort"] = ["_doc"]
|
||||
|
||||
try:
|
||||
response = client.request(
|
||||
"POST",
|
||||
(f"{index}/_search?scroll={SCROLL_KEEP_ALIVE}"),
|
||||
request_body,
|
||||
)
|
||||
|
||||
while True:
|
||||
current_scroll_id = response.get("_scroll_id")
|
||||
if isinstance(current_scroll_id, str) and current_scroll_id:
|
||||
scroll_id = current_scroll_id
|
||||
|
||||
hits_block = response.get("hits")
|
||||
if not isinstance(hits_block, dict):
|
||||
raise RuntimeError("Search response has no hits object.")
|
||||
|
||||
if reported_total is None:
|
||||
reported_total = total_hits_value(hits_block.get("total"))
|
||||
|
||||
hits = hits_block.get("hits")
|
||||
if not isinstance(hits, list):
|
||||
raise RuntimeError("Search response has no hits list.")
|
||||
|
||||
if not hits:
|
||||
break
|
||||
|
||||
for hit in hits:
|
||||
if not isinstance(hit, dict):
|
||||
raise RuntimeError("Search returned an invalid hit.")
|
||||
|
||||
handle_hit(hit)
|
||||
|
||||
fetched += len(hits)
|
||||
|
||||
print(f"{label}: {fetched}/{reported_total}")
|
||||
|
||||
if scroll_id is None:
|
||||
raise RuntimeError("Elasticsearch did not return a scroll ID.")
|
||||
|
||||
response = client.request(
|
||||
"POST",
|
||||
"_search/scroll",
|
||||
{
|
||||
"scroll": SCROLL_KEEP_ALIVE,
|
||||
"scroll_id": scroll_id,
|
||||
},
|
||||
)
|
||||
|
||||
finally:
|
||||
if scroll_id is not None:
|
||||
try:
|
||||
client.request(
|
||||
"DELETE",
|
||||
"_search/scroll",
|
||||
{"scroll_id": [scroll_id]},
|
||||
)
|
||||
except Exception as exc:
|
||||
print(f"Warning: could not clear Elasticsearch scroll context: {exc}")
|
||||
|
||||
if reported_total is None:
|
||||
raise RuntimeError(f"{label}: no total hit count was returned.")
|
||||
|
||||
if fetched != reported_total:
|
||||
raise RuntimeError(
|
||||
f"{label}: fetched {fetched} hits, "
|
||||
f"but Elasticsearch reported "
|
||||
f"{reported_total}."
|
||||
)
|
||||
|
||||
return {
|
||||
"reported_total": reported_total,
|
||||
"fetched": fetched,
|
||||
}
|
||||
|
||||
|
||||
def fetch_classified_work_ids(
|
||||
client: ElasticsearchClient,
|
||||
) -> tuple[
|
||||
int,
|
||||
int,
|
||||
set[str],
|
||||
int,
|
||||
]:
|
||||
initial_count = index_count(
|
||||
client,
|
||||
TARGET_INDEX,
|
||||
)
|
||||
|
||||
classified_work_ids: set[str] = set()
|
||||
|
||||
def handle_hit(
|
||||
hit: dict[str, Any],
|
||||
) -> None:
|
||||
source = hit.get("_source")
|
||||
es_id = hit.get("_id")
|
||||
|
||||
work_id = (
|
||||
normalize_work_id(source.get("work_id"))
|
||||
if isinstance(source, dict)
|
||||
else None
|
||||
) or normalize_work_id(es_id)
|
||||
|
||||
if work_id is None:
|
||||
raise RuntimeError(f"Invalid work ID in target index: {es_id}")
|
||||
|
||||
classified_work_ids.add(work_id)
|
||||
|
||||
stats = scan_scroll(
|
||||
client=client,
|
||||
index=TARGET_INDEX,
|
||||
body={
|
||||
"_source": ["work_id"],
|
||||
"query": {"match_all": {}},
|
||||
},
|
||||
label="Target index",
|
||||
handle_hit=handle_hit,
|
||||
)
|
||||
|
||||
final_count = index_count(
|
||||
client,
|
||||
TARGET_INDEX,
|
||||
)
|
||||
|
||||
if stats["reported_total"] != initial_count:
|
||||
raise RuntimeError(
|
||||
f"The target index changed before the scroll "
|
||||
f"snapshot was opened: count={initial_count}, "
|
||||
f"snapshot={stats['reported_total']}."
|
||||
)
|
||||
|
||||
if len(classified_work_ids) != stats["fetched"]:
|
||||
raise RuntimeError(
|
||||
f"The target index contains "
|
||||
f"{stats['fetched']} documents but only "
|
||||
f"{len(classified_work_ids)} unique work IDs."
|
||||
)
|
||||
|
||||
return (
|
||||
initial_count,
|
||||
final_count,
|
||||
classified_work_ids,
|
||||
stats["fetched"],
|
||||
)
|
||||
|
||||
|
||||
def source_work_query(
|
||||
author_ids: list[str],
|
||||
work_year_gte: int,
|
||||
) -> dict[str, Any]:
|
||||
return {
|
||||
"_source": [
|
||||
"id",
|
||||
"updated_date",
|
||||
"authorships.author.id",
|
||||
],
|
||||
"query": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{"range": {"publication_year": {"gte": work_year_gte}}},
|
||||
{
|
||||
"nested": {
|
||||
"path": "authorships",
|
||||
"query": {"terms": {"authorships.author.id": (author_ids)}},
|
||||
}
|
||||
},
|
||||
]
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def candidate_is_better(
|
||||
current: dict[str, Any],
|
||||
candidate: dict[str, Any],
|
||||
) -> bool:
|
||||
current_index = current.get("index")
|
||||
candidate_index = candidate.get("index")
|
||||
|
||||
if candidate_index == "openalex-works" and current_index != "openalex-works":
|
||||
return True
|
||||
|
||||
if current_index == "openalex-works" and candidate_index != "openalex-works":
|
||||
return False
|
||||
|
||||
current_updated = current.get("updated_date")
|
||||
candidate_updated = candidate.get("updated_date")
|
||||
|
||||
return isinstance(candidate_updated, str) and (
|
||||
not isinstance(current_updated, str) or candidate_updated > current_updated
|
||||
)
|
||||
|
||||
|
||||
def fetch_source_works(
|
||||
client: ElasticsearchClient,
|
||||
author_ids: set[str],
|
||||
work_year_gte: int,
|
||||
) -> tuple[
|
||||
dict[str, dict[str, Any]],
|
||||
dict[str, Any],
|
||||
]:
|
||||
selected_works: dict[str, dict[str, Any]] = {}
|
||||
|
||||
invalid_work_id_count = 0
|
||||
invalid_work_id_samples: list[str] = []
|
||||
no_listed_author_count = 0
|
||||
no_listed_author_samples: list[str] = []
|
||||
|
||||
def handle_hit(
|
||||
hit: dict[str, Any],
|
||||
) -> None:
|
||||
nonlocal invalid_work_id_count
|
||||
nonlocal no_listed_author_count
|
||||
|
||||
source = hit.get("_source")
|
||||
if not isinstance(source, dict):
|
||||
raise RuntimeError("A source work hit has no valid _source.")
|
||||
|
||||
work_id = normalize_work_id(source.get("id")) or normalize_work_id(
|
||||
hit.get("_id")
|
||||
)
|
||||
|
||||
if work_id is None:
|
||||
invalid_work_id_count += 1
|
||||
if len(invalid_work_id_samples) < SAMPLE_SIZE:
|
||||
invalid_work_id_samples.append(str(hit.get("_id")))
|
||||
return
|
||||
|
||||
work_author_ids = extract_authorship_author_ids(source)
|
||||
relevant_author_ids = work_author_ids & author_ids
|
||||
|
||||
if not relevant_author_ids:
|
||||
no_listed_author_count += 1
|
||||
if len(no_listed_author_samples) < SAMPLE_SIZE:
|
||||
no_listed_author_samples.append(work_id)
|
||||
return
|
||||
|
||||
candidate = {
|
||||
"index": hit.get("_index"),
|
||||
"updated_date": source.get("updated_date"),
|
||||
"author_ids": relevant_author_ids,
|
||||
}
|
||||
|
||||
current = selected_works.get(work_id)
|
||||
|
||||
if current is None or candidate_is_better(
|
||||
current,
|
||||
candidate,
|
||||
):
|
||||
selected_works[work_id] = candidate
|
||||
|
||||
stats = scan_scroll(
|
||||
client=client,
|
||||
index=WORKS_INDEX,
|
||||
body=source_work_query(
|
||||
sorted(author_ids),
|
||||
work_year_gte,
|
||||
),
|
||||
label="OpenAlex works",
|
||||
handle_hit=handle_hit,
|
||||
)
|
||||
|
||||
data_quality = {
|
||||
"source_raw_hits": stats["fetched"],
|
||||
"source_unique_works": len(selected_works),
|
||||
"source_duplicate_documents": (
|
||||
stats["fetched"]
|
||||
- len(selected_works)
|
||||
- invalid_work_id_count
|
||||
- no_listed_author_count
|
||||
),
|
||||
"source_invalid_work_ids": (invalid_work_id_count),
|
||||
"source_invalid_work_id_samples": (invalid_work_id_samples),
|
||||
"source_hits_without_listed_ude_author": (no_listed_author_count),
|
||||
"source_hits_without_listed_ude_author_samples": (no_listed_author_samples),
|
||||
}
|
||||
|
||||
return selected_works, data_quality
|
||||
|
||||
|
||||
def coverage_status(
|
||||
total: int,
|
||||
classified: int,
|
||||
) -> str:
|
||||
if total == 0:
|
||||
return "no_works"
|
||||
|
||||
if classified == 0:
|
||||
return "not_started"
|
||||
|
||||
if classified == total:
|
||||
return "complete"
|
||||
|
||||
return "partial"
|
||||
|
||||
|
||||
def author_sort_key(
|
||||
item: dict[str, Any],
|
||||
) -> tuple[Any, ...]:
|
||||
total = item["total_works"]
|
||||
classified = item["classified_works"]
|
||||
|
||||
coverage = classified / total if total > 0 else None
|
||||
|
||||
return (
|
||||
coverage is None,
|
||||
-coverage if coverage is not None else 0.0,
|
||||
-total,
|
||||
-classified,
|
||||
(
|
||||
item["display_name"].casefold()
|
||||
if isinstance(
|
||||
item["display_name"],
|
||||
str,
|
||||
)
|
||||
else ""
|
||||
),
|
||||
item["author_id"],
|
||||
)
|
||||
|
||||
|
||||
def build_report(
|
||||
*,
|
||||
authors_path: Path,
|
||||
authors: dict[str, dict[str, Any]],
|
||||
duplicate_author_records: int,
|
||||
initial_target_count: int,
|
||||
final_target_count: int,
|
||||
classified_work_ids: set[str],
|
||||
target_documents_scanned: int,
|
||||
selected_works: dict[str, dict[str, Any]],
|
||||
source_quality: dict[str, Any],
|
||||
work_year_gte: int,
|
||||
) -> dict[str, Any]:
|
||||
total_counts: Counter[str] = Counter()
|
||||
classified_counts: Counter[str] = Counter()
|
||||
|
||||
classified_source_work_ids: set[str] = set()
|
||||
|
||||
for work_id, work in selected_works.items():
|
||||
work_author_ids = work["author_ids"]
|
||||
is_classified = work_id in classified_work_ids
|
||||
|
||||
for author_id in work_author_ids:
|
||||
total_counts[author_id] += 1
|
||||
|
||||
if is_classified:
|
||||
classified_counts[author_id] += 1
|
||||
|
||||
if is_classified:
|
||||
classified_source_work_ids.add(work_id)
|
||||
|
||||
rows: list[dict[str, Any]] = []
|
||||
status_counts: Counter[str] = Counter()
|
||||
|
||||
author_work_assignments_total = 0
|
||||
author_work_assignments_classified = 0
|
||||
|
||||
for author_id, author in authors.items():
|
||||
total = total_counts.get(
|
||||
author_id,
|
||||
0,
|
||||
)
|
||||
classified = classified_counts.get(
|
||||
author_id,
|
||||
0,
|
||||
)
|
||||
unclassified = total - classified
|
||||
|
||||
coverage = classified / total if total > 0 else None
|
||||
|
||||
status = coverage_status(
|
||||
total,
|
||||
classified,
|
||||
)
|
||||
status_counts[status] += 1
|
||||
|
||||
author_work_assignments_total += total
|
||||
author_work_assignments_classified += classified
|
||||
|
||||
rows.append(
|
||||
{
|
||||
"author_id": author_id,
|
||||
"display_name": author["display_name"],
|
||||
"total_works": total,
|
||||
"classified_works": classified,
|
||||
"unclassified_works": (unclassified),
|
||||
"coverage_percent": (
|
||||
round(
|
||||
coverage * 100.0,
|
||||
2,
|
||||
)
|
||||
if coverage is not None
|
||||
else None
|
||||
),
|
||||
"coverage_status": status,
|
||||
}
|
||||
)
|
||||
|
||||
rows.sort(key=author_sort_key)
|
||||
|
||||
unique_work_coverage = (
|
||||
len(classified_source_work_ids) / len(selected_works)
|
||||
if selected_works
|
||||
else None
|
||||
)
|
||||
|
||||
assignment_coverage = (
|
||||
author_work_assignments_classified / author_work_assignments_total
|
||||
if author_work_assignments_total
|
||||
else None
|
||||
)
|
||||
|
||||
target_outside_source = classified_work_ids - set(selected_works)
|
||||
|
||||
return {
|
||||
"summary": {
|
||||
"created_at": utc_now(),
|
||||
"target_index": TARGET_INDEX,
|
||||
"works_index": WORKS_INDEX,
|
||||
"work_year_gte": work_year_gte,
|
||||
"authors_file": str(authors_path.resolve()),
|
||||
"authors_total": len(authors),
|
||||
"source_unique_works": len(selected_works),
|
||||
"target_index_documents": len(classified_work_ids),
|
||||
"target_index_initial_count": (initial_target_count),
|
||||
"target_index_final_count": (final_target_count),
|
||||
"target_index_count_consistent": (
|
||||
initial_target_count
|
||||
== final_target_count
|
||||
== target_documents_scanned
|
||||
== len(classified_work_ids)
|
||||
),
|
||||
"classified_source_works": len(classified_source_work_ids),
|
||||
"unclassified_source_works": (
|
||||
len(selected_works) - len(classified_source_work_ids)
|
||||
),
|
||||
"unique_work_coverage_percent": (
|
||||
round(
|
||||
unique_work_coverage * 100.0,
|
||||
2,
|
||||
)
|
||||
if unique_work_coverage is not None
|
||||
else None
|
||||
),
|
||||
"author_work_assignments_total": (author_work_assignments_total),
|
||||
"author_work_assignments_classified": (author_work_assignments_classified),
|
||||
"author_work_assignment_coverage_percent": (
|
||||
round(
|
||||
assignment_coverage * 100.0,
|
||||
2,
|
||||
)
|
||||
if assignment_coverage is not None
|
||||
else None
|
||||
),
|
||||
"authors_by_status": {
|
||||
"complete": status_counts["complete"],
|
||||
"partial": status_counts["partial"],
|
||||
"not_started": status_counts["not_started"],
|
||||
"no_works": status_counts["no_works"],
|
||||
},
|
||||
},
|
||||
"data_quality": {
|
||||
"duplicate_author_records": (duplicate_author_records),
|
||||
**source_quality,
|
||||
"target_documents_outside_source_work_set": (len(target_outside_source)),
|
||||
"target_documents_outside_source_work_set_samples": (
|
||||
sorted(target_outside_source)[:SAMPLE_SIZE]
|
||||
),
|
||||
},
|
||||
"sorting": {
|
||||
"primary": ("coverage percentage descending"),
|
||||
"secondary": ("total_works descending"),
|
||||
"tertiary": (
|
||||
"classified_works descending, "
|
||||
"display_name ascending, "
|
||||
"author_id ascending"
|
||||
),
|
||||
"authors_with_no_works": "last",
|
||||
},
|
||||
"notes": [
|
||||
(
|
||||
"total_works is calculated directly from "
|
||||
"openalex-works* for the listed UDE authors."
|
||||
),
|
||||
(
|
||||
f"Only works with publication_year >= "
|
||||
f"{work_year_gte} are included, matching the "
|
||||
"classification pipeline."
|
||||
),
|
||||
(
|
||||
"Duplicate work documents across matching "
|
||||
"OpenAlex indices are reduced to one work ID. "
|
||||
"The openalex-works document is preferred; "
|
||||
"otherwise the newest updated_date is used."
|
||||
),
|
||||
(
|
||||
"A coauthored work is counted once for every "
|
||||
"listed UDE author on that work."
|
||||
),
|
||||
(
|
||||
"The script is read-only and does not modify "
|
||||
"Elasticsearch or the author JSONL file."
|
||||
),
|
||||
],
|
||||
"authors": rows,
|
||||
}
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(
|
||||
description=(
|
||||
"Report classification coverage for every author "
|
||||
"in a UDE author JSONL list using OpenAlex works "
|
||||
"stored in Elasticsearch."
|
||||
)
|
||||
)
|
||||
parser.add_argument(
|
||||
"--authors",
|
||||
type=Path,
|
||||
default=DEFAULT_AUTHORS_FILE,
|
||||
help=("Path to ude_authors_set.jsonl."),
|
||||
)
|
||||
parser.add_argument(
|
||||
"--work-year-gte",
|
||||
type=int,
|
||||
default=WORK_YEAR_GTE,
|
||||
help=("Minimum publication year included in total_works."),
|
||||
)
|
||||
parser.add_argument(
|
||||
"--output",
|
||||
type=Path,
|
||||
default=None,
|
||||
help=("Optional output JSON path."),
|
||||
)
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
args = parse_args()
|
||||
|
||||
authors_path = args.authors.resolve()
|
||||
output_path = (
|
||||
args.output.resolve()
|
||||
if args.output is not None
|
||||
else (
|
||||
DEFAULT_OUTPUT_DIR
|
||||
/ (f"ude_author_classification_coverage_{timestamp()}.json")
|
||||
).resolve()
|
||||
)
|
||||
|
||||
authors, duplicate_author_records = load_authors(authors_path)
|
||||
author_ids = set(authors)
|
||||
|
||||
print(f"UDE authors loaded: {len(authors)}")
|
||||
|
||||
client = ElasticsearchClient()
|
||||
|
||||
(
|
||||
initial_target_count,
|
||||
final_target_count,
|
||||
classified_work_ids,
|
||||
target_documents_scanned,
|
||||
) = fetch_classified_work_ids(client)
|
||||
|
||||
print(f"Unique classified work IDs: {len(classified_work_ids)}")
|
||||
|
||||
selected_works, source_quality = fetch_source_works(
|
||||
client=client,
|
||||
author_ids=author_ids,
|
||||
work_year_gte=args.work_year_gte,
|
||||
)
|
||||
|
||||
print(f"Unique source works: {len(selected_works)}")
|
||||
|
||||
report = build_report(
|
||||
authors_path=authors_path,
|
||||
authors=authors,
|
||||
duplicate_author_records=(duplicate_author_records),
|
||||
initial_target_count=(initial_target_count),
|
||||
final_target_count=(final_target_count),
|
||||
classified_work_ids=(classified_work_ids),
|
||||
target_documents_scanned=(target_documents_scanned),
|
||||
selected_works=selected_works,
|
||||
source_quality=source_quality,
|
||||
work_year_gte=args.work_year_gte,
|
||||
)
|
||||
|
||||
output_path.parent.mkdir(
|
||||
parents=True,
|
||||
exist_ok=True,
|
||||
)
|
||||
output_path.write_text(
|
||||
json.dumps(
|
||||
report,
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
summary = report["summary"]
|
||||
statuses = summary["authors_by_status"]
|
||||
|
||||
print(f"Classified source works: {summary['classified_source_works']}")
|
||||
print(f"Unique work coverage: {summary['unique_work_coverage_percent']}%")
|
||||
print(
|
||||
"Authors complete/partial/not started/no works: "
|
||||
f"{statuses['complete']}/"
|
||||
f"{statuses['partial']}/"
|
||||
f"{statuses['not_started']}/"
|
||||
f"{statuses['no_works']}"
|
||||
)
|
||||
print(f"Output: {output_path}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,757 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from openai import OpenAI
|
||||
|
||||
PROJECT_ROOT = Path(__file__).resolve().parent
|
||||
CLASSIFICATION_DATA_DIR = PROJECT_ROOT / "classification_data"
|
||||
LLM_RESULTS_DIR = PROJECT_ROOT / "llm_results"
|
||||
PROMPT_FILE = PROJECT_ROOT / "prompt_frascati.txt"
|
||||
RUN_SUMMARY_FILE = LLM_RESULTS_DIR / "run_summary.json"
|
||||
|
||||
LLM_BASE_URL = "https://project.nes.uni-due.de/llm2/v1/"
|
||||
LLM_API_KEY = "c2d5e7ccf7a4760dd3d19bed2caed9d85ff7437400e0ea82a6d6f912ebc2f212"
|
||||
LLM_MODEL = "gemma4-e4b"
|
||||
|
||||
SKIP_IF_ALREADY_EXISTS = True
|
||||
WARM_UP_PREFIX_CACHE = True
|
||||
MAX_WORKERS = 10
|
||||
MAX_TOKENS = 2048
|
||||
TEMPERATURE = 0
|
||||
TOP_P = 1.0
|
||||
TOP_K = 64
|
||||
RETRY_ATTEMPTS = 3
|
||||
RETRY_DELAY_SECONDS = 2.0
|
||||
REQUEST_TIMEOUT_SECONDS = 180.0
|
||||
SCHEMA_NAME = "frascati_research_orientation"
|
||||
|
||||
CATEGORIES = {
|
||||
"basic_research",
|
||||
"applied_research",
|
||||
"experimental_development",
|
||||
"non_research",
|
||||
}
|
||||
PASTEUR_QUADRANTS = {
|
||||
"pure_basic",
|
||||
"use_inspired_basic",
|
||||
"pure_applied",
|
||||
"not_applicable",
|
||||
}
|
||||
CONFIDENCE_VALUES = {"high", "medium", "low"}
|
||||
SIGNAL_VALUES = {
|
||||
"title",
|
||||
"abstract",
|
||||
"venue",
|
||||
"work_type",
|
||||
"topics",
|
||||
"funders",
|
||||
"year",
|
||||
"language",
|
||||
}
|
||||
|
||||
RESPONSE_SCHEMA: dict[str, Any] = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"primary_category": {"type": "string", "enum": sorted(CATEGORIES)},
|
||||
"applied_orientation_score": {
|
||||
"anyOf": [
|
||||
{"type": "integer", "minimum": 0, "maximum": 100},
|
||||
{"type": "null"},
|
||||
]
|
||||
},
|
||||
"pasteur_quadrant": {
|
||||
"type": "string",
|
||||
"enum": sorted(PASTEUR_QUADRANTS),
|
||||
},
|
||||
"confidence": {"type": "string", "enum": sorted(CONFIDENCE_VALUES)},
|
||||
"signals_used": {
|
||||
"type": "array",
|
||||
"items": {"type": "string", "enum": sorted(SIGNAL_VALUES)},
|
||||
},
|
||||
"insufficient_context": {"type": "boolean"},
|
||||
"rationale": {"type": "string", "minLength": 1},
|
||||
},
|
||||
"required": [
|
||||
"primary_category",
|
||||
"applied_orientation_score",
|
||||
"pasteur_quadrant",
|
||||
"confidence",
|
||||
"signals_used",
|
||||
"insufficient_context",
|
||||
"rationale",
|
||||
],
|
||||
"additionalProperties": False,
|
||||
}
|
||||
|
||||
|
||||
def read_json(path: Path) -> Any:
|
||||
with path.open("r", encoding="utf-8") as file:
|
||||
return json.load(file)
|
||||
|
||||
|
||||
def write_json(path: Path, data: Any) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temp_path = path.with_suffix(path.suffix + ".tmp")
|
||||
temp_path.write_text(
|
||||
json.dumps(data, ensure_ascii=False, indent=2),
|
||||
encoding="utf-8",
|
||||
)
|
||||
temp_path.replace(path)
|
||||
|
||||
|
||||
def load_prompt() -> str:
|
||||
if not PROMPT_FILE.exists():
|
||||
raise FileNotFoundError(PROMPT_FILE)
|
||||
prompt = PROMPT_FILE.read_text(encoding="utf-8").strip()
|
||||
if not prompt:
|
||||
raise RuntimeError(f"Prompt file is empty: {PROMPT_FILE}")
|
||||
return prompt
|
||||
|
||||
|
||||
def person_filename(person_id: str) -> str:
|
||||
return person_id.rstrip("/").rsplit("/", 1)[-1]
|
||||
|
||||
|
||||
def clean_json_content(content: str) -> str:
|
||||
cleaned = content.strip()
|
||||
if cleaned.startswith("```"):
|
||||
lines = cleaned.splitlines()[1:]
|
||||
if lines and lines[-1].strip() == "```":
|
||||
lines = lines[:-1]
|
||||
cleaned = "\n".join(lines).strip()
|
||||
return cleaned
|
||||
|
||||
|
||||
def is_number(value: Any) -> bool:
|
||||
return isinstance(value, (int, float)) and not isinstance(value, bool)
|
||||
|
||||
|
||||
def validate_classification(classification: dict[str, Any]) -> list[str]:
|
||||
errors: list[str] = []
|
||||
category = classification.get("primary_category")
|
||||
score = classification.get("applied_orientation_score")
|
||||
quadrant = classification.get("pasteur_quadrant")
|
||||
confidence = classification.get("confidence")
|
||||
signals = classification.get("signals_used")
|
||||
insufficient_context = classification.get("insufficient_context")
|
||||
rationale = classification.get("rationale")
|
||||
|
||||
if category not in CATEGORIES:
|
||||
errors.append("invalid_primary_category")
|
||||
if quadrant not in PASTEUR_QUADRANTS:
|
||||
errors.append("invalid_pasteur_quadrant")
|
||||
if confidence not in CONFIDENCE_VALUES:
|
||||
errors.append("invalid_confidence")
|
||||
|
||||
if not isinstance(signals, list):
|
||||
errors.append("signals_used_must_be_list")
|
||||
else:
|
||||
if any(signal not in SIGNAL_VALUES for signal in signals):
|
||||
errors.append("invalid_signals_used")
|
||||
if len(signals) != len(set(signals)):
|
||||
errors.append("signals_used_must_be_unique")
|
||||
|
||||
if not isinstance(insufficient_context, bool):
|
||||
errors.append("insufficient_context_must_be_boolean")
|
||||
if not isinstance(rationale, str) or not rationale.strip():
|
||||
errors.append("rationale_missing_or_empty")
|
||||
|
||||
if category == "non_research":
|
||||
if score is not None:
|
||||
errors.append("non_research_score_must_be_null")
|
||||
if quadrant != "not_applicable":
|
||||
errors.append("non_research_quadrant_must_be_not_applicable")
|
||||
|
||||
if category == "basic_research":
|
||||
if not is_number(score):
|
||||
errors.append("basic_research_score_missing")
|
||||
elif quadrant == "use_inspired_basic" and not 25 <= score <= 45:
|
||||
errors.append("basic_research_score_outside_expected_range")
|
||||
elif quadrant != "use_inspired_basic" and not 0 <= score <= 30:
|
||||
errors.append("basic_research_score_outside_expected_range")
|
||||
if quadrant not in {"pure_basic", "use_inspired_basic"}:
|
||||
errors.append("basic_research_quadrant_mismatch")
|
||||
|
||||
if category == "applied_research":
|
||||
if not is_number(score):
|
||||
errors.append("applied_research_score_missing")
|
||||
elif not 31 <= score <= 70:
|
||||
errors.append("applied_research_score_outside_expected_range")
|
||||
if quadrant != "pure_applied":
|
||||
errors.append("applied_research_quadrant_mismatch")
|
||||
|
||||
if category == "experimental_development":
|
||||
if not is_number(score):
|
||||
errors.append("experimental_development_score_missing")
|
||||
elif not 71 <= score <= 100:
|
||||
errors.append("experimental_development_score_outside_expected_range")
|
||||
if quadrant != "pure_applied":
|
||||
errors.append("experimental_development_quadrant_mismatch")
|
||||
|
||||
return errors
|
||||
|
||||
|
||||
def store_classification(classification: dict[str, Any]) -> dict[str, Any]:
|
||||
stored = dict(classification)
|
||||
stored["classification_reason"] = stored.pop("rationale")
|
||||
return stored
|
||||
|
||||
|
||||
def value_from(value: Any, field: str) -> int:
|
||||
if value is None:
|
||||
return 0
|
||||
if isinstance(value, dict):
|
||||
return int(value.get(field, 0) or 0)
|
||||
return int(getattr(value, field, 0) or 0)
|
||||
|
||||
|
||||
def empty_usage() -> dict[str, int]:
|
||||
return {
|
||||
"prompt_tokens": 0,
|
||||
"uncached_prompt_tokens": 0,
|
||||
"completion_tokens": 0,
|
||||
"real_total_usage": 0,
|
||||
}
|
||||
|
||||
|
||||
def usage_dict(usage: Any) -> dict[str, int]:
|
||||
prompt_tokens = value_from(usage, "prompt_tokens")
|
||||
completion_tokens = value_from(usage, "completion_tokens")
|
||||
details = (
|
||||
usage.get("prompt_tokens_details")
|
||||
if isinstance(usage, dict)
|
||||
else getattr(usage, "prompt_tokens_details", None)
|
||||
)
|
||||
cached_tokens = min(
|
||||
value_from(details, "cached_tokens"),
|
||||
prompt_tokens,
|
||||
)
|
||||
uncached_prompt_tokens = max(
|
||||
prompt_tokens - cached_tokens,
|
||||
0,
|
||||
)
|
||||
return {
|
||||
"prompt_tokens": prompt_tokens,
|
||||
"uncached_prompt_tokens": uncached_prompt_tokens,
|
||||
"completion_tokens": completion_tokens,
|
||||
"real_total_usage": (uncached_prompt_tokens + completion_tokens),
|
||||
}
|
||||
|
||||
|
||||
def normalize_usage_record(usage: Any) -> dict[str, int]:
|
||||
if not isinstance(usage, dict):
|
||||
return empty_usage()
|
||||
|
||||
prompt_tokens = int(usage.get("prompt_tokens") or 0)
|
||||
completion_tokens = int(usage.get("completion_tokens") or 0)
|
||||
|
||||
if "uncached_prompt_tokens" in usage:
|
||||
uncached_prompt_tokens = int(usage.get("uncached_prompt_tokens") or 0)
|
||||
elif "cached_prompt_tokens" in usage:
|
||||
cached_prompt_tokens = min(
|
||||
int(usage.get("cached_prompt_tokens") or 0),
|
||||
prompt_tokens,
|
||||
)
|
||||
uncached_prompt_tokens = max(
|
||||
prompt_tokens - cached_prompt_tokens,
|
||||
0,
|
||||
)
|
||||
else:
|
||||
uncached_prompt_tokens = prompt_tokens
|
||||
|
||||
uncached_prompt_tokens = min(
|
||||
max(uncached_prompt_tokens, 0),
|
||||
prompt_tokens,
|
||||
)
|
||||
|
||||
return {
|
||||
"prompt_tokens": prompt_tokens,
|
||||
"uncached_prompt_tokens": uncached_prompt_tokens,
|
||||
"completion_tokens": completion_tokens,
|
||||
"real_total_usage": (uncached_prompt_tokens + completion_tokens),
|
||||
}
|
||||
|
||||
|
||||
def normalize_result_for_storage(
|
||||
result: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
debug = result.get("llm_debug")
|
||||
if isinstance(debug, dict):
|
||||
debug["usage"] = normalize_usage_record(debug.get("usage"))
|
||||
return result
|
||||
|
||||
|
||||
def deduplicate_works(works: Any) -> list[dict[str, Any]]:
|
||||
if not isinstance(works, list):
|
||||
raise ValueError("works must be a list")
|
||||
|
||||
works_by_id: dict[str, dict[str, Any]] = {}
|
||||
for work in works:
|
||||
if not isinstance(work, dict):
|
||||
raise ValueError("Each work must be an object")
|
||||
work_id = work.get("work_id")
|
||||
if not isinstance(work_id, str) or not work_id:
|
||||
raise ValueError("Each work must have a non-empty work_id")
|
||||
existing = works_by_id.get(work_id)
|
||||
if existing is None:
|
||||
works_by_id[work_id] = work
|
||||
elif existing != work:
|
||||
raise ValueError(f"Conflicting input records for work_id {work_id}")
|
||||
return list(works_by_id.values())
|
||||
|
||||
|
||||
def make_error_result(
|
||||
work: dict[str, Any],
|
||||
started: float,
|
||||
errors: list[str],
|
||||
attempts: int,
|
||||
) -> dict[str, Any]:
|
||||
return {
|
||||
"work_id": work.get("work_id"),
|
||||
"doi": work.get("doi"),
|
||||
"input": work.get("input"),
|
||||
"classification": None,
|
||||
"llm_debug": {
|
||||
"status": "error",
|
||||
"content": None,
|
||||
"finish_reason": None,
|
||||
"duration_seconds": round(time.perf_counter() - started, 3),
|
||||
"attempt_count": attempts,
|
||||
"attempt_errors": errors,
|
||||
"usage": empty_usage(),
|
||||
"error": errors[-1] if errors else "Unknown error",
|
||||
"validation_errors": [],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def classify_work(
|
||||
client: OpenAI,
|
||||
system_prompt: str,
|
||||
work: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
input_data = work.get("input")
|
||||
if not isinstance(input_data, dict):
|
||||
raise ValueError(f"Missing input for {work.get('work_id')}")
|
||||
|
||||
started = time.perf_counter()
|
||||
attempt_errors: list[str] = []
|
||||
|
||||
for attempt in range(1, RETRY_ATTEMPTS + 1):
|
||||
try:
|
||||
response = client.chat.completions.create(
|
||||
model=LLM_MODEL,
|
||||
messages=[
|
||||
{"role": "system", "content": system_prompt},
|
||||
{
|
||||
"role": "user",
|
||||
"content": json.dumps(
|
||||
input_data,
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
),
|
||||
},
|
||||
],
|
||||
temperature=TEMPERATURE,
|
||||
max_tokens=MAX_TOKENS,
|
||||
top_p=TOP_P,
|
||||
response_format={
|
||||
"type": "json_schema",
|
||||
"json_schema": {
|
||||
"name": SCHEMA_NAME,
|
||||
"strict": True,
|
||||
"schema": RESPONSE_SCHEMA,
|
||||
},
|
||||
},
|
||||
extra_body={"top_k": TOP_K},
|
||||
)
|
||||
|
||||
if not response.choices:
|
||||
raise RuntimeError("LLM response has no choices")
|
||||
|
||||
choice = response.choices[0]
|
||||
content = choice.message.content or ""
|
||||
if not content.strip():
|
||||
raise RuntimeError("LLM response content is empty")
|
||||
|
||||
classification = json.loads(clean_json_content(content))
|
||||
if not isinstance(classification, dict):
|
||||
raise ValueError("LLM response is not a JSON object")
|
||||
|
||||
return {
|
||||
"work_id": work.get("work_id"),
|
||||
"doi": work.get("doi"),
|
||||
"input": input_data,
|
||||
"classification": store_classification(classification),
|
||||
"llm_debug": {
|
||||
"status": "ok",
|
||||
"content": content,
|
||||
"finish_reason": choice.finish_reason,
|
||||
"duration_seconds": round(time.perf_counter() - started, 3),
|
||||
"attempt_count": attempt,
|
||||
"attempt_errors": attempt_errors,
|
||||
"usage": usage_dict(response.usage),
|
||||
"error": None,
|
||||
"validation_errors": validate_classification(classification),
|
||||
},
|
||||
}
|
||||
|
||||
except Exception as exception:
|
||||
attempt_errors.append(f"{type(exception).__name__}: {exception}")
|
||||
status_code = getattr(exception, "status_code", None)
|
||||
if status_code == 400 or type(exception).__name__ == "BadRequestError":
|
||||
return make_error_result(work, started, attempt_errors, attempt)
|
||||
if attempt < RETRY_ATTEMPTS:
|
||||
time.sleep(RETRY_DELAY_SECONDS * attempt)
|
||||
|
||||
return make_error_result(
|
||||
work,
|
||||
started,
|
||||
attempt_errors,
|
||||
len(attempt_errors),
|
||||
)
|
||||
|
||||
|
||||
def make_summary(results: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
usage = empty_usage()
|
||||
durations: list[float] = []
|
||||
parsed_ok = 0
|
||||
api_errors = 0
|
||||
validation_errors = 0
|
||||
|
||||
for result in results:
|
||||
debug = result.get("llm_debug") or {}
|
||||
result_usage = normalize_usage_record(debug.get("usage"))
|
||||
|
||||
for key in usage:
|
||||
usage[key] += result_usage[key]
|
||||
|
||||
duration = debug.get("duration_seconds")
|
||||
if isinstance(duration, (int, float)):
|
||||
durations.append(float(duration))
|
||||
|
||||
errors = debug.get("validation_errors") or []
|
||||
if debug.get("status") == "ok" and not errors:
|
||||
parsed_ok += 1
|
||||
elif debug.get("status") != "ok":
|
||||
api_errors += 1
|
||||
|
||||
if errors:
|
||||
validation_errors += 1
|
||||
|
||||
works_total = len(results)
|
||||
duration_sum = round(sum(durations), 3)
|
||||
|
||||
return {
|
||||
"works_total": works_total,
|
||||
"parsed_ok": parsed_ok,
|
||||
"api_errors": api_errors,
|
||||
"validation_errors": validation_errors,
|
||||
"usage": usage,
|
||||
"average_usage_per_work": {
|
||||
key: (round(value / works_total, 2) if works_total else 0.0)
|
||||
for key, value in usage.items()
|
||||
},
|
||||
"duration_seconds_sum_of_requests": duration_sum,
|
||||
"average_duration_seconds_per_work": (
|
||||
round(duration_sum / len(durations), 3) if durations else 0.0
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def make_output(
|
||||
person: dict[str, Any], results: list[dict[str, Any]]
|
||||
) -> dict[str, Any]:
|
||||
return {
|
||||
"person": person,
|
||||
"config": {
|
||||
"base_url": LLM_BASE_URL,
|
||||
"model": LLM_MODEL,
|
||||
"prompt_file": PROMPT_FILE.name,
|
||||
"classification_data_dir": CLASSIFICATION_DATA_DIR.name,
|
||||
"output_dir": LLM_RESULTS_DIR.name,
|
||||
"temperature": TEMPERATURE,
|
||||
"max_tokens": MAX_TOKENS,
|
||||
"top_p": TOP_P,
|
||||
"top_k": TOP_K,
|
||||
"max_workers": MAX_WORKERS,
|
||||
"skip_if_already_exists": SKIP_IF_ALREADY_EXISTS,
|
||||
"response_format": "json_schema",
|
||||
"schema_name": SCHEMA_NAME,
|
||||
"strict_schema": True,
|
||||
},
|
||||
"summary": make_summary(results),
|
||||
"results": results,
|
||||
}
|
||||
|
||||
|
||||
def load_existing_results(
|
||||
output_path: Path,
|
||||
works_by_id: dict[str, dict[str, Any]],
|
||||
) -> dict[str, dict[str, Any]]:
|
||||
if not output_path.exists():
|
||||
return {}
|
||||
|
||||
data = read_json(output_path)
|
||||
results = data.get("results", []) if isinstance(data, dict) else []
|
||||
existing: dict[str, dict[str, Any]] = {}
|
||||
|
||||
for result in results:
|
||||
if not isinstance(result, dict):
|
||||
continue
|
||||
work_id = result.get("work_id")
|
||||
if not isinstance(work_id, str) or work_id not in works_by_id:
|
||||
continue
|
||||
debug = result.get("llm_debug") or {}
|
||||
reusable = (
|
||||
debug.get("status") == "ok"
|
||||
and isinstance(result.get("classification"), dict)
|
||||
and result.get("input") == works_by_id[work_id].get("input")
|
||||
)
|
||||
if not reusable:
|
||||
continue
|
||||
previous = existing.get(work_id)
|
||||
if previous is None:
|
||||
existing[work_id] = result
|
||||
elif previous != result:
|
||||
raise ValueError(f"Conflicting existing results for work_id {work_id}")
|
||||
|
||||
return existing
|
||||
|
||||
|
||||
def save_results(
|
||||
output_path: Path,
|
||||
person: dict[str, Any],
|
||||
work_ids: list[str],
|
||||
results_by_id: dict[str, dict[str, Any]],
|
||||
) -> list[dict[str, Any]]:
|
||||
ordered = [
|
||||
normalize_result_for_storage(results_by_id[work_id])
|
||||
for work_id in work_ids
|
||||
if work_id in results_by_id
|
||||
]
|
||||
write_json(output_path, make_output(person, ordered))
|
||||
return ordered
|
||||
|
||||
|
||||
def process_person(
|
||||
input_path: Path,
|
||||
client: OpenAI,
|
||||
system_prompt: str,
|
||||
warm_up_needed: bool,
|
||||
) -> tuple[dict[str, Any], bool]:
|
||||
data = read_json(input_path)
|
||||
if not isinstance(data, dict):
|
||||
raise ValueError(f"Root is not an object in {input_path}")
|
||||
|
||||
person = data.get("person")
|
||||
if not isinstance(person, dict):
|
||||
raise ValueError(f"person is not an object in {input_path}")
|
||||
|
||||
person_id = person.get("id")
|
||||
if not isinstance(person_id, str) or not person_id:
|
||||
raise ValueError(f"Missing person id in {input_path}")
|
||||
|
||||
works = deduplicate_works(data.get("works"))
|
||||
works_by_id = {work["work_id"]: work for work in works}
|
||||
work_ids = list(works_by_id)
|
||||
output_path = LLM_RESULTS_DIR / f"{person_filename(person_id)}_results.json"
|
||||
results_by_id = (
|
||||
load_existing_results(output_path, works_by_id)
|
||||
if SKIP_IF_ALREADY_EXISTS
|
||||
else {}
|
||||
)
|
||||
pending = [
|
||||
works_by_id[work_id] for work_id in work_ids if work_id not in results_by_id
|
||||
]
|
||||
requested_count = len(pending)
|
||||
warm_up_succeeded = False
|
||||
|
||||
if not pending:
|
||||
print(f"Skip LLM calls: {output_path.name}")
|
||||
|
||||
if pending and warm_up_needed:
|
||||
work = pending.pop(0)
|
||||
print(f"Prefix cache warm-up: {work['work_id']}")
|
||||
result = classify_work(client, system_prompt, work)
|
||||
results_by_id[work["work_id"]] = result
|
||||
saved = save_results(output_path, person, work_ids, results_by_id)
|
||||
print(f"{person.get('display_name')}: {len(saved)}/{len(works)}")
|
||||
|
||||
if (result.get("llm_debug") or {}).get("status") != "ok":
|
||||
error = (result.get("llm_debug") or {}).get("error")
|
||||
raise RuntimeError(
|
||||
"Prefix cache warm-up failed. Parallel processing was not started. "
|
||||
f"Error: {error}"
|
||||
)
|
||||
warm_up_succeeded = True
|
||||
|
||||
if pending:
|
||||
executor = ThreadPoolExecutor(max_workers=min(MAX_WORKERS, len(pending)))
|
||||
futures = {
|
||||
executor.submit(classify_work, client, system_prompt, work): work
|
||||
for work in pending
|
||||
}
|
||||
|
||||
try:
|
||||
for future in as_completed(futures):
|
||||
work = futures[future]
|
||||
result = future.result()
|
||||
results_by_id[work["work_id"]] = result
|
||||
saved = save_results(output_path, person, work_ids, results_by_id)
|
||||
print(f"{person.get('display_name')}: {len(saved)}/{len(works)}")
|
||||
except KeyboardInterrupt:
|
||||
for future in futures:
|
||||
future.cancel()
|
||||
save_results(output_path, person, work_ids, results_by_id)
|
||||
executor.shutdown(wait=False, cancel_futures=True)
|
||||
print("Interrupted. Completed results were saved.")
|
||||
raise
|
||||
else:
|
||||
executor.shutdown(wait=True)
|
||||
|
||||
final_results = save_results(output_path, person, work_ids, results_by_id)
|
||||
output = make_output(person, final_results)
|
||||
return {
|
||||
"person": person,
|
||||
"source_file": input_path.relative_to(PROJECT_ROOT).as_posix(),
|
||||
"output_file": output_path.relative_to(PROJECT_ROOT).as_posix(),
|
||||
"summary": output["summary"],
|
||||
"skipped": requested_count == 0,
|
||||
"works_reused": len(works) - requested_count,
|
||||
"works_requested": requested_count,
|
||||
}, warm_up_succeeded
|
||||
|
||||
|
||||
def make_run_summary(
|
||||
person_runs: list[dict[str, Any]],
|
||||
) -> dict[str, Any]:
|
||||
summary: dict[str, Any] = {
|
||||
"persons_total": len(person_runs),
|
||||
"persons_skipped": sum(bool(item.get("skipped")) for item in person_runs),
|
||||
"works_total": 0,
|
||||
"works_reused": 0,
|
||||
"works_requested": 0,
|
||||
"parsed_ok": 0,
|
||||
"api_errors": 0,
|
||||
"validation_errors": 0,
|
||||
}
|
||||
usage = empty_usage()
|
||||
duration_sum = 0.0
|
||||
|
||||
for item in person_runs:
|
||||
person_summary = item["summary"]
|
||||
|
||||
for key in (
|
||||
"works_total",
|
||||
"parsed_ok",
|
||||
"api_errors",
|
||||
"validation_errors",
|
||||
):
|
||||
summary[key] += int(person_summary.get(key) or 0)
|
||||
|
||||
summary["works_reused"] += int(item.get("works_reused") or 0)
|
||||
summary["works_requested"] += int(item.get("works_requested") or 0)
|
||||
|
||||
person_usage = normalize_usage_record(person_summary.get("usage"))
|
||||
for key in usage:
|
||||
usage[key] += person_usage[key]
|
||||
|
||||
duration_sum += float(
|
||||
person_summary.get("duration_seconds_sum_of_requests") or 0
|
||||
)
|
||||
|
||||
works_total = summary["works_total"]
|
||||
summary["usage"] = usage
|
||||
summary["average_usage_per_work"] = {
|
||||
key: (round(value / works_total, 2) if works_total else 0.0)
|
||||
for key, value in usage.items()
|
||||
}
|
||||
summary["duration_seconds_sum_of_requests"] = round(
|
||||
duration_sum,
|
||||
3,
|
||||
)
|
||||
summary["average_duration_seconds_per_work"] = (
|
||||
round(duration_sum / works_total, 3) if works_total else 0.0
|
||||
)
|
||||
|
||||
return {
|
||||
"config": {
|
||||
"base_url": LLM_BASE_URL,
|
||||
"model": LLM_MODEL,
|
||||
"prompt_file": PROMPT_FILE.name,
|
||||
"classification_data_dir": (CLASSIFICATION_DATA_DIR.name),
|
||||
"output_dir": LLM_RESULTS_DIR.name,
|
||||
"max_workers": MAX_WORKERS,
|
||||
"skip_if_already_exists": (SKIP_IF_ALREADY_EXISTS),
|
||||
},
|
||||
"summary": summary,
|
||||
"persons": person_runs,
|
||||
}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
if LLM_API_KEY == "тут код" or not LLM_API_KEY.strip():
|
||||
raise RuntimeError("Set LLM_API_KEY in run_llm.py")
|
||||
if not CLASSIFICATION_DATA_DIR.exists():
|
||||
raise FileNotFoundError(CLASSIFICATION_DATA_DIR)
|
||||
if not PROMPT_FILE.exists():
|
||||
raise FileNotFoundError(PROMPT_FILE)
|
||||
|
||||
input_files = sorted(CLASSIFICATION_DATA_DIR.glob("A*.json"))
|
||||
if not input_files:
|
||||
raise FileNotFoundError(f"No A*.json files found in {CLASSIFICATION_DATA_DIR}")
|
||||
|
||||
LLM_RESULTS_DIR.mkdir(parents=True, exist_ok=True)
|
||||
client = OpenAI(
|
||||
base_url=LLM_BASE_URL,
|
||||
api_key=LLM_API_KEY,
|
||||
timeout=REQUEST_TIMEOUT_SECONDS,
|
||||
)
|
||||
system_prompt = load_prompt()
|
||||
person_runs: list[dict[str, Any]] = []
|
||||
prefix_cache_warmed = False
|
||||
|
||||
try:
|
||||
for input_file in input_files:
|
||||
print(f"Processing: {input_file.name}")
|
||||
person_run, warmed = process_person(
|
||||
input_file,
|
||||
client,
|
||||
system_prompt,
|
||||
WARM_UP_PREFIX_CACHE and not prefix_cache_warmed,
|
||||
)
|
||||
prefix_cache_warmed = prefix_cache_warmed or warmed
|
||||
person_runs.append(person_run)
|
||||
write_json(
|
||||
RUN_SUMMARY_FILE,
|
||||
make_run_summary(person_runs),
|
||||
)
|
||||
except KeyboardInterrupt:
|
||||
write_json(
|
||||
RUN_SUMMARY_FILE,
|
||||
make_run_summary(person_runs),
|
||||
)
|
||||
print("Classification interrupted safely.")
|
||||
return
|
||||
|
||||
run_summary = make_run_summary(person_runs)
|
||||
write_json(RUN_SUMMARY_FILE, run_summary)
|
||||
print("Classification completed.")
|
||||
print(f"Persons: {run_summary['summary']['persons_total']}")
|
||||
print(f"Skipped: {run_summary['summary']['persons_skipped']}")
|
||||
print(f"Works: {run_summary['summary']['works_total']}")
|
||||
print(f"Reused: {run_summary['summary']['works_reused']}")
|
||||
print(f"Requested: {run_summary['summary']['works_requested']}")
|
||||
print(f"Parsed OK: {run_summary['summary']['parsed_ok']}")
|
||||
print(f"Validation errors: {run_summary['summary']['validation_errors']}")
|
||||
print(f"API errors: {run_summary['summary']['api_errors']}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"run_id": "20260717_005426_057540",
|
||||
"started_at": "2026-07-17T00:54:26Z",
|
||||
"finished_at": "2026-07-17T00:54:57Z",
|
||||
"duration_seconds": 31.063,
|
||||
"status": "completed",
|
||||
"error": null,
|
||||
"parameters": {
|
||||
"limit": 2,
|
||||
"workers": 1,
|
||||
"model": "gemma4-e4b",
|
||||
"prompt_version": "frascati_v1",
|
||||
"sqlite_file": "C:\\Users\\Roman\\Desktop\\smartguide\\llm_evaluations\\basic_applied_experimental\\classification_pipeline_v2.sqlite3",
|
||||
"target_index": "work-classifications",
|
||||
"preflight_only": false
|
||||
},
|
||||
"classification": {
|
||||
"llm_completed": 2,
|
||||
"valid": 2,
|
||||
"invalid": 0,
|
||||
"categories": {
|
||||
"basic_research": 2
|
||||
},
|
||||
"validation_errors": {}
|
||||
},
|
||||
"indexing": {
|
||||
"newly_indexed": 2,
|
||||
"recovered_from_ready": 0
|
||||
},
|
||||
"token_usage": {
|
||||
"prompt_tokens": 6351,
|
||||
"cached_prompt_tokens": 5824,
|
||||
"uncached_prompt_tokens": 527,
|
||||
"completion_tokens": 1707,
|
||||
"real_total_usage": 2234
|
||||
},
|
||||
"throughput_indexed_per_hour": 231.79,
|
||||
"sqlite_counts_after_run": {
|
||||
"indexed": 391,
|
||||
"pending": 3
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
{
|
||||
"run_id": "20260717_005603_805495",
|
||||
"started_at": "2026-07-17T00:56:03Z",
|
||||
"finished_at": "2026-07-17T01:12:01Z",
|
||||
"duration_seconds": 958.094,
|
||||
"status": "completed",
|
||||
"error": null,
|
||||
"parameters": {
|
||||
"limit": 1000,
|
||||
"workers": 20,
|
||||
"model": "gemma4-e4b",
|
||||
"prompt_version": "frascati_v1",
|
||||
"sqlite_file": "C:\\Users\\Roman\\Desktop\\smartguide\\llm_evaluations\\basic_applied_experimental\\classification_pipeline_v2.sqlite3",
|
||||
"target_index": "work-classifications",
|
||||
"preflight_only": false
|
||||
},
|
||||
"classification": {
|
||||
"llm_completed": 1000,
|
||||
"valid": 927,
|
||||
"invalid": 73,
|
||||
"categories": {
|
||||
"basic_research": 562,
|
||||
"applied_research": 340,
|
||||
"experimental_development": 67,
|
||||
"non_research": 31
|
||||
},
|
||||
"validation_errors": {
|
||||
"applied_research_score_outside_expected_range": 60,
|
||||
"basic_research_quadrant_score_mismatch": 12,
|
||||
"applied_research_quadrant_mismatch": 1
|
||||
}
|
||||
},
|
||||
"indexing": {
|
||||
"newly_indexed": 1000,
|
||||
"recovered_from_ready": 0
|
||||
},
|
||||
"token_usage": {
|
||||
"prompt_tokens": 3240183,
|
||||
"cached_prompt_tokens": 2912992,
|
||||
"uncached_prompt_tokens": 327191,
|
||||
"completion_tokens": 839984,
|
||||
"real_total_usage": 1167175
|
||||
},
|
||||
"throughput_indexed_per_hour": 3757.46,
|
||||
"sqlite_counts_after_run": {
|
||||
"indexed": 1392,
|
||||
"pending": 191
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
{
|
||||
"run_id": "20260717_011548_698699",
|
||||
"started_at": "2026-07-17T01:15:48Z",
|
||||
"finished_at": "2026-07-17T01:28:58Z",
|
||||
"duration_seconds": 790.125,
|
||||
"status": "completed",
|
||||
"error": null,
|
||||
"parameters": {
|
||||
"limit": 1000,
|
||||
"workers": 25,
|
||||
"model": "gemma4-e4b",
|
||||
"prompt_version": "frascati_v1",
|
||||
"sqlite_file": "C:\\Users\\Roman\\Desktop\\smartguide\\llm_evaluations\\basic_applied_experimental\\classification_pipeline_v2.sqlite3",
|
||||
"target_index": "work-classifications",
|
||||
"preflight_only": false
|
||||
},
|
||||
"classification": {
|
||||
"llm_completed": 1000,
|
||||
"valid": 940,
|
||||
"invalid": 60,
|
||||
"categories": {
|
||||
"basic_research": 575,
|
||||
"non_research": 16,
|
||||
"applied_research": 338,
|
||||
"experimental_development": 71
|
||||
},
|
||||
"validation_errors": {
|
||||
"applied_research_score_outside_expected_range": 54,
|
||||
"basic_research_quadrant_score_mismatch": 6
|
||||
}
|
||||
},
|
||||
"indexing": {
|
||||
"newly_indexed": 1000,
|
||||
"recovered_from_ready": 0
|
||||
},
|
||||
"token_usage": {
|
||||
"prompt_tokens": 3231350,
|
||||
"cached_prompt_tokens": 2913504,
|
||||
"uncached_prompt_tokens": 317846,
|
||||
"completion_tokens": 835555,
|
||||
"real_total_usage": 1153401
|
||||
},
|
||||
"throughput_indexed_per_hour": 4556.24,
|
||||
"sqlite_counts_after_run": {
|
||||
"indexed": 2392,
|
||||
"pending": 169
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
{
|
||||
"run_id": "20260717_013708_966462",
|
||||
"started_at": "2026-07-17T01:37:08Z",
|
||||
"finished_at": "2026-07-17T01:49:01Z",
|
||||
"duration_seconds": 712.64,
|
||||
"status": "completed",
|
||||
"error": null,
|
||||
"parameters": {
|
||||
"limit": 1000,
|
||||
"workers": 30,
|
||||
"model": "gemma4-e4b",
|
||||
"prompt_version": "frascati_v1",
|
||||
"sqlite_file": "C:\\Users\\Roman\\Desktop\\smartguide\\llm_evaluations\\basic_applied_experimental\\classification_pipeline_v2.sqlite3",
|
||||
"target_index": "work-classifications",
|
||||
"preflight_only": false
|
||||
},
|
||||
"classification": {
|
||||
"llm_completed": 1000,
|
||||
"valid": 948,
|
||||
"invalid": 52,
|
||||
"categories": {
|
||||
"applied_research": 360,
|
||||
"basic_research": 557,
|
||||
"experimental_development": 68,
|
||||
"non_research": 15
|
||||
},
|
||||
"validation_errors": {
|
||||
"applied_research_score_outside_expected_range": 49,
|
||||
"basic_research_quadrant_score_mismatch": 3
|
||||
}
|
||||
},
|
||||
"indexing": {
|
||||
"newly_indexed": 1000,
|
||||
"recovered_from_ready": 0
|
||||
},
|
||||
"token_usage": {
|
||||
"prompt_tokens": 3224853,
|
||||
"cached_prompt_tokens": 2927360,
|
||||
"uncached_prompt_tokens": 297493,
|
||||
"completion_tokens": 827150,
|
||||
"real_total_usage": 1124643
|
||||
},
|
||||
"throughput_indexed_per_hour": 5051.64,
|
||||
"sqlite_counts_after_run": {
|
||||
"indexed": 3393,
|
||||
"pending": 150
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
{
|
||||
"run_id": "20260717_020319_001747",
|
||||
"started_at": "2026-07-17T02:03:19Z",
|
||||
"finished_at": "2026-07-17T02:14:00Z",
|
||||
"duration_seconds": 641.141,
|
||||
"status": "completed",
|
||||
"error": null,
|
||||
"parameters": {
|
||||
"limit": 1000,
|
||||
"workers": 35,
|
||||
"model": "gemma4-e4b",
|
||||
"prompt_version": "frascati_v1",
|
||||
"sqlite_file": "C:\\Users\\Roman\\Desktop\\smartguide\\llm_evaluations\\basic_applied_experimental\\classification_pipeline_v2.sqlite3",
|
||||
"target_index": "work-classifications",
|
||||
"preflight_only": false
|
||||
},
|
||||
"classification": {
|
||||
"llm_completed": 1000,
|
||||
"valid": 935,
|
||||
"invalid": 65,
|
||||
"categories": {
|
||||
"basic_research": 559,
|
||||
"non_research": 22,
|
||||
"applied_research": 342,
|
||||
"experimental_development": 77
|
||||
},
|
||||
"validation_errors": {
|
||||
"applied_research_score_outside_expected_range": 58,
|
||||
"basic_research_quadrant_score_mismatch": 7
|
||||
}
|
||||
},
|
||||
"indexing": {
|
||||
"newly_indexed": 1000,
|
||||
"recovered_from_ready": 0
|
||||
},
|
||||
"token_usage": {
|
||||
"prompt_tokens": 3234874,
|
||||
"cached_prompt_tokens": 2913440,
|
||||
"uncached_prompt_tokens": 321434,
|
||||
"completion_tokens": 831117,
|
||||
"real_total_usage": 1152551
|
||||
},
|
||||
"throughput_indexed_per_hour": 5614.99,
|
||||
"sqlite_counts_after_run": {
|
||||
"indexed": 4393,
|
||||
"pending": 134
|
||||
}
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
{
|
||||
"run_id": "20260717_022730_111266",
|
||||
"started_at": "2026-07-17T02:27:30Z",
|
||||
"finished_at": "2026-07-17T02:37:39Z",
|
||||
"duration_seconds": 609.859,
|
||||
"status": "completed",
|
||||
"error": null,
|
||||
"parameters": {
|
||||
"limit": 1000,
|
||||
"workers": 40,
|
||||
"model": "gemma4-e4b",
|
||||
"prompt_version": "frascati_v1",
|
||||
"sqlite_file": "C:\\Users\\Roman\\Desktop\\smartguide\\llm_evaluations\\basic_applied_experimental\\classification_pipeline_v2.sqlite3",
|
||||
"target_index": "work-classifications",
|
||||
"preflight_only": false
|
||||
},
|
||||
"classification": {
|
||||
"llm_completed": 1000,
|
||||
"valid": 915,
|
||||
"invalid": 85,
|
||||
"categories": {
|
||||
"applied_research": 382,
|
||||
"non_research": 29,
|
||||
"basic_research": 526,
|
||||
"experimental_development": 63
|
||||
},
|
||||
"validation_errors": {
|
||||
"applied_research_score_outside_expected_range": 74,
|
||||
"basic_research_quadrant_score_mismatch": 9,
|
||||
"basic_research_quadrant_mismatch": 1,
|
||||
"applied_research_quadrant_mismatch": 1
|
||||
}
|
||||
},
|
||||
"indexing": {
|
||||
"newly_indexed": 1000,
|
||||
"recovered_from_ready": 0
|
||||
},
|
||||
"token_usage": {
|
||||
"prompt_tokens": 3247991,
|
||||
"cached_prompt_tokens": 2913120,
|
||||
"uncached_prompt_tokens": 334871,
|
||||
"completion_tokens": 835172,
|
||||
"real_total_usage": 1170043
|
||||
},
|
||||
"throughput_indexed_per_hour": 5903.0,
|
||||
"sqlite_counts_after_run": {
|
||||
"indexed": 5393,
|
||||
"pending": 122
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
{
|
||||
"run_id": "20260717_030100_386210",
|
||||
"started_at": "2026-07-17T03:01:00Z",
|
||||
"finished_at": "2026-07-17T06:38:43Z",
|
||||
"duration_seconds": 13062.969,
|
||||
"status": "completed",
|
||||
"error": null,
|
||||
"parameters": {
|
||||
"limit": 10000,
|
||||
"workers": 30,
|
||||
"model": "gemma4-e4b",
|
||||
"prompt_version": "frascati_v1",
|
||||
"sqlite_file": "C:\\Users\\Roman\\Desktop\\smartguide\\llm_evaluations\\basic_applied_experimental\\classification_pipeline_v2.sqlite3",
|
||||
"target_index": "work-classifications",
|
||||
"preflight_only": false
|
||||
},
|
||||
"classification": {
|
||||
"llm_completed": 10000,
|
||||
"valid": 9089,
|
||||
"invalid": 911,
|
||||
"categories": {
|
||||
"non_research": 708,
|
||||
"basic_research": 4382,
|
||||
"applied_research": 4275,
|
||||
"experimental_development": 635
|
||||
},
|
||||
"validation_errors": {
|
||||
"basic_research_quadrant_score_mismatch": 55,
|
||||
"applied_research_score_outside_expected_range": 844,
|
||||
"applied_research_quadrant_mismatch": 10,
|
||||
"experimental_development_quadrant_mismatch": 2,
|
||||
"experimental_development_score_outside_expected_range": 1
|
||||
}
|
||||
},
|
||||
"indexing": {
|
||||
"newly_indexed": 10000,
|
||||
"recovered_from_ready": 0
|
||||
},
|
||||
"token_usage": {
|
||||
"prompt_tokens": 32719632,
|
||||
"cached_prompt_tokens": 29184896,
|
||||
"uncached_prompt_tokens": 3534736,
|
||||
"completion_tokens": 8554523,
|
||||
"real_total_usage": 12089259
|
||||
},
|
||||
"throughput_indexed_per_hour": 2755.88,
|
||||
"sqlite_counts_after_run": {
|
||||
"indexed": 15402,
|
||||
"pending": 185
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"run_id": "20260717_175129_424220",
|
||||
"started_at": "2026-07-17T17:51:29Z",
|
||||
"finished_at": "2026-07-17T18:05:54Z",
|
||||
"duration_seconds": 865.141,
|
||||
"status": "completed",
|
||||
"error": null,
|
||||
"parameters": {
|
||||
"limit": 1000,
|
||||
"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": 1000,
|
||||
"valid": 1000,
|
||||
"invalid": 0,
|
||||
"categories": {
|
||||
"basic_research": 531,
|
||||
"applied_research": 386,
|
||||
"non_research": 26,
|
||||
"experimental_development": 57
|
||||
},
|
||||
"validation_errors": {}
|
||||
},
|
||||
"indexing": {
|
||||
"newly_indexed": 1000,
|
||||
"bulk_requests": 8,
|
||||
"bulk_documents_submitted": 1200,
|
||||
"bulk_failures": 0
|
||||
},
|
||||
"token_usage": {
|
||||
"prompt_tokens": 3711992,
|
||||
"cached_prompt_tokens": 3424000,
|
||||
"uncached_prompt_tokens": 287992,
|
||||
"completion_tokens": 920369,
|
||||
"real_total_usage": 1208361
|
||||
},
|
||||
"throughput_indexed_per_hour": 4161.17
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"run_id": "20260717_182758_995379",
|
||||
"started_at": "2026-07-17T18:27:58Z",
|
||||
"finished_at": "2026-07-17T18:41:42Z",
|
||||
"duration_seconds": 823.015,
|
||||
"status": "completed",
|
||||
"error": null,
|
||||
"parameters": {
|
||||
"limit": 1000,
|
||||
"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": 1000,
|
||||
"valid": 1000,
|
||||
"invalid": 0,
|
||||
"categories": {
|
||||
"basic_research": 518,
|
||||
"applied_research": 401,
|
||||
"experimental_development": 60,
|
||||
"non_research": 21
|
||||
},
|
||||
"validation_errors": {}
|
||||
},
|
||||
"indexing": {
|
||||
"newly_indexed": 1000,
|
||||
"bulk_requests": 6,
|
||||
"bulk_documents_submitted": 1000,
|
||||
"bulk_failures": 0
|
||||
},
|
||||
"token_usage": {
|
||||
"prompt_tokens": 3708032,
|
||||
"cached_prompt_tokens": 3424000,
|
||||
"uncached_prompt_tokens": 284032,
|
||||
"completion_tokens": 913796,
|
||||
"real_total_usage": 1197828
|
||||
},
|
||||
"throughput_indexed_per_hour": 4374.16
|
||||
}
|
||||
+44
@@ -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
|
||||
}
|
||||
+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
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
{
|
||||
"run_id": "20260723_154918_847690",
|
||||
"started_at": "2026-07-23T15:49:18Z",
|
||||
"finished_at": "2026-07-23T19:49:04Z",
|
||||
"duration_seconds": 14385.39,
|
||||
"status": "completed",
|
||||
"error": null,
|
||||
"parameters": {
|
||||
"limit": null,
|
||||
"workers": 25,
|
||||
"model": "gemma4-e4b",
|
||||
"prompt_version": "frascati_hard_ranges_v2",
|
||||
"target_index": "work-classifications",
|
||||
"bulk_batch_size": 200,
|
||||
"state_storage": "memory_only",
|
||||
"preflight_only": false,
|
||||
"selection_mode": "author-cohort",
|
||||
"institution_id": "https://openalex.org/I62318514",
|
||||
"institution_ror": "https://ror.org/04mz5ra38",
|
||||
"institution_name": "University of Duisburg-Essen",
|
||||
"affiliation_year_gte": 2024,
|
||||
"work_year_gte": 1950,
|
||||
"all_work_years": false
|
||||
},
|
||||
"classification": {
|
||||
"llm_completed": 16272,
|
||||
"valid": 16272,
|
||||
"invalid": 0,
|
||||
"categories": {
|
||||
"basic_research": 8658,
|
||||
"applied_research": 4889,
|
||||
"non_research": 1190,
|
||||
"experimental_development": 1535
|
||||
},
|
||||
"validation_errors": {}
|
||||
},
|
||||
"indexing": {
|
||||
"newly_indexed": 16272,
|
||||
"bulk_requests": 148,
|
||||
"bulk_documents_submitted": 16472,
|
||||
"bulk_failures": 0
|
||||
},
|
||||
"token_usage": {
|
||||
"prompt_tokens": 60051102,
|
||||
"cached_prompt_tokens": 55752000,
|
||||
"uncached_prompt_tokens": 4299102,
|
||||
"completion_tokens": 14983831,
|
||||
"real_total_usage": 19282933
|
||||
},
|
||||
"throughput_indexed_per_hour": 4072.13
|
||||
}
|
||||
@@ -1,382 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import statistics
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
PROJECT_ROOT = Path(__file__).resolve().parent
|
||||
LLM_RESULTS_DIR = PROJECT_ROOT / "llm_results"
|
||||
CLASSIFICATION_SUMMARY_DIR = PROJECT_ROOT / "classification_summary"
|
||||
OVERALL_OUTPUT = CLASSIFICATION_SUMMARY_DIR / "overall_summary.json"
|
||||
PERSON_OUTPUT = CLASSIFICATION_SUMMARY_DIR / "person_summary.json"
|
||||
|
||||
CATEGORIES = [
|
||||
"basic_research",
|
||||
"applied_research",
|
||||
"experimental_development",
|
||||
"non_research",
|
||||
]
|
||||
CONFIDENCE_VALUES = [
|
||||
"high",
|
||||
"medium",
|
||||
"low",
|
||||
]
|
||||
|
||||
|
||||
def read_json(path: Path) -> Any:
|
||||
with path.open("r", encoding="utf-8") as file:
|
||||
return json.load(file)
|
||||
|
||||
|
||||
def write_json(path: Path, data: Any) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temp_path = path.with_suffix(path.suffix + ".tmp")
|
||||
temp_path.write_text(
|
||||
json.dumps(data, ensure_ascii=False, indent=2),
|
||||
encoding="utf-8",
|
||||
)
|
||||
temp_path.replace(path)
|
||||
|
||||
|
||||
def safe_share(numerator: int, denominator: int) -> float:
|
||||
return round(numerator / denominator, 4) if denominator else 0.0
|
||||
|
||||
|
||||
def safe_mean(values: list[int | float]) -> float | None:
|
||||
return round(statistics.mean(values), 2) if values else None
|
||||
|
||||
|
||||
def safe_median(values: list[int | float]) -> float | None:
|
||||
return round(statistics.median(values), 2) if values else None
|
||||
|
||||
|
||||
def is_numeric_score(value: Any) -> bool:
|
||||
return isinstance(value, (int, float)) and not isinstance(value, bool)
|
||||
|
||||
|
||||
def has_abstract(result: dict[str, Any]) -> bool:
|
||||
input_data = result.get("input") or {}
|
||||
abstract = input_data.get("abstract")
|
||||
return isinstance(abstract, str) and bool(abstract.strip())
|
||||
|
||||
|
||||
def get_validation_errors(result: dict[str, Any]) -> list[str]:
|
||||
debug = result.get("llm_debug") or {}
|
||||
errors = debug.get("validation_errors") or []
|
||||
|
||||
if not isinstance(errors, list):
|
||||
return []
|
||||
|
||||
return [str(error) for error in errors]
|
||||
|
||||
|
||||
def is_api_error(result: dict[str, Any]) -> bool:
|
||||
debug = result.get("llm_debug") or {}
|
||||
return debug.get("status") != "ok"
|
||||
|
||||
|
||||
def normalize_usage_record(usage: Any) -> dict[str, int]:
|
||||
if not isinstance(usage, dict):
|
||||
return {
|
||||
"prompt_tokens": 0,
|
||||
"uncached_prompt_tokens": 0,
|
||||
"completion_tokens": 0,
|
||||
"real_total_usage": 0,
|
||||
}
|
||||
|
||||
prompt_tokens = int(usage.get("prompt_tokens") or 0)
|
||||
completion_tokens = int(usage.get("completion_tokens") or 0)
|
||||
|
||||
if "uncached_prompt_tokens" in usage:
|
||||
uncached_prompt_tokens = int(usage.get("uncached_prompt_tokens") or 0)
|
||||
elif "cached_prompt_tokens" in usage:
|
||||
cached_prompt_tokens = min(
|
||||
int(usage.get("cached_prompt_tokens") or 0),
|
||||
prompt_tokens,
|
||||
)
|
||||
uncached_prompt_tokens = max(
|
||||
prompt_tokens - cached_prompt_tokens,
|
||||
0,
|
||||
)
|
||||
else:
|
||||
uncached_prompt_tokens = prompt_tokens
|
||||
|
||||
uncached_prompt_tokens = min(
|
||||
max(uncached_prompt_tokens, 0),
|
||||
prompt_tokens,
|
||||
)
|
||||
|
||||
return {
|
||||
"prompt_tokens": prompt_tokens,
|
||||
"uncached_prompt_tokens": uncached_prompt_tokens,
|
||||
"completion_tokens": completion_tokens,
|
||||
"real_total_usage": (uncached_prompt_tokens + completion_tokens),
|
||||
}
|
||||
|
||||
|
||||
def has_score_range_mismatch(
|
||||
validation_errors: list[str],
|
||||
) -> bool:
|
||||
return any("score_outside_expected_range" in error for error in validation_errors)
|
||||
|
||||
|
||||
def validate_unique_results(
|
||||
results: list[dict[str, Any]],
|
||||
source_file: Path,
|
||||
) -> None:
|
||||
seen: set[str] = set()
|
||||
duplicates: list[str] = []
|
||||
|
||||
for result in results:
|
||||
work_id = result.get("work_id")
|
||||
|
||||
if not isinstance(work_id, str) or not work_id:
|
||||
raise ValueError(f"Missing work_id in {source_file}")
|
||||
|
||||
if work_id in seen:
|
||||
duplicates.append(work_id)
|
||||
else:
|
||||
seen.add(work_id)
|
||||
|
||||
if duplicates:
|
||||
duplicate_list = ", ".join(sorted(set(duplicates)))
|
||||
raise ValueError(f"Duplicate work_id values in {source_file}: {duplicate_list}")
|
||||
|
||||
|
||||
def summarize_results(
|
||||
results: list[dict[str, Any]],
|
||||
person: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
works_total = len(results)
|
||||
valid_outputs = 0
|
||||
validation_error_outputs = 0
|
||||
api_error_outputs = 0
|
||||
category_counts = {category: 0 for category in CATEGORIES}
|
||||
confidence_counts = {confidence: 0 for confidence in CONFIDENCE_VALUES}
|
||||
scores: list[int | float] = []
|
||||
durations: list[int | float] = []
|
||||
works_with_abstract = 0
|
||||
usage = {
|
||||
"prompt_tokens": 0,
|
||||
"uncached_prompt_tokens": 0,
|
||||
"completion_tokens": 0,
|
||||
"real_total_usage": 0,
|
||||
}
|
||||
quality_checks = {
|
||||
"high_confidence_without_abstract": 0,
|
||||
"title_only_high_confidence": 0,
|
||||
"non_research_with_score": 0,
|
||||
"score_range_mismatches": 0,
|
||||
}
|
||||
problem_cases: list[dict[str, Any]] = []
|
||||
|
||||
for result in results:
|
||||
input_data = result.get("input") or {}
|
||||
classification = result.get("classification") or {}
|
||||
debug = result.get("llm_debug") or {}
|
||||
validation_errors = get_validation_errors(result)
|
||||
api_error = is_api_error(result)
|
||||
|
||||
if validation_errors:
|
||||
validation_error_outputs += 1
|
||||
|
||||
if api_error:
|
||||
api_error_outputs += 1
|
||||
|
||||
if (
|
||||
not validation_errors
|
||||
and not api_error
|
||||
and isinstance(result.get("classification"), dict)
|
||||
):
|
||||
valid_outputs += 1
|
||||
|
||||
category = classification.get("primary_category")
|
||||
score = classification.get("applied_orientation_score")
|
||||
confidence = classification.get("confidence")
|
||||
signals_used = classification.get("signals_used") or []
|
||||
|
||||
if category in category_counts:
|
||||
category_counts[category] += 1
|
||||
|
||||
if confidence in confidence_counts:
|
||||
confidence_counts[confidence] += 1
|
||||
|
||||
abstract_available = has_abstract(result)
|
||||
|
||||
if abstract_available:
|
||||
works_with_abstract += 1
|
||||
|
||||
if is_numeric_score(score):
|
||||
scores.append(score)
|
||||
|
||||
result_usage = normalize_usage_record(debug.get("usage"))
|
||||
for key in usage:
|
||||
usage[key] += result_usage[key]
|
||||
|
||||
duration = debug.get("duration_seconds")
|
||||
if isinstance(duration, (int, float)):
|
||||
durations.append(duration)
|
||||
|
||||
if not abstract_available and confidence == "high":
|
||||
quality_checks["high_confidence_without_abstract"] += 1
|
||||
|
||||
if signals_used == ["title"] and confidence == "high":
|
||||
quality_checks["title_only_high_confidence"] += 1
|
||||
|
||||
if category == "non_research" and score is not None:
|
||||
quality_checks["non_research_with_score"] += 1
|
||||
|
||||
if has_score_range_mismatch(validation_errors):
|
||||
quality_checks["score_range_mismatches"] += 1
|
||||
|
||||
if validation_errors or api_error:
|
||||
problem_cases.append(
|
||||
{
|
||||
"person_name": (person or {}).get("display_name"),
|
||||
"person_id": (person or {}).get("id"),
|
||||
"work_id": result.get("work_id"),
|
||||
"doi": result.get("doi"),
|
||||
"title": input_data.get("title"),
|
||||
"year": input_data.get("year"),
|
||||
"work_type": input_data.get("work_type"),
|
||||
"has_abstract": abstract_available,
|
||||
"primary_category": category,
|
||||
"applied_orientation_score": score,
|
||||
"confidence": confidence,
|
||||
"classification_reason": classification.get(
|
||||
"classification_reason"
|
||||
),
|
||||
"validation_errors": validation_errors,
|
||||
"api_error": api_error,
|
||||
"api_error_message": debug.get("error"),
|
||||
}
|
||||
)
|
||||
|
||||
works_without_abstract = works_total - works_with_abstract
|
||||
|
||||
return {
|
||||
"counts": {
|
||||
"works_total": works_total,
|
||||
"valid_outputs": valid_outputs,
|
||||
"validation_errors": validation_error_outputs,
|
||||
"api_errors": api_error_outputs,
|
||||
},
|
||||
"category_distribution": category_counts,
|
||||
"category_share": {
|
||||
category: safe_share(count, works_total)
|
||||
for category, count in category_counts.items()
|
||||
},
|
||||
"confidence_distribution": confidence_counts,
|
||||
"abstract_coverage": {
|
||||
"works_with_abstract": works_with_abstract,
|
||||
"works_without_abstract": works_without_abstract,
|
||||
"missing_abstract_share": safe_share(
|
||||
works_without_abstract,
|
||||
works_total,
|
||||
),
|
||||
},
|
||||
"score_summary": {
|
||||
"scored_outputs": len(scores),
|
||||
"mean_applied_orientation_score": safe_mean(scores),
|
||||
"median_applied_orientation_score": safe_median(scores),
|
||||
"min_applied_orientation_score": (min(scores) if scores else None),
|
||||
"max_applied_orientation_score": (max(scores) if scores else None),
|
||||
},
|
||||
"quality_checks": quality_checks,
|
||||
"usage": usage,
|
||||
"average_usage_per_work": {
|
||||
key: (round(value / works_total, 2) if works_total else None)
|
||||
for key, value in usage.items()
|
||||
},
|
||||
"timing": {
|
||||
"average_duration_seconds_per_work": safe_mean(durations),
|
||||
},
|
||||
"problem_cases": problem_cases,
|
||||
}
|
||||
|
||||
|
||||
def merge_summaries(
|
||||
person_items: list[dict[str, Any]],
|
||||
) -> dict[str, Any]:
|
||||
all_results: list[dict[str, Any]] = []
|
||||
|
||||
for item in person_items:
|
||||
all_results.extend(item["results"])
|
||||
|
||||
overall = summarize_results(all_results)
|
||||
overall["counts"] = {
|
||||
"persons_total": len(person_items),
|
||||
**overall["counts"],
|
||||
}
|
||||
overall["problem_cases"] = [
|
||||
problem_case
|
||||
for item in person_items
|
||||
for problem_case in item["summary"].get("problem_cases", [])
|
||||
]
|
||||
return overall
|
||||
|
||||
|
||||
def main() -> None:
|
||||
if not LLM_RESULTS_DIR.exists():
|
||||
raise FileNotFoundError(LLM_RESULTS_DIR)
|
||||
|
||||
result_files = sorted(LLM_RESULTS_DIR.glob("A*_results.json"))
|
||||
|
||||
if not result_files:
|
||||
raise FileNotFoundError(f"No A*_results.json files found in {LLM_RESULTS_DIR}")
|
||||
|
||||
person_items: list[dict[str, Any]] = []
|
||||
|
||||
for result_file in result_files:
|
||||
data = read_json(result_file)
|
||||
|
||||
if not isinstance(data, dict):
|
||||
raise ValueError(f"Root is not an object in {result_file}")
|
||||
|
||||
person = data.get("person") or {}
|
||||
results = data.get("results") or []
|
||||
|
||||
if not isinstance(person, dict):
|
||||
raise ValueError(f"person is not an object in {result_file}")
|
||||
|
||||
if not isinstance(results, list):
|
||||
raise ValueError(f"results is not a list in {result_file}")
|
||||
|
||||
validate_unique_results(results, result_file)
|
||||
summary = summarize_results(results, person)
|
||||
|
||||
person_items.append(
|
||||
{
|
||||
"person": person,
|
||||
"source_file": result_file.relative_to(PROJECT_ROOT).as_posix(),
|
||||
"summary": summary,
|
||||
"results": results,
|
||||
}
|
||||
)
|
||||
|
||||
overall_summary = merge_summaries(person_items)
|
||||
person_output = [
|
||||
{
|
||||
"person": item["person"],
|
||||
"source_file": item["source_file"],
|
||||
"summary": item["summary"],
|
||||
}
|
||||
for item in person_items
|
||||
]
|
||||
|
||||
write_json(OVERALL_OUTPUT, overall_summary)
|
||||
write_json(PERSON_OUTPUT, person_output)
|
||||
|
||||
print("Classification summary completed.")
|
||||
print(f"Persons: {overall_summary['counts']['persons_total']}")
|
||||
print(f"Works: {overall_summary['counts']['works_total']}")
|
||||
print(f"Valid outputs: {overall_summary['counts']['valid_outputs']}")
|
||||
print(f"Validation errors: {overall_summary['counts']['validation_errors']}")
|
||||
print(f"API errors: {overall_summary['counts']['api_errors']}")
|
||||
print(f"Written: {OVERALL_OUTPUT.relative_to(PROJECT_ROOT).as_posix()}")
|
||||
print(f"Written: {PERSON_OUTPUT.relative_to(PROJECT_ROOT).as_posix()}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,50 +0,0 @@
|
||||
{
|
||||
"filters": {
|
||||
"final_author_set": {
|
||||
"definition": "backend-compatible UDE authors plus authors with recent UDE affiliation and empty last_known_institutions",
|
||||
"components": {
|
||||
"backend_compatible": {
|
||||
"last_known_institutions.display_name": "University of Duisburg-Essen",
|
||||
"affiliations.institution": {
|
||||
"id": "https://openalex.org/I62318514",
|
||||
"ror": "https://ror.org/04mz5ra38",
|
||||
"display_name": "University of Duisburg-Essen"
|
||||
},
|
||||
"affiliations.years_gte": 2025
|
||||
},
|
||||
"empty_last_known_recent_ude": {
|
||||
"last_known_institutions": "missing_or_empty",
|
||||
"affiliations.institution": {
|
||||
"id": "https://openalex.org/I62318514",
|
||||
"ror": "https://ror.org/04mz5ra38",
|
||||
"display_name": "University of Duisburg-Essen"
|
||||
},
|
||||
"affiliations.years_gte": 2025
|
||||
}
|
||||
}
|
||||
},
|
||||
"work_set": {
|
||||
"definition": "All works authored by final_author_set",
|
||||
"work_year_gte": 1950,
|
||||
"works_index": "openalex-works*"
|
||||
},
|
||||
"excluded_types": ["editorial", "erratum", "paratext", "retraction"]
|
||||
},
|
||||
"counts": {
|
||||
"backend_author_count": 4740,
|
||||
"empty_last_known_recent_ude_author_count": 181,
|
||||
"final_author_count": 4921,
|
||||
"works_by_final_authors": 183661,
|
||||
"works_with_abstract": 113242,
|
||||
"works_without_abstract": 70419,
|
||||
"works_excluded_type": 2328
|
||||
},
|
||||
"debug_counts": {
|
||||
"backend_query_count_before_dedup": 4740,
|
||||
"empty_last_known_query_count_before_dedup": 181
|
||||
},
|
||||
"output_files": {
|
||||
"authors": "ude_authors_set.jsonl",
|
||||
"works": "ude_works_set.jsonl"
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,6 @@ from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
|
||||
from ollama import Client
|
||||
|
||||
|
||||
ENDPOINT = os.environ.get("OLLAMA_HOST", "https://project.nes.uni-due.de/llm2/")
|
||||
MODEL = os.environ.get("OLLAMA_MODEL", "gemma4:e4b-it-bf16")
|
||||
DATA_FOLDER = "data"
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import os
|
||||
import json
|
||||
import os
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from time import time
|
||||
|
||||
from openai import OpenAI, APIConnectionError
|
||||
from openai import APIConnectionError, OpenAI
|
||||
|
||||
DATA_FOLDER = "data2"
|
||||
BATCH_SIZE = 6
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import requests, json
|
||||
import json
|
||||
|
||||
import helpers
|
||||
import requests
|
||||
|
||||
AUTHOR_OPEN_ALEXID = helpers.get_all_author_ids_from_specific_university("University of Duisburg-Essen")
|
||||
#AUTHOR_OPEN_ALEXID = ["A5047117780"]
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import requests, json
|
||||
import json
|
||||
|
||||
import helpers
|
||||
import requests
|
||||
|
||||
AUTHOR_OPEN_ALEXID = helpers.get_all_author_ids_from_specific_university("University of Duisburg-Essen")
|
||||
#AUTHOR_OPEN_ALEXID = ["A5093075883", "A5047117780", "A5007170803"]
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import os
|
||||
|
||||
import requests
|
||||
|
||||
ELASTICSEARCH_URL = os.environ.get("ELASTICSEARCH_URL", "https://project.nes.uni-due.de/elastic")
|
||||
|
||||
@@ -2,8 +2,8 @@ import os
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from time import time
|
||||
|
||||
from openai import OpenAI, APIConnectionError
|
||||
import helpers
|
||||
from openai import APIConnectionError, OpenAI
|
||||
|
||||
DATA_FOLDER = "data2"
|
||||
BATCH_SIZE = 6
|
||||
|
||||
@@ -0,0 +1,343 @@
|
||||
import json
|
||||
from collections import defaultdict
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from elasticsearch import Elasticsearch, NotFoundError
|
||||
|
||||
# elasticseach library required. Here used elasticsearch==8.0.0
|
||||
# estimated execution time: 3-5 Minutes
|
||||
|
||||
def remove_year(patent_number: str) -> str:
|
||||
"""Remove a leading 4-digit year from the front of a patent number, if present.
|
||||
|
||||
Only strips the first 4 characters when they are all digits (i.e. actually
|
||||
look like a year). Otherwise the ID is returned unchanged.
|
||||
"""
|
||||
prefix = patent_number[:4]
|
||||
if len(patent_number) > 4 and prefix.isdigit():
|
||||
return patent_number[4:]
|
||||
return patent_number
|
||||
|
||||
|
||||
class PatentCounter:
|
||||
def __init__(
|
||||
self,
|
||||
source_es: Elasticsearch,
|
||||
target_es: Elasticsearch,
|
||||
source_index: str,
|
||||
results_file: str = "patent_matches.json",
|
||||
):
|
||||
self.source_es = source_es
|
||||
self.target_es = target_es
|
||||
self.source_index = source_index
|
||||
self.results_file = Path(results_file)
|
||||
|
||||
self.match_stats = defaultdict(int)
|
||||
|
||||
def _build_variations_uspto(self, patent_id: str) -> dict[str, str]:
|
||||
raw_id = patent_id.upper().removeprefix("US")
|
||||
no_year = remove_year(raw_id)
|
||||
|
||||
return {
|
||||
"publication_number": raw_id,
|
||||
"publication_number_no_year": no_year,
|
||||
"application_number": raw_id,
|
||||
"application_number_no_year": no_year,
|
||||
}
|
||||
|
||||
def _build_variations_epo(self, patent_id: str) -> dict[str, str]:
|
||||
raw_id = patent_id.upper().removeprefix("EP")
|
||||
no_year = remove_year(raw_id)
|
||||
|
||||
return {
|
||||
"doc_number": raw_id,
|
||||
"doc_number_no_year": no_year,
|
||||
"application_number": raw_id,
|
||||
"application_number_no_year": no_year,
|
||||
}
|
||||
|
||||
def _uspto_query_by_id(
|
||||
self,
|
||||
patent_id: str,
|
||||
size: int = 100,
|
||||
) -> dict[str, Any]:
|
||||
variations = self._build_variations_uspto(patent_id)
|
||||
body = {
|
||||
"size": size,
|
||||
"track_total_hits": True,
|
||||
"_source": [
|
||||
"publication_number",
|
||||
"application_number",
|
||||
"title",
|
||||
],
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{"term": {"publication_number": variations["publication_number"]}},
|
||||
{"term": {"publication_number": variations["publication_number_no_year"]}},
|
||||
{"term": {"application_number": variations["application_number"]}},
|
||||
{"term": {"application_number": variations["application_number_no_year"]}},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
},
|
||||
}
|
||||
#print(f"USPTO query for {patent_id}: {json.dumps(body)}") # Debugging line
|
||||
return body
|
||||
|
||||
def _epo_query_by_id(
|
||||
self,
|
||||
patent_id: str,
|
||||
size: int = 100,
|
||||
) -> dict[str, Any]:
|
||||
variations = self._build_variations_epo(patent_id)
|
||||
body = {
|
||||
"size": size,
|
||||
"track_total_hits": True,
|
||||
"_source": [
|
||||
"doc_number",
|
||||
"application_number",
|
||||
"title_en",
|
||||
"title_fr",
|
||||
"title_de",
|
||||
],
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{"term": {"doc_number": variations["doc_number"]}},
|
||||
{"term": {"application_number": variations["application_number"]}},
|
||||
{"term": {"doc_number": variations["doc_number_no_year"]}},
|
||||
{"term": {"application_number": variations["application_number_no_year"]}},
|
||||
{"wildcard": {
|
||||
"application_number": {
|
||||
"value": f"{variations['application_number']}*"
|
||||
}
|
||||
}
|
||||
},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
},
|
||||
}
|
||||
#print(f"EP query for {patent_id}: {json.dumps(body)}") # Debugging line
|
||||
return body
|
||||
|
||||
def _scroll_all(self, query: dict) -> Iterator[dict]:
|
||||
"""Run a scroll query to completion, yielding each hit's _source,
|
||||
and always clearing the scroll context when done."""
|
||||
resp = self.source_es.search(
|
||||
index=self.source_index,
|
||||
body=query,
|
||||
scroll="5m",
|
||||
size=10000,
|
||||
)
|
||||
scroll_id = resp.get("_scroll_id")
|
||||
|
||||
try:
|
||||
while True:
|
||||
hits = resp["hits"]["hits"]
|
||||
if not hits:
|
||||
break
|
||||
|
||||
for hit in hits:
|
||||
yield hit["_source"]
|
||||
|
||||
try:
|
||||
resp = self.source_es.scroll(scroll_id=scroll_id, scroll="5m")
|
||||
scroll_id = resp.get("_scroll_id")
|
||||
except NotFoundError:
|
||||
break
|
||||
finally:
|
||||
if scroll_id:
|
||||
try:
|
||||
self.source_es.clear_scroll(scroll_id=scroll_id)
|
||||
except Exception:
|
||||
pass # best-effort cleanup, don't fail the run over this
|
||||
|
||||
def get_source_docs(self) -> Iterator[dict]:
|
||||
"""
|
||||
Yield source docs (with applicationIdentifier, applicationPrefix, title) in order:
|
||||
1. All EP patents (applicationPrefix: "EP")
|
||||
2. Then all USPTO patents (applicationPrefix: "US")
|
||||
"""
|
||||
query_ep = {
|
||||
"_source": ["applicationIdentifier", "applicationPrefix", "title"],
|
||||
"query": {"term": {"applicationPrefix": "EP"}},
|
||||
}
|
||||
query_us = {
|
||||
"_source": ["applicationIdentifier", "applicationPrefix", "title"],
|
||||
"query": {"term": {"applicationPrefix": "US"}},
|
||||
}
|
||||
|
||||
for source in self._scroll_all(query_ep):
|
||||
if source.get("applicationIdentifier"):
|
||||
yield source
|
||||
|
||||
for source in self._scroll_all(query_us):
|
||||
if source.get("applicationIdentifier"):
|
||||
yield source
|
||||
|
||||
def find_matches(self, patent_id: str, source_prefix: str, source_title: str) -> dict:
|
||||
"""Match a single source patent against the target indexes.
|
||||
|
||||
source_prefix/source_title are passed in from get_source_docs() rather
|
||||
than being re-fetched here, avoiding a redundant query per record and
|
||||
the IndexError that occurred when a fetch found no hits.
|
||||
"""
|
||||
variations_uspto = self._build_variations_uspto(patent_id)
|
||||
variations_epo = self._build_variations_epo(patent_id)
|
||||
raw_id_epo = patent_id.upper().removeprefix("EP")
|
||||
|
||||
matches = []
|
||||
matched_indexes = set()
|
||||
|
||||
# EP PATENTS -> Only match in EPO index
|
||||
if source_prefix == "EP":
|
||||
epo_resp = self.target_es.search(
|
||||
index="epo_index_1.0",
|
||||
body=self._epo_query_by_id(patent_id),
|
||||
)
|
||||
epo_hits = epo_resp["hits"]["hits"]
|
||||
|
||||
for hit in epo_hits:
|
||||
source = hit["_source"]
|
||||
|
||||
matched_field = None
|
||||
if source.get("doc_number") == raw_id_epo:
|
||||
matched_field = "doc_number"
|
||||
elif source.get("doc_number") == variations_epo["doc_number_no_year"]:
|
||||
matched_field = "doc_number_no_year"
|
||||
|
||||
matched_field_app = None
|
||||
if source.get("application_number") == raw_id_epo:
|
||||
matched_field_app = "application_number"
|
||||
elif source.get("application_number") == variations_epo["application_number_no_year"]:
|
||||
matched_field_app = "application_number_no_year"
|
||||
elif source.get("application_number", "").startswith(variations_epo["application_number"]):
|
||||
matched_field_app = "application_number_wildcard"
|
||||
matched_fields = [f for f in (matched_field, matched_field_app) if f]
|
||||
|
||||
for field in matched_fields:
|
||||
self.match_stats[f"epo:{field}"] += 1
|
||||
|
||||
all_ids = {
|
||||
"doc_number": source.get("doc_number"),
|
||||
"application_number": source.get("application_number"),
|
||||
}
|
||||
|
||||
matches.append({
|
||||
"index": "epo_index_1.0",
|
||||
"field": field,
|
||||
"doc_id": hit["_id"],
|
||||
"title_en": source.get("title_en"),
|
||||
"title_fr": source.get("title_fr"),
|
||||
"title_de": source.get("title_de"),
|
||||
"all_ids": all_ids,
|
||||
})
|
||||
|
||||
if epo_hits:
|
||||
matched_indexes.add("epo_index_1.0")
|
||||
|
||||
# US PATENTS -> Only match in USPTO index
|
||||
elif source_prefix == "US":
|
||||
uspto_resp = self.target_es.search(
|
||||
index="uspto_patents_3.0",
|
||||
body=self._uspto_query_by_id(patent_id),
|
||||
)
|
||||
uspto_hits = uspto_resp["hits"]["hits"]
|
||||
|
||||
for hit in uspto_hits:
|
||||
source = hit["_source"]
|
||||
pub = source.get("publication_number")
|
||||
app = source.get("application_number")
|
||||
|
||||
matched_field_pub = None
|
||||
if pub == variations_uspto["publication_number"]:
|
||||
matched_field_pub = "publication_number"
|
||||
elif pub == variations_uspto["publication_number_no_year"]:
|
||||
matched_field_pub = "publication_number_no_year"
|
||||
|
||||
matched_field_app = None
|
||||
if app == variations_uspto["application_number"]:
|
||||
matched_field_app = "application_number"
|
||||
elif app == variations_uspto["application_number_no_year"]:
|
||||
matched_field_app = "application_number_no_year"
|
||||
|
||||
matched_fields = [f for f in (matched_field_pub, matched_field_app) if f]
|
||||
|
||||
for field in matched_fields:
|
||||
self.match_stats[f"uspto:{field}"] += 1
|
||||
|
||||
matches.append({
|
||||
"index": "uspto_patents_3.0",
|
||||
"field": field,
|
||||
"doc_id": hit["_id"],
|
||||
"title": source.get("title"),
|
||||
})
|
||||
|
||||
if uspto_hits:
|
||||
matched_indexes.add("uspto_patents_3.0")
|
||||
|
||||
return {
|
||||
"source_id": patent_id,
|
||||
"source_prefix": source_prefix,
|
||||
"source_title": source_title,
|
||||
"found": len(matches) > 0,
|
||||
"matches": matches,
|
||||
"not_found_in": [
|
||||
idx for idx in ("epo_index_1.0", "uspto_patents_3.0")
|
||||
if idx not in matched_indexes
|
||||
],
|
||||
}
|
||||
|
||||
def count_matches(self):
|
||||
total = 0
|
||||
matched = 0
|
||||
all_results = []
|
||||
|
||||
for source_doc in self.get_source_docs():
|
||||
patent_id = source_doc["applicationIdentifier"]
|
||||
source_prefix = source_doc.get("applicationPrefix", "")
|
||||
source_title = source_doc.get("title", "")
|
||||
|
||||
total += 1
|
||||
result = self.find_matches(patent_id, source_prefix, source_title)
|
||||
|
||||
if result["found"]:
|
||||
matched += 1
|
||||
|
||||
all_results.append(result)
|
||||
|
||||
if total % 1000 == 0:
|
||||
print(f"Processed={total:,}, Matched={matched:,}")
|
||||
with open(self.results_file, "w") as f:
|
||||
json.dump(all_results, f, indent=2)
|
||||
|
||||
# Final save
|
||||
with open(self.results_file, "w") as f:
|
||||
json.dump(all_results, f, indent=2)
|
||||
|
||||
return total, matched
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
source_es = Elasticsearch('https://inse.nes.uni-due.de:443/elastic', basic_auth=('elastic', 'RLldUaJgbGeoqd3KCX3p'), request_timeout=60, max_retries=5, retry_on_timeout=True)
|
||||
|
||||
counter = PatentCounter(
|
||||
source_es=source_es,
|
||||
target_es=source_es,
|
||||
source_index="cordis_eu_fp7_project_iprs",
|
||||
results_file="patent_matches.json",
|
||||
)
|
||||
|
||||
total, matched = counter.count_matches()
|
||||
|
||||
print(f"Total IDs: {total:,}")
|
||||
print(f"Matched source IDs: {matched:,}")
|
||||
print(f"Not found: {total - matched:,}")
|
||||
|
||||
print("\nMatch statistics:")
|
||||
for key, count in sorted(counter.match_stats.items()):
|
||||
print(f"{key}: {count:,}")
|
||||
@@ -0,0 +1,78 @@
|
||||
Here’s a shorter, more concise version:
|
||||
|
||||
# Patent Matching Pipeline — CORDIS FP7 IPR Records ↔ EPO / USPTO
|
||||
|
||||
## Purpose
|
||||
|
||||
This pipeline validates FP7 patent records from CORDIS against external patent databases:
|
||||
|
||||
- **EPO index (`epo_index_1.0`)** for `EP` patents
|
||||
- **USPTO index (`uspto_patents_3.0`)** for `US` patents
|
||||
|
||||
The objective is to measure match coverage and determine which ID-matching strategies are reliable for downstream patent linking.
|
||||
|
||||
## Dataset
|
||||
|
||||
Source: `cordis_eu_fp7_project_iprs`
|
||||
Patents tested: 5196(total) - 2270(others) -> 2926 (EP and US patents)
|
||||
|
||||
| Prefix | Count |
|
||||
| --------- | --------: |
|
||||
| EP | 1,952 |
|
||||
| US | 974 |
|
||||
| **Total** | **2,926** |
|
||||
|
||||
## Matching Strategies
|
||||
|
||||
### EPO
|
||||
|
||||
- `doc_number`: exact, no-year
|
||||
- `application_number`: exact, no-year, wildcard (`{id}*`)
|
||||
|
||||
### USPTO
|
||||
|
||||
- `application_number`: exact, no-year
|
||||
- `publication_number`: exact, no-year
|
||||
|
||||
Matching priority: **exact → no-year → wildcard** (first match wins).
|
||||
|
||||
## Results
|
||||
|
||||
| Metric | Count |
|
||||
| ----------- | ----: |
|
||||
| Total IDs | 2,926 |
|
||||
| Matched IDs | 1,713 |
|
||||
| Not Found | 1,213 |
|
||||
|
||||
### Match Counts by Field
|
||||
|
||||
| Field | Hits |
|
||||
| ---------------------------------- | ----: |
|
||||
| `epo:application_number_wildcard` | 1,864 |
|
||||
| `epo:doc_number` | 7 |
|
||||
| `uspto:application_number_no_year` | 564 |
|
||||
| `uspto:application_number` | 6 |
|
||||
|
||||
No matches were found for:
|
||||
|
||||
- `epo:application_number` (exact/no-year)
|
||||
- `epo:doc_number_no_year`
|
||||
- `uspto:publication_number` (exact/no-year)
|
||||
|
||||
## Findings
|
||||
|
||||
### EPO
|
||||
|
||||
| Strategy | Assessment |
|
||||
| ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
|
||||
| `doc_number` | ❌ Unreliable; often matches unrelated patents |
|
||||
| `application_number` exact/no-year | ⚠️ No matches |
|
||||
| `application_number` wildcard (APPROVED) | ⚠️ Best coverage (1,864 hits) but over-matches related filings; requires secondary validation (e.g., title similarity) |
|
||||
|
||||
### USPTO
|
||||
|
||||
| Strategy | Assessment |
|
||||
| --------------------------------------- | --------------------------------------- |
|
||||
| `application_number` exact | ❌ Unreliable; numbering formats differ |
|
||||
| `application_number_no_year` (APPROVED) | ✅ Reliable (564 matches) |
|
||||
| `publication_number` | No useful matches |
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,5 +1,5 @@
|
||||
import os
|
||||
import json
|
||||
import os
|
||||
from time import time
|
||||
|
||||
from llm_classify_news import call, parse_label, parse_persons
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Baut aus den JSON-Dateien in data2/ eine eigenstaendige viewer.html.
|
||||
|
||||
@@ -8,8 +7,8 @@ mit Vor/Zurueck durch die News blaettern. Oben stehen _id, llm_label und
|
||||
llm_persons, darunter der full_content als reiner Text (kein Parsing).
|
||||
"""
|
||||
|
||||
import os
|
||||
import json
|
||||
import os
|
||||
|
||||
DATA_FOLDER = "validation_data"
|
||||
OUTPUT_FILE = "viewer.html"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import os
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
|
||||
import requests
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import os
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
|
||||
import requests
|
||||
from openai import OpenAI, APIConnectionError
|
||||
|
||||
from openai import APIConnectionError, OpenAI
|
||||
|
||||
INSE_URL = "https://inse.nes.uni-due.de/elastic"
|
||||
INDEX_URL = f"{INSE_URL}/aktuell"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import os
|
||||
import json
|
||||
import os
|
||||
|
||||
DATA_FOLDER = "data2"
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import json
|
||||
|
||||
from tabulate import tabulate
|
||||
|
||||
result_files = [
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
from urllib.parse import quote
|
||||
|
||||
import requests
|
||||
from requests.adapters import HTTPAdapter
|
||||
from urllib.parse import quote
|
||||
|
||||
INSE_URL = "https://inse.nes.uni-due.de/elastic"
|
||||
INSE_API_KEY = "bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw=="
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import requests
|
||||
from openai import OpenAI, APIConnectionError
|
||||
from openai import APIConnectionError, OpenAI
|
||||
|
||||
LLM_BASE_URL = "https://project.nes.uni-due.de/llm2/v1/"
|
||||
LLM_API_KEY = "c2d5e7ccf7a4760dd3d19bed2caed9d85ff7437400e0ea82a6d6f912ebc2f212"
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import argparse
|
||||
import json
|
||||
import threading
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
|
||||
import elastic.client as es_client
|
||||
import llm.client as llm_client
|
||||
import json
|
||||
import argparse
|
||||
import time
|
||||
import threading
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
|
||||
|
||||
def print_pretty_json(data):
|
||||
print(json.dumps(data, indent=2))
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
Perhaps not the final version. I did not find the files inside my local git branch. I most likely did not save them, however i made backups sometimes, so i hope these versions are the final ones.
|
||||
@@ -0,0 +1,429 @@
|
||||
#!/usr/bin/env python3
|
||||
import asyncio
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
import numpy as np
|
||||
|
||||
# Load service environment config
|
||||
current_dir = Path(__file__).parent.resolve()
|
||||
project_root = current_dir.parent.parent.resolve()
|
||||
env_path = project_root / "service" / "src" / "main" / "inse" / ".env"
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv(dotenv_path=env_path)
|
||||
|
||||
sys.path.append(str(project_root / "service" / "src" / "main"))
|
||||
|
||||
from inse.config import settings
|
||||
from inse.util import get_model
|
||||
|
||||
ELASTIC_URL = settings.elasticsearch_url
|
||||
if ELASTIC_URL and not ELASTIC_URL.endswith("/"):
|
||||
ELASTIC_URL += "/"
|
||||
API_KEY = settings.elasticsearch_api_key
|
||||
|
||||
headers = {
|
||||
"Authorization": f"ApiKey {API_KEY}",
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
FIELDS = [
|
||||
"Social Sciences", "Medicine", "Engineering", "Computer Science",
|
||||
"Arts and Humanities", "Biochemistry, Genetics and Molecular Biology",
|
||||
"Agricultural and Biological Sciences", "Environmental Science",
|
||||
"Business, Management and Accounting", "Psychology", "Materials Science",
|
||||
"Economics, Econometrics and Finance", "Health Professions",
|
||||
"Physics and Astronomy", "Chemistry", "Mathematics", "Neuroscience",
|
||||
"Decision Sciences", "Earth and Planetary Sciences", "Immunology and Microbiology",
|
||||
"Energy", "Pharmacology, Toxicology and Pharmaceutics", "Nursing",
|
||||
"Chemical Engineering", "Dentistry", "Veterinary"
|
||||
]
|
||||
|
||||
QUERIES_FILE = current_dir / "evaluation_queries.json"
|
||||
|
||||
def load_queries():
|
||||
if QUERIES_FILE.exists():
|
||||
print(f"Loading cached queries from {QUERIES_FILE}...")
|
||||
with open(QUERIES_FILE, "r", encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
else:
|
||||
raise FileNotFoundError(f"Evaluation queries file not found at {QUERIES_FILE}")
|
||||
|
||||
def make_es_payload(query_vector, query_str, config_type, limit=10):
|
||||
if config_type == "display_name":
|
||||
clause = {
|
||||
"knn": {
|
||||
"field": "display_name_vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
}
|
||||
query_body = {"query": clause}
|
||||
elif config_type == "description":
|
||||
clause = {
|
||||
"knn": {
|
||||
"field": "description_vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
}
|
||||
query_body = {"query": clause}
|
||||
elif config_type == "keywords":
|
||||
clause = {
|
||||
"nested": {
|
||||
"path": "keyword_vectors",
|
||||
"query": {
|
||||
"knn": {
|
||||
"field": "keyword_vectors.vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
},
|
||||
"score_mode": "max"
|
||||
}
|
||||
}
|
||||
query_body = {"query": clause}
|
||||
elif config_type == "display_name_and_keywords":
|
||||
query_body = {
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"knn": {
|
||||
"field": "display_name_vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
},
|
||||
{
|
||||
"nested": {
|
||||
"path": "keyword_vectors",
|
||||
"query": {
|
||||
"knn": {
|
||||
"field": "keyword_vectors.vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
},
|
||||
"score_mode": "max"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
elif config_type == "display_name_and_description":
|
||||
query_body = {
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"knn": {
|
||||
"field": "display_name_vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
},
|
||||
{
|
||||
"knn": {
|
||||
"field": "description_vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
elif config_type == "combined":
|
||||
query_body = {
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"knn": {
|
||||
"field": "display_name_vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
},
|
||||
{
|
||||
"knn": {
|
||||
"field": "description_vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
},
|
||||
{
|
||||
"nested": {
|
||||
"path": "keyword_vectors",
|
||||
"query": {
|
||||
"knn": {
|
||||
"field": "keyword_vectors.vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
},
|
||||
"score_mode": "max"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
elif config_type == "lexical_only":
|
||||
query_body = {
|
||||
"query": {
|
||||
"multi_match": {
|
||||
"query": query_str,
|
||||
"fields": ["display_name^3", "keywords^2", "description^1"]
|
||||
}
|
||||
}
|
||||
}
|
||||
elif config_type == "hybrid":
|
||||
query_body = {
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"multi_match": {
|
||||
"query": query_str,
|
||||
"fields": ["display_name^3", "keywords^2", "description^1"]
|
||||
}
|
||||
},
|
||||
{
|
||||
"knn": {
|
||||
"field": "display_name_vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
},
|
||||
{
|
||||
"knn": {
|
||||
"field": "description_vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
},
|
||||
{
|
||||
"nested": {
|
||||
"path": "keyword_vectors",
|
||||
"query": {
|
||||
"knn": {
|
||||
"field": "keyword_vectors.vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
},
|
||||
"score_mode": "max"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
else:
|
||||
raise ValueError(f"Unknown config_type: {config_type}")
|
||||
|
||||
query_body["_source"] = {
|
||||
"excludes": ["display_name_vector", "description_vector", "keyword_vectors", "description"]
|
||||
}
|
||||
query_body["size"] = limit
|
||||
return query_body
|
||||
|
||||
async def evaluate():
|
||||
queries_by_field = load_queries()
|
||||
|
||||
# 1. Warm up model and connection
|
||||
print("\nWarming up model and Elasticsearch connection...")
|
||||
model = get_model()
|
||||
model.encode("warmup search term")
|
||||
|
||||
# Run a dummy check on ES
|
||||
dummy_vector = [0.1] * 768
|
||||
dummy_payload = make_es_payload(dummy_vector, "warmup search term", "display_name")
|
||||
try:
|
||||
with httpx.Client(timeout=10.0) as client:
|
||||
client.post(f"{ELASTIC_URL}topicvectors/_search", json=dummy_payload, headers=headers)
|
||||
print("Warmup complete.")
|
||||
except Exception as exc:
|
||||
print(f"Warmup query failed: {exc}")
|
||||
|
||||
results = []
|
||||
print("\nRunning comprehensive latency evaluation on 520 queries...")
|
||||
query_count = 0
|
||||
|
||||
config_list = [
|
||||
"display_name", "description", "keywords",
|
||||
"display_name_and_keywords", "display_name_and_description",
|
||||
"combined", "lexical_only", "hybrid"
|
||||
]
|
||||
|
||||
with httpx.Client(timeout=30.0) as client:
|
||||
for field, queries in queries_by_field.items():
|
||||
for q in queries:
|
||||
query_count += 1
|
||||
if query_count % 50 == 0:
|
||||
print(f"Processed {query_count} / 520 queries...")
|
||||
|
||||
# Measure encoding latency
|
||||
t0 = time.perf_counter()
|
||||
query_vector = model.encode(q).tolist()
|
||||
t1 = time.perf_counter()
|
||||
encode_time = (t1 - t0) * 1000.0 # ms
|
||||
|
||||
latencies = {}
|
||||
|
||||
# Benchmark each configuration
|
||||
for config in config_list:
|
||||
payload = make_es_payload(query_vector, q, config)
|
||||
t0 = time.perf_counter()
|
||||
try:
|
||||
resp = client.post(f"{ELASTIC_URL}topicvectors/_search", json=payload, headers=headers)
|
||||
resp.raise_for_status()
|
||||
except Exception:
|
||||
# Log error but don't crash
|
||||
pass
|
||||
t1 = time.perf_counter()
|
||||
latencies[config] = (t1 - t0) * 1000.0 # ms
|
||||
|
||||
results.append({
|
||||
"query": q,
|
||||
"field": field,
|
||||
"encode_latency_ms": encode_time,
|
||||
"display_name_latency_ms": latencies.get("display_name", 0.0),
|
||||
"description_latency_ms": latencies.get("description", 0.0),
|
||||
"keywords_latency_ms": latencies.get("keywords", 0.0),
|
||||
"display_name_and_keywords_latency_ms": latencies.get("display_name_and_keywords", 0.0),
|
||||
"display_name_and_description_latency_ms": latencies.get("display_name_and_description", 0.0),
|
||||
"combined_latency_ms": latencies.get("combined", 0.0),
|
||||
"lexical_only_latency_ms": latencies.get("lexical_only", 0.0),
|
||||
"hybrid_latency_ms": latencies.get("hybrid", 0.0)
|
||||
})
|
||||
|
||||
# Calculate global stats
|
||||
encode_l = [r["encode_latency_ms"] for r in results]
|
||||
display_name_l = [r["display_name_latency_ms"] for r in results]
|
||||
description_l = [r["description_latency_ms"] for r in results]
|
||||
keywords_l = [r["keywords_latency_ms"] for r in results]
|
||||
display_name_and_keywords_l = [r["display_name_and_keywords_latency_ms"] for r in results]
|
||||
display_name_and_description_l = [r["display_name_and_description_latency_ms"] for r in results]
|
||||
combined_l = [r["combined_latency_ms"] for r in results]
|
||||
lexical_only_l = [r["lexical_only_latency_ms"] for r in results]
|
||||
hybrid_l = [r["hybrid_latency_ms"] for r in results]
|
||||
|
||||
summary = {
|
||||
"total_queries": len(results),
|
||||
"encode": {
|
||||
"mean": np.mean(encode_l), "median": np.median(encode_l),
|
||||
"p90": np.percentile(encode_l, 90), "p95": np.percentile(encode_l, 95)
|
||||
},
|
||||
"display_name": {
|
||||
"mean": np.mean(display_name_l), "median": np.median(display_name_l),
|
||||
"p90": np.percentile(display_name_l, 90), "p95": np.percentile(display_name_l, 95)
|
||||
},
|
||||
"description": {
|
||||
"mean": np.mean(description_l), "median": np.median(description_l),
|
||||
"p90": np.percentile(description_l, 90), "p95": np.percentile(description_l, 95)
|
||||
},
|
||||
"keywords": {
|
||||
"mean": np.mean(keywords_l), "median": np.median(keywords_l),
|
||||
"p90": np.percentile(keywords_l, 90), "p95": np.percentile(keywords_l, 95)
|
||||
},
|
||||
"display_name_and_keywords": {
|
||||
"mean": np.mean(display_name_and_keywords_l), "median": np.median(display_name_and_keywords_l),
|
||||
"p90": np.percentile(display_name_and_keywords_l, 90), "p95": np.percentile(display_name_and_keywords_l, 95)
|
||||
},
|
||||
"display_name_and_description": {
|
||||
"mean": np.mean(display_name_and_description_l), "median": np.median(display_name_and_description_l),
|
||||
"p90": np.percentile(display_name_and_description_l, 90), "p95": np.percentile(display_name_and_description_l, 95)
|
||||
},
|
||||
"combined": {
|
||||
"mean": np.mean(combined_l), "median": np.median(combined_l),
|
||||
"p90": np.percentile(combined_l, 90), "p95": np.percentile(combined_l, 95)
|
||||
},
|
||||
"lexical_only": {
|
||||
"mean": np.mean(lexical_only_l), "median": np.median(lexical_only_l),
|
||||
"p90": np.percentile(lexical_only_l, 90), "p95": np.percentile(lexical_only_l, 95)
|
||||
},
|
||||
"hybrid": {
|
||||
"mean": np.mean(hybrid_l), "median": np.median(hybrid_l),
|
||||
"p90": np.percentile(hybrid_l, 90), "p95": np.percentile(hybrid_l, 95)
|
||||
}
|
||||
}
|
||||
|
||||
# Save full report to json
|
||||
report_json_path = current_dir / "evaluation_report.json"
|
||||
with open(report_json_path, "w", encoding="utf-8") as f:
|
||||
json.dump({"summary": summary, "results": results}, f, indent=2, ensure_ascii=False)
|
||||
print(f"\nSaved detailed JSON report to {report_json_path}")
|
||||
|
||||
# Generate and save markdown report
|
||||
md_report_path = current_dir / "evaluation_report.md"
|
||||
md_content = f"""# Vector Search Configuration Latency Report
|
||||
Generated on: {time.strftime('%Y-%m-%d %H:%M:%S')}
|
||||
|
||||
This report documents the latency breakdown for different Elasticsearch query configurations across 520 queries, measuring flat vector searches, nested searches, multi-field combinations, pure lexical searches, and full hybrid queries.
|
||||
|
||||
## Latency Summary Table (ms)
|
||||
|
||||
| Query Configuration | Mean | Median | p90 | p95 |
|
||||
| :--- | :---: | :---: | :---: | :---: |
|
||||
| **Embedding Encode** | {summary["encode"]["mean"]:.2f} | {summary["encode"]["median"]:.2f} | {summary["encode"]["p90"]:.2f} | {summary["encode"]["p95"]:.2f} |
|
||||
| **Pure Lexical Search (`multi_match`)** | {summary["lexical_only"]["mean"]:.2f} | {summary["lexical_only"]["median"]:.2f} | {summary["lexical_only"]["p90"]:.2f} | {summary["lexical_only"]["p95"]:.2f} |
|
||||
| **Description Only (`description_vector`)** | {summary["description"]["mean"]:.2f} | {summary["description"]["median"]:.2f} | {summary["description"]["p90"]:.2f} | {summary["description"]["p95"]:.2f} |
|
||||
| **Display Name Only (`display_name_vector`)** | {summary["display_name"]["mean"]:.2f} | {summary["display_name"]["median"]:.2f} | {summary["display_name"]["p90"]:.2f} | {summary["display_name"]["p95"]:.2f} |
|
||||
| **Keywords Only (`keyword_vectors` - Nested)** | {summary["keywords"]["mean"]:.2f} | {summary["keywords"]["median"]:.2f} | {summary["keywords"]["p90"]:.2f} | {summary["keywords"]["p95"]:.2f} |
|
||||
| **Display Name & Description** | {summary["display_name_and_description"]["mean"]:.2f} | {summary["display_name_and_description"]["median"]:.2f} | {summary["display_name_and_description"]["p90"]:.2f} | {summary["display_name_and_description"]["p95"]:.2f} |
|
||||
| **Display Name & Keywords (Nested)** | {summary["display_name_and_keywords"]["mean"]:.2f} | {summary["display_name_and_keywords"]["median"]:.2f} | {summary["display_name_and_keywords"]["p90"]:.2f} | {summary["display_name_and_keywords"]["p95"]:.2f} |
|
||||
| **Combined (All 3 vector fields)** | {summary["combined"]["mean"]:.2f} | {summary["combined"]["median"]:.2f} | {summary["combined"]["p90"]:.2f} | {summary["combined"]["p95"]:.2f} |
|
||||
| **Hybrid Search (Lexical + All 3 vector fields)** | {summary["hybrid"]["mean"]:.2f} | {summary["hybrid"]["median"]:.2f} | {summary["hybrid"]["p90"]:.2f} | {summary["hybrid"]["p95"]:.2f} |
|
||||
|
||||
---
|
||||
|
||||
## 💡 Latency Bottleneck & Configuration Analysis
|
||||
|
||||
1. **Lexical Baseline**: **Pure Lexical Search** has extremely low latency (mean: **{summary["lexical_only"]["mean"]:.2f} ms**), representing standard BM25 keyword matching speed.
|
||||
2. **Impact of Nested Fields**:
|
||||
- Compares **Keywords Only (Nested)** (mean: **{summary["keywords"]["mean"]:.2f} ms**) with **Description Only (Flat)** (mean: **{summary["description"]["mean"]:.2f} ms**).
|
||||
- Combining Display Name with the flat Description (**Display Name & Description**: **{summary["display_name_and_description"]["mean"]:.2f} ms**) is faster than combining Display Name with nested Keywords (**Display Name & Keywords**: **{summary["display_name_and_keywords"]["mean"]:.2f} ms**), demonstrating that nested vector joins add a steady latency premium.
|
||||
3. **Compound Parallel Execution**:
|
||||
- Adding lexical queries to the 3 combined vector queries (**Hybrid Search**: **{summary["hybrid"]["mean"]:.2f} ms**) introduces virtually no latency overhead compared to **Combined** vector-only search (mean: **{summary["combined"]["mean"]:.2f} ms**), proving that standard lexical match is executed concurrently with HNSW vector retrieval.
|
||||
"""
|
||||
with open(md_report_path, "w", encoding="utf-8") as f:
|
||||
f.write(md_content)
|
||||
print(f"Saved Markdown report summary to {md_report_path}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(evaluate())
|
||||
@@ -0,0 +1,391 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Professional evaluation pipeline to benchmark different Sentence Transformer models
|
||||
on the OpenAlex topics dataset. Measures Information Retrieval (IR) metrics,
|
||||
Taxonomy Clustering metrics, and operational performance metrics.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import random
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Add service/src/main to python path to load settings
|
||||
current_dir = Path(__file__).parent.resolve()
|
||||
project_root = current_dir.parent.parent.resolve()
|
||||
env_path = project_root / "service" / "src" / "main" / "inse" / ".env"
|
||||
load_dotenv(dotenv_path=env_path)
|
||||
|
||||
sys.path.append(str(project_root / "service" / "src" / "main"))
|
||||
from inse.config import settings
|
||||
|
||||
ELASTIC_URL = settings.elasticsearch_url
|
||||
API_KEY = settings.elasticsearch_api_key
|
||||
|
||||
# Import evaluation libraries
|
||||
from sentence_transformers import SentenceTransformer
|
||||
from sentence_transformers.evaluation import InformationRetrievalEvaluator
|
||||
from sklearn import metrics
|
||||
from sklearn.cluster import KMeans
|
||||
|
||||
DEFAULT_MODELS = [
|
||||
"paraphrase-multilingual-mpnet-base-v2",
|
||||
"BAAI/bge-m3",
|
||||
"google/embeddinggemma-300m",
|
||||
"intfloat/multilingual-e5-small",
|
||||
"intfloat/multilingual-e5-base",
|
||||
"intfloat/multilingual-e5-large",
|
||||
"sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2",
|
||||
#english
|
||||
"sentence-transformers/all-MiniLM-L6-v2",
|
||||
"intfloat/e5-large-v2",
|
||||
"BAAI/bge-large-en-v1.5"
|
||||
]
|
||||
|
||||
def fetch_all_topics():
|
||||
topics = []
|
||||
size = 1000
|
||||
offset = 0
|
||||
headers = {
|
||||
"Authorization": f"ApiKey {API_KEY}",
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
with httpx.Client(timeout=60.0) as client:
|
||||
while True:
|
||||
payload = {
|
||||
"query": {"match_all": {}},
|
||||
"from": offset,
|
||||
"size": size
|
||||
}
|
||||
resp = client.post(
|
||||
f"{ELASTIC_URL.rstrip('/')}/openalex-topics/_search",
|
||||
json=payload,
|
||||
headers=headers
|
||||
)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
hits = data.get("hits", {}).get("hits", [])
|
||||
if not hits:
|
||||
break
|
||||
topics.extend(hits)
|
||||
offset += len(hits)
|
||||
print(f"Fetched {len(topics)} topics...")
|
||||
if len(hits) < size:
|
||||
break
|
||||
|
||||
print(f"Total topics loaded: {len(topics)}")
|
||||
return topics
|
||||
|
||||
def prepare_data(topics, sample_size=None):
|
||||
"""
|
||||
Formulate the IR dataset and clustering taxonomy ground truth labels.
|
||||
"""
|
||||
corpus = {}
|
||||
queries = {}
|
||||
relevant_docs = {}
|
||||
|
||||
# Clustering labels
|
||||
topic_ids = []
|
||||
names_for_clustering = []
|
||||
descriptions_for_clustering = []
|
||||
labels_subfield = []
|
||||
labels_field = []
|
||||
labels_domain = []
|
||||
|
||||
# Build complete corpus dictionary of documents
|
||||
for t in topics:
|
||||
source = t["_source"]
|
||||
doc_id = source["id"]
|
||||
display_name = source.get("display_name") or ""
|
||||
description = source.get("description") or ""
|
||||
doc_text = f"{display_name} {description}".strip()
|
||||
|
||||
corpus[doc_id] = doc_text
|
||||
|
||||
# Taxonomy labels
|
||||
topic_ids.append(doc_id)
|
||||
names_for_clustering.append(display_name.strip())
|
||||
descriptions_for_clustering.append(description.strip())
|
||||
labels_subfield.append(source.get("subfield", {}).get("id") or "unknown_subfield")
|
||||
labels_field.append(source.get("field", {}).get("id") or "unknown_field")
|
||||
labels_domain.append(source.get("domain", {}).get("id") or "unknown_domain")
|
||||
|
||||
sampled_topics = topics
|
||||
if sample_size and sample_size < len(topics):
|
||||
print(f"Sampling {sample_size} topics for query/keyword generation...")
|
||||
sampled_topics = random.sample(topics, sample_size)
|
||||
|
||||
query_count = 0
|
||||
for t in sampled_topics:
|
||||
source = t["_source"]
|
||||
doc_id = source["id"]
|
||||
keywords = source.get("keywords") or []
|
||||
|
||||
for keyword in keywords:
|
||||
if not keyword.strip():
|
||||
continue
|
||||
query_id = f"q_{query_count}"
|
||||
queries[query_id] = keyword
|
||||
|
||||
# Ground truth relevant documents: topic name
|
||||
rel_docs = {doc_id}
|
||||
relevant_docs[query_id] = rel_docs
|
||||
query_count += 1
|
||||
|
||||
print(f"Dataset Formulated: {len(corpus)} corpus documents, {len(queries)} queries.")
|
||||
|
||||
return {
|
||||
"corpus": corpus,
|
||||
"queries": queries,
|
||||
"relevant_docs": relevant_docs,
|
||||
"clustering": {
|
||||
"ids": topic_ids,
|
||||
"names": names_for_clustering,
|
||||
"descriptions": descriptions_for_clustering,
|
||||
"subfield": labels_subfield,
|
||||
"field": labels_field,
|
||||
"domain": labels_domain
|
||||
}
|
||||
}
|
||||
|
||||
def evaluate_model(model_name, data, output_dir):
|
||||
"""
|
||||
Load a model, measure operational speed, and calculate IR + clustering quality.
|
||||
"""
|
||||
model_safe_name = model_name.replace("/", "_").replace("-", "_")
|
||||
report_file = output_dir / f"model_report_{model_safe_name}.json"
|
||||
|
||||
print("\n==================================================")
|
||||
print(f"Evaluating Model: '{model_name}'")
|
||||
print("==================================================")
|
||||
|
||||
start_load = time.time()
|
||||
try:
|
||||
model = SentenceTransformer(model_name)
|
||||
except Exception as exc:
|
||||
print(f"ERROR: Failed to load model '{model_name}': {exc}")
|
||||
return None
|
||||
|
||||
load_time = time.time() - start_load
|
||||
print(f"Model loaded in {load_time:.2f} seconds.")
|
||||
|
||||
num_params = sum(p.numel() for p in model.parameters())
|
||||
param_count_m = num_params / 1_000_000
|
||||
vector_dim = model.get_sentence_embedding_dimension()
|
||||
print(f"Parameters: {param_count_m:.1f}M, Vector Dimension: {vector_dim}")
|
||||
|
||||
# --- FIXED: Perform a warm-up to initialize computation graphs ---
|
||||
print("Warming up model...")
|
||||
_ = model.encode(["warmup sentence"])
|
||||
|
||||
# 2. Measure Query Latency
|
||||
sample_queries = list(data["queries"].values())[:100]
|
||||
if not sample_queries:
|
||||
sample_queries = ["artificial intelligence", "machine learning"]
|
||||
|
||||
start_lat = time.time()
|
||||
for q in sample_queries:
|
||||
_ = model.encode(q)
|
||||
latency_ms = ((time.time() - start_lat) / len(sample_queries)) * 1000
|
||||
print(f"Average Query Latency: {latency_ms:.2f} ms")
|
||||
|
||||
# 3. Measure Ingestion Throughput
|
||||
sample_docs = list(data["corpus"].values())[:200]
|
||||
start_batch = time.time()
|
||||
_ = model.encode(sample_docs, batch_size=32)
|
||||
batch_time = time.time() - start_batch
|
||||
throughput_docs_sec = len(sample_docs) / batch_time
|
||||
print(f"Ingestion Throughput: {throughput_docs_sec:.2f} docs/sec")
|
||||
|
||||
# 4. Information Retrieval Evaluation
|
||||
print("Running Information Retrieval evaluation (NDCG, MRR, Recall)...")
|
||||
|
||||
# --- FIXED: Use precision_recall_at_k for true recall metrics ---
|
||||
evaluator = InformationRetrievalEvaluator(
|
||||
data["queries"],
|
||||
data["corpus"],
|
||||
data["relevant_docs"], # The evaluator natively accepts sets, no need to cast to lists
|
||||
name=model_safe_name,
|
||||
mrr_at_k=[10],
|
||||
ndcg_at_k=[10],
|
||||
precision_recall_at_k=[10] # This ensures true Recall is calculated across multiple sibling matches
|
||||
)
|
||||
|
||||
ir_results = evaluator(model)
|
||||
|
||||
# Extract keys safely
|
||||
ndcg_key = f"{model_safe_name}_cosine_ndcg@10"
|
||||
mrr_key = f"{model_safe_name}_cosine_mrr@10"
|
||||
recall_key = f"{model_safe_name}_cosine_recall@10" # Changed from accuracy to recall
|
||||
|
||||
ndcg_score = ir_results.get(ndcg_key, 0.0)
|
||||
mrr_score = ir_results.get(mrr_key, 0.0)
|
||||
recall_score = ir_results.get(recall_key, 0.0)
|
||||
|
||||
print(f"NDCG@10: {ndcg_score:.4f}, MRR@10: {mrr_score:.4f}, Recall@10: {recall_score:.4f}")
|
||||
|
||||
# 5. Clustering evaluation against ground-truth taxonomy
|
||||
print("Running Taxonomy Clustering evaluation (NMI)...")
|
||||
|
||||
unique_subfields = list(set(data["clustering"]["subfield"]))
|
||||
n_clusters = len(unique_subfields)
|
||||
|
||||
# Topic Names Clustering
|
||||
print("Clustering Topic Names...")
|
||||
clustering_names = data["clustering"]["names"]
|
||||
name_embeddings = model.encode(clustering_names, show_progress_bar=False, batch_size=64)
|
||||
|
||||
nmi_name = 0.0
|
||||
ari_name = 0.0
|
||||
if n_clusters > 1 and len(name_embeddings) > n_clusters:
|
||||
kmeans_name = KMeans(n_clusters=n_clusters, random_state=42, n_init='auto')
|
||||
assignments_name = kmeans_name.fit_predict(name_embeddings)
|
||||
nmi_name = metrics.normalized_mutual_info_score(data["clustering"]["subfield"], assignments_name)
|
||||
ari_name = metrics.adjusted_rand_score(data["clustering"]["subfield"], assignments_name)
|
||||
print(f"Names - Subfield Clustering NMI: {nmi_name:.4f}, ARI: {ari_name:.4f}")
|
||||
|
||||
# Topic Descriptions Clustering
|
||||
print("Clustering Topic Descriptions...")
|
||||
clustering_descs = data["clustering"]["descriptions"]
|
||||
desc_embeddings = model.encode(clustering_descs, show_progress_bar=False, batch_size=64)
|
||||
|
||||
nmi_desc = 0.0
|
||||
ari_desc = 0.0
|
||||
if n_clusters > 1 and len(desc_embeddings) > n_clusters:
|
||||
kmeans_desc = KMeans(n_clusters=n_clusters, random_state=42, n_init='auto')
|
||||
assignments_desc = kmeans_desc.fit_predict(desc_embeddings)
|
||||
nmi_desc = metrics.normalized_mutual_info_score(data["clustering"]["subfield"], assignments_desc)
|
||||
ari_desc = metrics.adjusted_rand_score(data["clustering"]["subfield"], assignments_desc)
|
||||
print(f"Descriptions - Subfield Clustering NMI: {nmi_desc:.4f}, ARI: {ari_desc:.4f}")
|
||||
|
||||
report = {
|
||||
"model_name": model_name,
|
||||
"parameters_m": param_count_m,
|
||||
"vector_dim": vector_dim,
|
||||
"latency_ms": latency_ms,
|
||||
"throughput_docs_sec": throughput_docs_sec,
|
||||
"ndcg_at_10": ndcg_score,
|
||||
"mrr_at_10": mrr_score,
|
||||
"recall_at_10": recall_score,
|
||||
"name_nmi": nmi_name,
|
||||
"name_ari": ari_name,
|
||||
"desc_nmi": nmi_desc,
|
||||
"desc_ari": ari_desc
|
||||
}
|
||||
|
||||
with open(report_file, "w", encoding="utf-8") as f:
|
||||
json.dump(report, f, indent=2, ensure_ascii=False)
|
||||
print(f"Saved model report to {report_file}")
|
||||
|
||||
return report
|
||||
|
||||
def generate_consolidated_report(output_dir, reports):
|
||||
if not reports:
|
||||
print("No reports to consolidate.")
|
||||
return
|
||||
|
||||
report_file = output_dir / "model_evaluation_report.md"
|
||||
print(f"\nCompiling consolidated report into {report_file}...")
|
||||
|
||||
sorted_reports = sorted(reports, key=lambda x: x["ndcg_at_10"], reverse=True)
|
||||
|
||||
lines = [
|
||||
"# Sentence Transformer Model Evaluation Report",
|
||||
"",
|
||||
"This report aggregates performance metrics and accuracy benchmarks for different Sentence Transformer models evaluated against the OpenAlex topic keywords dataset.",
|
||||
"",
|
||||
"## Overall Leaderboard",
|
||||
"",
|
||||
"| Rank | Model Name | Vector Dim | Params (M) | Query Latency (ms) | Throughput (docs/s) | NDCG@10 | MRR@10 | Recall@10 | Name NMI | Desc NMI |",
|
||||
"| :--- | :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |"
|
||||
]
|
||||
|
||||
for idx, r in enumerate(sorted_reports):
|
||||
name_nmi = r.get("name_nmi", 0.0)
|
||||
desc_nmi = r.get("desc_nmi", 0.0)
|
||||
lines.append(
|
||||
f"| {idx+1} | `{r['model_name']}` | {r['vector_dim']} | {r['parameters_m']:.1f}M | {r['latency_ms']:.2f}ms | {r['throughput_docs_sec']:.1f} | **{r['ndcg_at_10']:.4f}** | {r['mrr_at_10']:.4f} | {r['recall_at_10']:.4f} | {name_nmi:.4f} | {desc_nmi:.4f} |"
|
||||
)
|
||||
|
||||
lines.extend([
|
||||
"",
|
||||
"### Metric Definitions:",
|
||||
"* **NDCG@10**: Normalized Discounted Cumulative Gain. Measures how well the query maps to the target topic at the top 10 positions.",
|
||||
"* **MRR@10**: Mean Reciprocal Rank. Looks at the average of `1 / rank` for the first correctly matched topic.",
|
||||
"* **Recall@10**: Percentage of times the target document (excluding sibling topics) was successfully retrieved in the top 10.",
|
||||
"* **Name NMI**: Normalized Mutual Information of K-Means clusters of topic display names against ground truth OpenAlex subfields.",
|
||||
"* **Desc NMI**: Normalized Mutual Information of K-Means clusters of topic descriptions against ground truth OpenAlex subfields.",
|
||||
"* **Query Latency**: Time to encode a single search keyword.",
|
||||
"* **Throughput**: Ingestion batch encoding speed."
|
||||
])
|
||||
|
||||
with open(report_file, "w", encoding="utf-8") as f:
|
||||
f.write("\n".join(lines))
|
||||
print(f"Report compiled successfully at {report_file}")
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Evaluate Sentence Transformer models on OpenAlex topics.")
|
||||
parser.add_argument("--model", type=str, help="Specific model to evaluate (skips others).")
|
||||
parser.add_argument("--sample-size", type=int, help="Sample size of topics to evaluate keywords for (faster run).")
|
||||
parser.add_argument("--all", action="store_true", help="Evaluate all topics/keywords (default if sample-size omitted).")
|
||||
parser.add_argument("--output-dir", type=str, help="Custom directory to save reports.")
|
||||
parser.add_argument("--force-refresh", action="store_true", help="Force reload topics from Elasticsearch instead of cache.")
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if Path("/data").is_dir():
|
||||
data_dir = Path("/data")
|
||||
else:
|
||||
project_root = Path(__file__).parent.parent.parent.parent.parent.resolve()
|
||||
data_dir = project_root / "service" / "src" / "data"
|
||||
data_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
output_dir = Path(args.output_dir) if args.output_dir else data_dir
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
cache_file = data_dir / "raw_topics_cache.json"
|
||||
if cache_file.exists() and not args.force_refresh:
|
||||
print(f"Loading topics from local cache: {cache_file}")
|
||||
with open(cache_file, "r", encoding="utf-8") as f:
|
||||
topics = json.load(f)
|
||||
else:
|
||||
topics = fetch_all_topics()
|
||||
with open(cache_file, "w", encoding="utf-8") as f:
|
||||
json.dump(topics, f, indent=2, ensure_ascii=False)
|
||||
print(f"Cached {len(topics)} topics to {cache_file}")
|
||||
|
||||
if not topics:
|
||||
print("Error: No topics dataset available. Make sure Elasticsearch is running or cache exists.")
|
||||
sys.exit(1)
|
||||
|
||||
data = prepare_data(topics, sample_size=args.sample_size)
|
||||
|
||||
models_to_evaluate = DEFAULT_MODELS
|
||||
if args.model:
|
||||
models_to_evaluate = [args.model]
|
||||
|
||||
print(f"Models scheduled for evaluation: {models_to_evaluate}")
|
||||
|
||||
reports = []
|
||||
for m in models_to_evaluate:
|
||||
model_safe_name = m.replace("/", "_").replace("-", "_")
|
||||
report_file = output_dir / f"model_report_{model_safe_name}.json"
|
||||
|
||||
if report_file.exists() and not args.model:
|
||||
print(f"Loading cached evaluation report for '{m}' from {report_file}")
|
||||
with open(report_file, "r", encoding="utf-8") as f:
|
||||
reports.append(json.load(f))
|
||||
else:
|
||||
rep = evaluate_model(m, data, output_dir)
|
||||
if rep:
|
||||
reports.append(rep)
|
||||
|
||||
generate_consolidated_report(output_dir, reports)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,159 @@
|
||||
# Performance Summary
|
||||
|
||||
520 Keywords as query against hybrid & semantic search
|
||||
|
||||
- Search fields:
|
||||
- display name (Keyword & single vector)
|
||||
- description (Keyword & single vector)
|
||||
- keywords (Keyword & nested vectors)
|
||||
|
||||
- 26 Fields: 20 examples each
|
||||
| # | OpenAlex Field Name | Complete Test Queries |
|
||||
|---|---------------------|-----------------------------------------|
|
||||
| 01 | **Social Sciences** | `sociology, gender inequality in workplace, urbanization trends, political polarization, human rights law, social mobility, qualitative research methods, demographic shifts, cultural anthropology, criminal justice reform, public policy analysis, indigenous languages, voter behavior, globalization effects, community development, media studies, social movements, migration patterns, welfare systems, family dynamics` |
|
||||
| 02 | **Medicine** | `cardiology, diabetes management, oncology treatment options, clinical trials, pediatric care, chronic pain relief, cardiovascular disease prevention, surgical procedures, infectious disease outbreak, medical imaging techniques, hypertension guidelines, patient outcomes, immunotherapy for cancer, epidemiology study, stroke rehabilitation, genetic disorders, telemedicine adoption, internal medicine, diagnostic accuracy, palliative care` |
|
||||
| 03 | **Engineering** | `civil engineering, structural integrity, aerospace propulsion, mechanical design, robotics automation, geotechnical analysis, bridge construction, renewable energy grid, fluid mechanics, electrical circuits, thermodynamics applications, manufacturing optimization, control systems engineering, materials fatigue, hvac design, biomedical devices, transportation infrastructure, signal processing, solid mechanics, industrial engineering` |
|
||||
| 04 | **Computer Science** | `machine learning, natural language processing, cybersecurity protocols, cloud computing architecture, neural networks, database optimization, software engineering practices, computer vision algorithms, blockchain technology, artificial intelligence ethics, human computer interaction, operating systems, distributed ledgers, compiler design, data mining techniques, cryptographic keys, quantum computing algorithms, web development frameworks, reinforcement learning, graph databases` |
|
||||
| 05 | **Arts and Humanities** | `art history, literary criticism, philosophy of mind, renaissance architecture, linguistics morphology, creative writing, musical composition, theater history, postmodern literature, ethics and morality, historical archives, film analysis, religious studies, classical archaeology, metaphysics, cultural heritage preservation, comparative literature, linguistic semantics, medieval art, epistemology` |
|
||||
| 06 | **Biochemistry, Genetics and Molecular Biology** | `dna replication, crispr gene editing, protein folding, rna sequencing, enzyme kinetics, cellular signaling pathways, metabolic pathways, genomic sequencing, molecular cloning, apoptosis mechanism, mitochondrial DNA, epigenetic modifications, proteomics analysis, gene expression regulation, chromatin remodeling, amino acid synthesis, nucleic acids, cellular differentiation, lipid metabolism, transcription factors` |
|
||||
| 07 | **Agricultural and Biological Sciences** | `crop yield optimization, plant physiology, marine biology, soil microbiology, entomology study, botany research, sustainable agriculture, animal behavior, ecology systems, pest management, forestry conservation, photosynthesis mechanism, biodiversity preservation, aquaculture techniques, agronomy practices, seed germination, horticulture science, wildlife ecology, plant pathology, livestock breeding` |
|
||||
| 08 | **Environmental Science** | `climate change mitigation, renewable resource management, air pollution monitoring, microplastics in oceans, deforestation rates, waste management systems, carbon footprint reduction, biodiversity loss, global warming impacts, ecosystem restoration, water quality analysis, urban sustainability, environmental impact assessment, glacier melting, conservation biology, greenhouse gas emissions, soil erosion control, renewable energy transition, climate adaptation strategies, acid rain causes` |
|
||||
| 09 | **Business, Management and Accounting** | `corporate strategy, supply chain logistics, financial auditing, marketing analytics, human resource management, organizational behavior, consumer behavior trends, risk assessment framework, entrepreneurship ecosystems, project management methodologies, accounting principles, brand equity, leadership styles, business ethics, digital transformation strategy, operations management, corporate governance, market segmentation, strategic planning, financial reporting standards` |
|
||||
| 10 | **Psychology** | `cognitive behavioral therapy, developmental psychology, social anxiety disorder, memory retention techniques, neuropsychology assessment, human behavior analysis, mental health counseling, personality traits theory, child development stages, addiction recovery mechanisms, emotional intelligence, perception and sensation, group dynamics psychology, depression treatment outcomes, stress management interventions, motivation theories, cognitive dissonance, behavioral psychology, mindfulness practices, sleep disorders psychology` |
|
||||
| 11 | **Materials Science** | `nanomaterials synthesis, graphene applications, polymers characterization, metallurgy engineering, semiconductor fabrication, composite materials design, biomaterials tissue engineering, thin film deposition, corrosion resistance, superconductors properties, ceramic engineering, alloy development, material degradation, photovoltaic materials, mechanical testing of alloys, smart materials technology, crystal structure analysis, carbon nanotubes research, thermal conductivity materials, magnetic materials applications` |
|
||||
| 12 | **Economics, Econometrics and Finance** | `macroeconomic policy, econometric modeling, financial market analysis, monetary theory, microeconomics principles, game theory applications, inflation rates forecast, labor economics, behavioral finance, portfolio optimization, international trade agreements, fiscal policy impact, time series analysis, asset pricing models, poverty reduction strategies, economic growth models, corporate finance theory, cryptocurrency economics, market equilibrium, public finance management` |
|
||||
| 13 | **Health Professions** | `physical therapy techniques, occupational therapy interventions, speech language pathology, radiologic technology, emergency medical services, healthcare administration, audiology assessments, rehabilitation sciences, clinical nutrition, paramedic protocols, respiratory therapy management, health informatics systems, dietetics practice, patient care quality, medical laboratory technology, orthotics and prosthetics, interprofessional healthcare collaboration, community health education, sports medicine rehabilitation, physician assistant training` |
|
||||
| 14 | **Physics and Astronomy** | `quantum mechanics, astrophysics research, dark matter detection, particle physics collision, general relativity theory, cosmology evolution, exoplanet discovery, nuclear fusion energy, condensed matter physics, string theory concepts, optics and photonics, black hole thermodynamics, gravitational waves detection, statistical mechanics, plasma physics applications, stellar evolution models, high energy physics, quantum entanglement experiments, spectroscopy techniques, thermodynamics principles` |
|
||||
| 15 | **Chemistry** | `organic synthesis, analytical chemistry methods, inorganic compounds coordination, physical chemistry thermodynamics, spectroscopy chemical analysis, catalysis mechanism design, polymer chemistry polymerization, electrochemistry batteries, medicinal chemistry design, chromatography separation techniques, chemical kinetics reactions, mass spectrometry profiling, computational chemistry modeling, environmental chemistry monitoring, photochemistry solar conversion, biophysical chemistry structure, green chemistry principles, molecular orbital theory, supramolecular architecture, crystallography structure determination` |
|
||||
| 16 | **Mathematics** | `linear algebra, differential equations solution, algebraic topology, number theory cryptography, calculus fundamentals, probability and statistics, discrete mathematics structures, numerical analysis algorithms, complex analysis functions, geometry axiom theories, combinatorics counting techniques, mathematical modeling simulation, set theory foundations, graph theory applications, real analysis limits, partial differential equations, abstract algebra groups, optimization theory algorithms, stochastic processes modeling, chaos theory dynamics` |
|
||||
| 17 | **Neuroscience** | `synaptic plasticity, neurodegenerative diseases mechanisms, brain mapping fmri, cognitive neuroscience memory, neurotransmitter receptors pathways, neural network architecture, behavioral neuroscience addiction, neurogenesis adult brain, axon guidance development, spinal cord injury, sensory processing systems, motor control pathways, alzheimer disease pathology, parkinson motor deficits, neuroimmunology inflammation, sleep neural circuits, epilepsy seizure mechanisms, computational neuroscience models, neuropharmacology drugs action, brain computer interface` |
|
||||
| 18 | **Decision Sciences** | `operations research optimization, decision analysis models, multi criteria decision making, game theory strategies, risk analysis management, linear programming applications, forecasting methods business, supply chain optimization, stochastic modeling systems, queuing theory performance, decision tree classification, predictive analytics framework, statistical decision theory, heuristic search optimization, inventory control models, simulation optimization methods, behavioral decision making, utility theory choices, data driven decision support, dynamic programming problems` |
|
||||
| 19 | **Earth and Planetary Sciences** | `plate tectonics geology, seismology earthquake prediction, volcanology eruption monitoring, paleoclimatology proxy data, planetary geology mars, mineralogy crystal structures, sedimentology deposition environments, stratigraphy rock layers, geomorphology landscape evolution, hydrology water cycle, meteorology weather forecasting, oceanography ocean currents, geochemistry isotopic analysis, remote sensing earth, petrology rock formation, impact cratering planetary, paleontology fossil records, glaciology ice sheets, geophysics magnetic fields, environmental geology hazards` |
|
||||
| 20 | **Immunology and Microbiology** | `t cell activation, antibody response mechanics, bacterial resistance antibiotics, viral replication cycle, autoimmune disease pathogenesis, innate immunity defense, vaccine development strategies, microbiome gut health, macrophage polarization function, pathogen virulence factors, cytokine storm response, mycology fungal infections, parasitology host interaction, adaptive immune system, antigen presentation pathway, bacteriophage therapy applications, immunotherapy cancer treatment, microbial biofilms formation, virology host defense, inflammation signaling pathways` |
|
||||
| 21 | **Energy** | `solar cell efficiency, wind turbine aerodynamics, battery energy storage, hydrogen fuel cells, nuclear power generation, biofuel production technologies, geothermal energy extraction, energy grid optimization, fossil fuel alternative, hydroelectric power systems, energy efficiency buildings, carbon capture storage, renewable energy policy, smart grid infrastructure, tidal energy conversion, thermal energy storage, power electronics converters, microgrid energy systems, biomass combustion processes, energy consumption forecasting` |
|
||||
| 22 | **Pharmacology, Toxicology and Pharmaceutics** | `drug delivery systems, pharmacokinetics modeling analysis, pharmacodynamics receptor binding, toxicology safety assessment, pharmaceutical formulation design, bioavailability drug absorption, cytotoxicity assays testing, clinical pharmacology trials, neuropharmacology drug effects, cardiotoxicity drug evaluation, nanoparticle drug carriers, pharmacogenomics personalized medicine, drug metabolism enzymes, adverse drug reactions, controlled release tablets, heavy metal toxicology, target identification drug, natural product pharmacology, dosage form optimization, endocrine disruptors toxicology` |
|
||||
| 23 | **Nursing** | `patient care management, nursing education curriculum, clinical nursing practice, geriatric nursing care, pediatric nursing interventions, critical care nursing, palliative nursing care, nursing leadership styles, community health nursing, evidence based nursing, mental health nursing, maternal newborn nursing, wound care management, nurse practitioner roles, patient safety protocols, nursing burnout prevention, oncology nursing practices, chronic disease management, telehealth nursing care, infection control nursing` |
|
||||
| 24 | **Chemical Engineering** | `process systems engineering, chemical reactor design, transport phenomena fluid, separation processes distillation, catalytic reaction engineering, bioprocess engineering fermentation, thermodynamics chemical mixtures, heat exchanger network, polymer processing extrusion, mass transfer operations, process safety management, fluidized bed reactor, chemical plant optimization, multi phase flow, computational fluid dynamics, industrial scale synthesis, green chemical engineering, adsorption separation kinetics, process control loops, materials processing chemical` |
|
||||
| 25 | **Dentistry** | `endodontic treatment procedures, periodontal disease therapy, orthodontic alignment techniques, dental implant surgery, prosthodontics crown design, pediatric dentistry prevention, oral maxillofacial surgery, dental caries prevention, restorative dentistry materials, oral pathology diagnosis, laser dentistry applications, dental biomaterials wear, cone beam ct, salivary diagnostics biomarkers, aesthetic dentistry veneers, root canal morphology, gingival recession treatment, fluoride treatment efficacy, dental pulp stem cells, temporomandibular joint disorders` |
|
||||
| 26 | **Veterinary** | `veterinary medicine diagnosis, canine parvovirus treatment, feline leukemia virus, equine sports medicine, bovine mastitis control, veterinary surgery techniques, animal nutrition guidelines, zoonotic disease transmission, veterinary oncology treatment, avian medicine care, small animal internal, livestock herd health, veterinary pharmacology drugs, animal welfare assessment, veterinary radiology imaging, feline behavior issues, canine hip dysplasia, veterinary epidemiology outbreaks, companion animal care, exotic pet medicine` |
|
||||
|
||||
## Latency results
|
||||
|
||||
| Query Configuration | Mean | Median | p95 |
|
||||
| :-------------------------------------- | :---: | :----: | :---: |
|
||||
| **Embedding Encode** | 35.81 | 35.11 | 42.98 |
|
||||
| **Pure Lexical Search (`multi_match`)** | 44.03 | 43.21 | 52.12 |
|
||||
|
||||
|
|
||||
| **Description Only (`description_vector`)** | 27.11 | 24.83 | 40.23 |
|
||||
| **Display Name Only (`display_name_vector`)** | 42.71 | 45.33 | 55.51 |
|
||||
| **Keywords Only (`keyword_vectors` - Nested)** | 47.65 | 47.06 | 56.88 |
|
||||
| **Display Name & Description** | 46.62 | 49.22 | 59.43 |
|
||||
| **Display Name & Keywords (Nested)** | 52.11 | 51.36 | 61.22 |
|
||||
| **Combined (All 3 vector fields)** | 57.06 | 55.65 | 67.32 |
|
||||
|
|
||||
| **Hybrid Search (Lexical + All 3 vector fields)** | 58.65 | 57.09 | 69.10 |
|
||||
|
||||
- should query runs hybrid and semantic concurrently => nested Keyword vector search bottleneck
|
||||
- Hybrid returns more results overall due to partailly matching words in display name & Keywords
|
||||
- Query: "Cell Adhesion Molecules Research"
|
||||
- Low rank return: "Q Methodology Applications"
|
||||
- because: ["**Research** Methods", "Qualitative **Research**"] Keywords
|
||||
|
||||
- Changed k & num_candidates to 500 (fixed bug, where not all keywords were considered):
|
||||
| Query Configuration | Mean | Median | p95 |
|
||||
| :--- | :---: | :---: | :---: |
|
||||
| **Embedding Encode** | 38.25 | 37.41 | 45.48 |
|
||||
| **Pure Lexical Search (`multi_match`)** | 44.98 | 43.69 | 55.21 |
|
||||
| **Description Only (`description_vector`)** | 29.69 | 27.76 | 45.46 |
|
||||
| **Display Name Only (`display_name_vector`)** | 45.20 | 46.68 | 59.47 |
|
||||
| **Keywords Only (`keyword_vectors` - Nested)** | 50.00 | 48.89 | 60.61 |
|
||||
| **Display Name & Description** | 49.84 | 51.16 | 66.37 |
|
||||
| **Display Name & Keywords (Nested)** | 55.50 | 54.16 | 66.12 |
|
||||
| **Combined (All 3 vector fields)** | 61.81 | 59.74 | 75.30 |
|
||||
| **Hybrid Search (Lexical + All 3 vector fields)** | 63.25 | 61.05 | 76.39 |
|
||||
|
||||
# Search Score Breakdown & Weight Analysis Report
|
||||
|
||||
---
|
||||
|
||||
## Global Score Contribution
|
||||
|
||||
| Weight Component | Boost | Avg. Score Contribution | Percentage of Total Score |
|
||||
| :-------------------------------------------- | :---: | :---------------------: | :-----------------------: |
|
||||
| **Lexical Match (`multi_match`)** | 1.0 | 36.2275 | 54.31% |
|
||||
| **Title Vector (`display_name_vector`)** | 30.0 | 17.9748 | 26.95% |
|
||||
| **Description Vector (`description_vector`)** | 15.0 | 2.5502 | 3.82% |
|
||||
| **Nested Keywords (`keyword_vectors`)** | 25.0 | 9.9531 | 14.92% |
|
||||
|
||||
| After fix:
|
||||
| **Lexical Match (`multi_match`)** | 1.0 | 38.2910 | 44.79% |
|
||||
| **Title Vector (`display_name_vector`)** | 30.0 | 22.5727 | 26.40% |
|
||||
| **Description Vector (`description_vector`)** | 15.0 | 3.3518 | 3.92% |
|
||||
| **Nested Keywords (`keyword_vectors`)** | 25.0 | 21.2808 | 24.89% |
|
||||
|
||||
---
|
||||
|
||||
## Contribution Breakdown by Field
|
||||
|
||||
| Field | Avg. Score | Lexical % | Title Vector % | Description Vector % | Keywords Vector % |
|
||||
| :------------------------------------------- | :--------: | :-------: | :------------: | :------------------: | :---------------: |
|
||||
| Social Sciences | 76.10 | 42.6% | 27.0% | 6.2% | 24.2% |
|
||||
| Medicine | 71.58 | 43.9% | 26.5% | 4.1% | 25.5% |
|
||||
| Engineering | 67.73 | 43.8% | 27.6% | 3.5% | 25.2% |
|
||||
| Computer Science | 69.63 | 47.3% | 23.4% | 4.0% | 25.3% |
|
||||
| Arts and Humanities | 75.38 | 40.2% | 28.7% | 5.9% | 25.1% |
|
||||
| Biochemistry, Genetics and Molecular Biology | 64.32 | 43.5% | 26.7% | 1.6% | 28.1% |
|
||||
| Agricultural and Biological Sciences | 70.48 | 38.0% | 30.7% | 4.2% | 27.1% |
|
||||
| Environmental Science | 72.92 | 44.3% | 26.3% | 5.0% | 24.3% |
|
||||
| Business, Management and Accounting | 75.14 | 47.1% | 25.8% | 2.7% | 24.5% |
|
||||
| Psychology | 67.50 | 40.8% | 28.5% | 4.9% | 25.8% |
|
||||
| Materials Science | 75.99 | 40.4% | 28.5% | 6.4% | 24.7% |
|
||||
| Economics, Econometrics and Finance | 67.58 | 43.0% | 25.3% | 5.7% | 25.9% |
|
||||
| Health Professions | 62.96 | 41.9% | 28.4% | 3.2% | 26.5% |
|
||||
| Physics and Astronomy | 70.10 | 47.5% | 24.4% | 3.6% | 24.5% |
|
||||
| Chemistry | 73.17 | 44.6% | 26.8% | 4.2% | 24.4% |
|
||||
| Mathematics | 74.83 | 48.1% | 24.7% | 4.4% | 22.9% |
|
||||
| Neuroscience | 68.20 | 45.2% | 24.6% | 5.2% | 25.0% |
|
||||
| Decision Sciences | 67.13 | 49.5% | 23.3% | 2.4% | 24.8% |
|
||||
| Earth and Planetary Sciences | 64.59 | 41.3% | 28.9% | 2.4% | 27.3% |
|
||||
| Immunology and Microbiology | 68.62 | 44.9% | 25.7% | 3.6% | 25.9% |
|
||||
| Energy | 80.04 | 50.3% | 22.8% | 5.4% | 21.6% |
|
||||
| Pharmacology, Toxicology and Pharmaceutics | 64.61 | 45.2% | 26.1% | 2.4% | 26.2% |
|
||||
| Nursing | 75.86 | 47.8% | 26.5% | 2.8% | 22.8% |
|
||||
| Chemical Engineering | 59.12 | 48.5% | 26.0% | 1.1% | 24.4% |
|
||||
| Dentistry | 62.51 | 44.1% | 28.1% | 3.1% | 24.7% |
|
||||
| Veterinary | 53.56 | 49.2% | 26.9% | 1.9% | 22.0% |
|
||||
|
||||
---
|
||||
|
||||
## Score Breakdown Examples (Top Match per Field Sample)
|
||||
|
||||
| Field & Query | Fixed Variant Performance | Bug Variant Performance |
|
||||
| :------------------------------------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| **Social Sciences**<br>`"sociology"` | **Topic**: Emile Durkheim and Sociology<br>**Total Score**: 80.7964<br><br>• Lexical: 33.6289<br>• Title KNN: 25.3876<br>• Desc KNN: 12.1561<br>• Key KNN: 24.9897<br><br>**Keywords**:<br>• 'sociology' (0.9996)<br>• 'social conditions' (0.8254) | **Topic**: Emile Durkheim and Sociology<br>**Total Score**: 55.4088<br><br>• Lexical: 33.6289<br>• Title KNN: 0.0000<br>• Desc KNN: 12.1561<br>• Key KNN: 24.9897<br><br>**Keywords**:<br>• 'sociology' (0.9996)<br>• 'social conditions' (0.8254) |
|
||||
| **Medicine**<br>`"cardiology"` | **Topic**: Cardiomyopathy and Myosin Studies<br>**Total Score**: 62.3436<br><br>• Lexical: 0.0000<br>• Title KNN: 26.0134<br>• Desc KNN: 12.4090<br>• Key KNN: 23.9212<br><br>**Keywords**:<br>• 'Cardiomyopathies' (0.9568)<br>• 'Cardiac Imaging' (0.9192) | **Topic**: Cardiac Imaging and Diagnostics<br>**Total Score**: 27.6677<br><br>• Lexical: 0.0000<br>• Title KNN: 27.6677<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Cardiac Imaging' (0.9192)<br>• 'Myocardial Infarction' (0.8564) |
|
||||
| **Engineering**<br>`"civil engineering"` | **Topic**: Civil and Structural Engineering Research<br>**Total Score**: 97.2652<br><br>• Lexical: 60.8415<br>• Title KNN: 28.1018<br>• Desc KNN: 12.3099<br>• Key KNN: 24.8941<br><br>**Keywords**:<br>• 'Civil Engineering' (0.9958)<br>• 'Construction' (0.8388) | **Topic**: Civil and Structural Engineering Research<br>**Total Score**: 97.2652<br><br>• Lexical: 60.8415<br>• Title KNN: 28.1018<br>• Desc KNN: 12.3099<br>• Key KNN: 24.8941<br><br>**Keywords**:<br>• 'Civil Engineering' (0.9958)<br>• 'Construction' (0.8388) |
|
||||
| **Computer Science**<br>`"machine learning"` | **Topic**: Machine Learning and Algorithms<br>**Total Score**: 99.2549<br><br>• Lexical: 55.5562<br>• Title KNN: 29.2590<br>• Desc KNN: 12.5187<br>• Key KNN: 24.9693<br><br>**Keywords**:<br>• 'Machine Learning' (0.9988)<br>• 'Deep Learning' (0.9119) | **Topic**: Machine Learning and Algorithms<br>**Total Score**: 74.2856<br><br>• Lexical: 55.5562<br>• Title KNN: 29.2590<br>• Desc KNN: 12.5187<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Machine Learning' (0.9988)<br>• 'Deep Learning' (0.9119) |
|
||||
| **Arts and Humanities**<br>`"art history"` | **Topic**: Art, Politics, and Modernism<br>**Total Score**: 79.6751<br><br>• Lexical: 41.4462<br>• Title KNN: 26.8390<br>• Desc KNN: 12.2412<br>• Key KNN: 23.1472<br><br>**Keywords**:<br>• 'Contemporary Art' (0.9259)<br>• 'Art Theory' (0.8902) | **Topic**: Art History and Market Analysis<br>**Total Score**: 54.6477<br><br>• Lexical: 44.3255<br>• Title KNN: 27.6256<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Art Market' (0.8499) |
|
||||
| **Biochemistry, Genetics...**<br>`"dna replication"` | **Topic**: DNA Repair Mechanisms<br>**Total Score**: 69.5873<br><br>• Lexical: 37.9645<br>• Title KNN: 25.5676<br>• Desc KNN: 0.0000<br>• Key KNN: 21.2950<br><br>**Keywords**:<br>• 'Homologous Recombination' (0.8518) | **Topic**: DNA Repair Mechanisms<br>**Total Score**: 48.2923<br><br>• Lexical: 37.9645<br>• Title KNN: 25.5676<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Homologous Recombination' (0.8518) |
|
||||
| **Agricultural Sciences**<br>`"crop yield optimization"` | **Topic**: Crop Yield and Soil Fertility<br>**Total Score**: 86.9026<br><br>• Lexical: 72.9192<br>• Title KNN: 25.6184<br>• Desc KNN: 0.0000<br>• Key KNN: 21.9673<br><br>**Keywords**:<br>• 'Crop Management' (0.8787)<br>• 'Maize Yield' (0.8515) | **Topic**: Soil Management and Crop Yield<br>**Total Score**: 65.6488<br><br>• Lexical: 58.5754<br>• Title KNN: 26.3319<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'No-till Crop Production' (0.8136) |
|
||||
| **Environmental Science**<br>`"climate change mitigation"` | **Topic**: Climate Change, Adaptation, Migration<br>**Total Score**: 95.6090<br><br>• Lexical: 55.1717<br>• Title KNN: 24.9003<br>• Desc KNN: 12.3419<br>• Key KNN: 23.2867<br><br>**Keywords**:<br>• 'Climate Change' (0.9315) | **Topic**: Climate Change and Sustainable Development<br>**Total Score**: 72.0562<br><br>• Lexical: 52.0331<br>• Title KNN: 27.6359<br>• Desc KNN: 12.3920<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Climate Change' (0.9314)<br>• 'Environmental Policy' (0.8447) |
|
||||
| **Business & Accounting**<br>`"corporate strategy"` | **Topic**: Political Influence and Corporate Strategies<br>**Total Score**: 70.1485<br><br>• Lexical: 43.3796<br>• Title KNN: 25.4050<br>• Desc KNN: 0.0000<br>• Key KNN: 23.5512<br><br>**Keywords**:<br>• 'Business Strategy' (0.9420)<br>• 'Corporate Governance' (0.8537) | **Topic**: Corporate Management and Leadership<br>**Total Score**: 44.0634<br><br>• Lexical: 18.0385<br>• Title KNN: 26.0249<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• _None matched_ |
|
||||
| **Psychology**<br>`"cognitive behavioral therapy"` | **Topic**: Psychological Treatments and Assessments<br>**Total Score**: 74.0625<br><br>• Lexical: 33.9552<br>• Title KNN: 26.3648<br>• Desc KNN: 0.0000<br>• Key KNN: 24.8575<br><br>**Keywords**:<br>• 'Cognitive Behavioral Therapy' (0.9943)<br>• 'Rational Emotive Behavior Therapy' (0.8906) | **Topic**: Psychological Treatments and Assessments<br>**Total Score**: 74.0625<br><br>• Lexical: 33.9552<br>• Title KNN: 26.3648<br>• Desc KNN: 0.0000<br>• Key KNN: 24.8575<br><br>**Keywords**:<br>• 'Cognitive Behavioral Therapy' (0.9943)<br>• 'Rational Emotive Behavior Therapy' (0.8906) |
|
||||
| **Materials Science**<br>`"nanomaterials synthesis"` | **Topic**: Copper-based nanomaterials and applications<br>**Total Score**: 79.3170<br><br>• Lexical: 31.3198<br>• Title KNN: 25.5626<br>• Desc KNN: 12.8334<br>• Key KNN: 23.2389<br><br>**Keywords**:<br>• 'Nanostructures' (0.9296)<br>• 'Nanocrystals' (0.8989) | **Topic**: Nanoparticles: synthesis and applications<br>**Total Score**: 51.4193<br><br>• Lexical: 41.6580<br>• Title KNN: 28.1196<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Nanomaterials' (0.9593)<br>• 'Nanoparticles' (0.9017) |
|
||||
| **Economics & Finance**<br>`"macroeconomic policy"` | **Topic**: Monetary Policy and Economic Impact<br>**Total Score**: 77.2466<br><br>• Lexical: 33.6052<br>• Title KNN: 27.9601<br>• Desc KNN: 12.7554<br>• Key KNN: 23.1466<br><br>**Keywords**:<br>• 'Monetary Policy' (0.9259)<br>• 'Fiscal Policy' (0.8719) | **Topic**: Monetary Policy and Economic Impact<br>**Total Score**: 54.1000<br><br>• Lexical: 33.6052<br>• Title KNN: 27.9601<br>• Desc KNN: 12.7554<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Monetary Policy' (0.9259)<br>• 'Fiscal Policy' (0.8719) |
|
||||
| **Health Professions**<br>`"physical therapy techniques"` | **Topic**: Physical Activity and Health<br>**Total Score**: 63.6719<br><br>• Lexical: 35.4732<br>• Title KNN: 24.8417<br>• Desc KNN: 0.0000<br>• Key KNN: 21.5571<br><br>**Keywords**:<br>• 'Physical Fitness' (0.8623)<br>• 'Exercise' (0.8567) | **Topic**: Physical Education and Training Studies<br>**Total Score**: 41.6865<br><br>• Lexical: 34.0993<br>• Title KNN: 25.9162<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Physical Education' (0.8518)<br>• 'Athletic Training' (0.8386) |
|
||||
| **Physics and Astronomy**<br>`"quantum mechanics"` | **Topic**: Quantum Mechanics and Applications<br>**Total Score**: 100.0179<br><br>• Lexical: 62.6773<br>• Title KNN: 29.4806<br>• Desc KNN: 12.8902<br>• Key KNN: 23.1009<br><br>**Keywords**:<br>• 'Quantum Interpretations' (0.9240)<br>• 'Quantum Measurement' (0.9195) | **Topic**: Quantum Mechanics and Non-Hermitian Physics<br>**Total Score**: 82.1469<br><br>• Lexical: 59.7515<br>• Title KNN: 28.2917<br>• Desc KNN: 0.0000<br>• Key KNN: 24.8390<br><br>**Keywords**:<br>• 'Quantum Mechanics' (0.9936)<br>• 'Non-Hermitian Physics' (0.8265) |
|
||||
| **Chemistry**<br>`"organic synthesis"` | **Topic**: Organic Chemistry Synthesis Methods<br>**Total Score**: 93.3478<br><br>• Lexical: 51.1392<br>• Title KNN: 28.8346<br>• Desc KNN: 12.8016<br>• Key KNN: 21.2545<br><br>**Keywords**:<br>• 'Total Synthesis' (0.8502) | **Topic**: Organic Chemistry Synthesis Methods<br>**Total Score**: 72.0932<br><br>• Lexical: 51.1392<br>• Title KNN: 28.8346<br>• Desc KNN: 12.8016<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Total Synthesis' (0.8502) |
|
||||
| **Mathematics**<br>`"linear algebra"` | **Topic**: Advanced Algebra and Logic<br>**Total Score**: 69.1804<br><br>• Lexical: 21.0841<br>• Title KNN: 26.3365<br>• Desc KNN: 0.0000<br>• Key KNN: 21.7598<br><br>**Keywords**:<br>• 'MV-algebras' (0.8704)<br>• 'Algebraic Semantics' (0.8542) | **Topic**: Matrix Theory and Algorithms<br>**Total Score**: 51.1267<br><br>• Lexical: 42.7259<br>• Title KNN: 0.0000<br>• Desc KNN: 0.0000<br>• Key KNN: 24.3482<br><br>**Keywords**:<br>• 'Numerical Linear Algebra' (0.9739) |
|
||||
| **Neuroscience**<br>`"synaptic plasticity"` | **Topic**: Neuroscience and Neuropharmacology Research<br>**Total Score**: 59.8949<br><br>• Lexical: 34.7332<br>• Title KNN: 0.0000<br>• Desc KNN: 13.1294<br>• Key KNN: 24.0698<br><br>**Keywords**:<br>• 'Synaptic Plasticity' (0.9628)<br>• 'Neuronal Circuits' (0.8298) | **Topic**: Neuroscience and Neuropharmacology Research<br>**Total Score**: 59.8949<br><br>• Lexical: 34.7332<br>• Title KNN: 0.0000<br>• Desc KNN: 13.1294<br>• Key KNN: 24.0698<br><br>**Keywords**:<br>• 'Synaptic Plasticity' (0.9628)<br>• 'Neuronal Circuits' (0.8298) |
|
||||
| **Decision Sciences**<br>`"operations research optimization"` | **Topic**: Operations Management Techniques<br>**Total Score**: 72.2617<br><br>• Lexical: 45.7187<br>• Title KNN: 25.8359<br>• Desc KNN: 0.0000<br>• Key KNN: 20.3829<br><br>**Keywords**:<br>• 'Operations Management' (0.8153) | **Topic**: Management and Optimization Techniques<br>**Total Score**: 67.5272<br><br>• Lexical: 38.2684<br>• Title KNN: 27.0016<br>• Desc KNN: 0.0000<br>• Key KNN: 22.7133<br><br>**Keywords**:<br>• 'Operations Research' (0.9085) |
|
||||
| **Earth Sciences**<br>`"plate tectonics geology"` | **Topic**: Geological and Geochemical Analysis<br>**Total Score**: 81.4082<br><br>• Lexical: 47.1954<br>• Title KNN: 24.9384<br>• Desc KNN: 0.0000<br>• Key KNN: 24.0854<br><br>**Keywords**:<br>• 'Plate Tectonics' (0.9634)<br>• 'Tectonics' (0.9412) | **Topic**: Geological and Geophysical Studies<br>**Total Score**: 76.8806<br><br>• Lexical: 33.5170<br>• Title KNN: 25.9864<br>• Desc KNN: 0.0000<br>• Key KNN: 24.0846<br><br>**Keywords**:<br>• 'Plate Tectonics' (0.9634)<br>• 'Tectonic Model' (0.8970) |
|
||||
| **Immunology & Micro.**<br>`"t cell activation"` | **Topic**: T-cell and B-cell Immunology<br>**Total Score**: 101.7294<br><br>• Lexical: 58.5911<br>• Title KNN: 26.2074<br>• Desc KNN: 12.7561<br>• Key KNN: 22.2172<br><br>**Keywords**:<br>• 'Memory T Cells' (0.8887)<br>• 'TGF-ß' (0.8379) | **Topic**: T-cell and B-cell Immunology<br>**Total Score**: 79.5122<br><br>• Lexical: 58.5911<br>• Title KNN: 26.2074<br>• Desc KNN: 12.7561<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Memory T Cells' (0.8887)<br>• 'TGF-ß' (0.8379) |
|
||||
| **Energy**<br>`"solar cell efficiency"` | **Topic**: solar cell performance optimization<br>**Total Score**: 100.7331<br><br>• Lexical: 69.7479<br>• Title KNN: 28.9188<br>• Desc KNN: 12.4518<br>• Key KNN: 21.6075<br><br>**Keywords**:<br>• 'Energy Conversion Efficiency' (0.8643)<br>• 'Multijunction Solar Cells' (0.8636) | **Topic**: solar cell performance optimization<br>**Total Score**: 79.1256<br><br>• Lexical: 69.7479<br>• Title KNN: 28.9188<br>• Desc KNN: 12.4518<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Energy Conversion Efficiency' (0.8643)<br>• 'Multijunction Solar Cells' (0.8636) |
|
||||
| **Pharmacology & Tox.**<br>`"drug delivery systems"` | **Topic**: Advanced Drug Delivery Systems<br>**Total Score**: 101.0864<br><br>• Lexical: 82.7073<br>• Title KNN: 29.0884<br>• Desc KNN: 0.0000<br>• Key KNN: 23.9235<br><br>**Keywords**:<br>• 'Drug Delivery' (0.9569) | **Topic**: Advanced Drug Delivery Systems<br>**Total Score**: 77.1629<br><br>• Lexical: 82.7073<br>• Title KNN: 29.0884<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Drug Delivery' (0.9569) |
|
||||
| **Nursing**<br>`"patient care management"` | **Topic**: Family and Patient Care in ICU<br>**Total Score**: 81.2835<br><br>• Lexical: 62.5713<br>• Title KNN: 25.2221<br>• Desc KNN: 0.0000<br>• Key KNN: 23.3629<br><br>**Keywords**:<br>• 'Patient-Centered Care' (0.9345)<br>• 'Critical Care' (0.8654) | **Topic**: Health Services Management and Policy<br>**Total Score**: 49.0703<br><br>• Lexical: 44.9180<br>• Title KNN: 0.0000<br>• Desc KNN: 0.0000<br>• Key KNN: 24.1204<br><br>**Keywords**:<br>• 'patient care' (0.9648)<br>• 'hospital management' (0.9044) |
|
||||
| **Chemical Engineering**<br>`"process systems engineering"` | **Topic**: Systems Engineering Methodologies<br>**Total Score**: 69.4196<br><br>• Lexical: 46.7857<br>• Title KNN: 27.1586<br>• Desc KNN: 0.0000<br>• Key KNN: 21.4144<br><br>**Keywords**:<br>• 'Interdisciplinary System Eng.' (0.8566)<br>• 'Model-Based Systems Eng.' (0.8462) | **Topic**: Control Systems in Engineering<br>**Total Score**: 48.0307<br><br>• Lexical: 30.2824<br>• Title KNN: 25.1976<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• _None matched_ |
|
||||
| **Dentistry**<br>`"endodontic treatment procedures"` | **Topic**: Endodontics and Root Canal Treatments<br>**Total Score**: 85.0595<br><br>• Lexical: 33.2248<br>• Title KNN: 27.3373<br>• Desc KNN: 12.9073<br>• Key KNN: 24.7433<br><br>**Keywords**:<br>• 'Endodontic Treatment' (0.9897)<br>• 'Regenerative Endodontics' (0.9185) | **Topic**: Endodontics and Root Canal Treatments<br>**Total Score**: 85.0595<br><br>• Lexical: 33.2248<br>• Title KNN: 27.3373<br>• Desc KNN: 12.9073<br>• Key KNN: 24.7433<br><br>**Keywords**:<br>• 'Endodontic Treatment' (0.9897)<br>• 'Regenerative Endodontics' (0.9185) |
|
||||
| **Veterinary**<br>`"veterinary medicine diagnosis"` | **Topic**: Animal health and immunology<br>**Total Score**: 70.5398<br><br>• Lexical: 36.6445<br>• Title KNN: 24.4738<br>• Desc KNN: 0.0000<br>• Key KNN: 24.6649<br><br>**Keywords**:<br>• 'Veterinary Diagnosis' (0.9866) | **Topic**: Veterinary Medicine and Surgery<br>**Total Score**: 63.5579<br><br>• Lexical: 36.3745<br>• Title KNN: 27.1833<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• _None matched_ |
|
||||
+31375
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user