Compare commits
247
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3895acc057 | ||
|
|
843b555a11 | ||
|
|
2b23bb7027 | ||
|
|
e87c62f823 | ||
|
|
37497808e5 | ||
|
|
ddc1e9ae01 | ||
|
|
2d5928e667 | ||
|
|
f973537738 | ||
|
|
b524d75f22 | ||
|
|
d2dec7c6ee | ||
|
|
60d8ab805d | ||
|
|
ed7ab50b7a | ||
|
|
a0ef884ca3 | ||
|
|
54696df912 | ||
|
|
58530d40d6 | ||
|
|
e9d268ff9f | ||
|
|
6627651ae0 | ||
|
|
31253ff03b | ||
|
|
b983a01174 | ||
|
|
497575c2a6 | ||
|
|
01a37e2ea7 | ||
|
|
0915019315 | ||
|
|
605ffc1fff | ||
|
|
ba3421983f | ||
|
|
58177a5374 | ||
|
|
9f0e5a5085 | ||
|
|
60ff521061 | ||
|
|
44e950161f | ||
|
|
1b85ea7241 | ||
|
|
fe39ca2bf5 | ||
|
|
8601024d26 | ||
|
|
df56af976c | ||
|
|
57c88e1de5 | ||
|
|
e8153a9440 | ||
|
|
638b036ebf | ||
|
|
0fd028c6cb | ||
|
|
c2942906db | ||
|
|
de7e8f6328 | ||
|
|
1e8e82f1d9 | ||
|
|
13507c2ae8 | ||
|
|
1c535a872f | ||
|
|
4e66e581e1 | ||
|
|
2bacb8e0f9 | ||
|
|
464bacffdc | ||
|
|
baf5b17239 | ||
|
|
fa5e42a5eb | ||
|
|
304ce0f1ab | ||
|
|
92e32cd79e | ||
|
|
acad12bf27 | ||
|
|
3fa6f1dd6e | ||
|
|
f20be8aa63 | ||
|
|
0f3388d290 | ||
|
|
2e855dcf7b | ||
|
|
680d2924ee | ||
|
|
ace2a6bba3 | ||
|
|
6dfec1cfd4 | ||
|
|
4568669d53 | ||
|
|
e162ec1cac | ||
|
|
4027728626 | ||
|
|
1fc64c9c21 | ||
|
|
85610215b5 | ||
|
|
c12393a906 | ||
|
|
9cf6348f55 | ||
|
|
fafd5018bd | ||
|
|
f1ff7c9f66 | ||
|
|
b3af72a6ae | ||
|
|
7f02de2194 | ||
|
|
5f71a4b56c | ||
|
|
390e1049b8 | ||
|
|
34b01f2ae8 | ||
|
|
6360e86179 | ||
|
|
2427f4baa0 | ||
|
|
0e7bc41522 | ||
|
|
77c7eeef8b | ||
|
|
5b894d8927 | ||
|
|
b352e5288a | ||
|
|
7bbfe1761d | ||
|
|
09cb54109a | ||
|
|
bfa91a684e | ||
|
|
010e1c7f21 | ||
|
|
f5bf3ecbe4 | ||
|
|
d1802fa1f8 | ||
|
|
1980bde9ce | ||
|
|
4d0a6db3c3 | ||
|
|
aa473a6523 | ||
|
|
72a1dc27bc | ||
|
|
c5d62faf2f | ||
|
|
e5cf17620a | ||
|
|
ea3ddabac0 | ||
|
|
fa43ff8106 | ||
|
|
1c9ca6fa7d | ||
|
|
23b1be3b7b | ||
|
|
233a2d2fca | ||
|
|
b12e254cae | ||
|
|
40610c94c5 | ||
|
|
2b1aa8d9e3 | ||
|
|
db604feb37 | ||
|
|
cd0e98ec5f | ||
|
|
42685ae44f | ||
|
|
9be024bb13 | ||
|
|
87b7e207e3 | ||
|
|
8eaa9c2420 | ||
|
|
87b02ed0a4 | ||
|
|
a6d30dd897 | ||
|
|
134055b8b9 | ||
|
|
be72d28bda | ||
|
|
2bfb877e77 | ||
|
|
48e33e7fe5 | ||
|
|
f469594c17 | ||
|
|
3e115619a6 | ||
|
|
13b2fb3350 | ||
|
|
d26ddb8cb4 | ||
|
|
a8e582cf23 | ||
|
|
940c050cd7 | ||
|
|
e470b65b5a | ||
|
|
383c77134a | ||
|
|
bb941361a1 | ||
|
|
5d22b201e9 | ||
|
|
1c6dbb540f | ||
|
|
cf9a5df4e9 | ||
|
|
213edf8a5f | ||
|
|
c277fcfece | ||
|
|
8efbbf1f1a | ||
|
|
9ad6d5cd8c | ||
|
|
77540e4002 | ||
|
|
fd3ceb54aa | ||
|
|
7baeab92c2 | ||
|
|
0c526be983 | ||
|
|
53f5440d01 | ||
|
|
e86a19f800 | ||
|
|
61fd920a9f | ||
|
|
7eed7e6614 | ||
|
|
e34e1fe3d5 | ||
|
|
2418821691 | ||
|
|
058c92227a | ||
|
|
bf38147acc | ||
|
|
3f23845c89 | ||
|
|
52e70a5b24 | ||
|
|
d502431102 | ||
|
|
3533b994d0 | ||
|
|
5d22f4831a | ||
|
|
8130192a44 | ||
|
|
bda7aff447 | ||
|
|
82421c1040 | ||
|
|
0723bb5c5b | ||
|
|
e4dbe07436 | ||
|
|
19c6574945 | ||
|
|
0b750d27e7 | ||
|
|
398ea7b56c | ||
|
|
0176eea873 | ||
|
|
b0e8c86743 | ||
|
|
03a2954c72 | ||
|
|
b9d382c78a | ||
|
|
78a8e5d919 | ||
|
|
f9f6a58ad5 | ||
|
|
5cc110174a | ||
|
|
c3ec93fba1 | ||
|
|
169b825195 | ||
|
|
0a3bf72e14 | ||
|
|
eb94fc5942 | ||
|
|
e868c4a47e | ||
|
|
1cf80ae074 | ||
|
|
9d6656b6c4 | ||
|
|
c74d0b5b87 | ||
|
|
a69f014413 | ||
|
|
cabf819e94 | ||
|
|
c243088752 | ||
|
|
de4ba0591e | ||
|
|
eb89076070 | ||
|
|
1dd032a66c | ||
|
|
9f03c92bc1 | ||
|
|
86bced4940 | ||
|
|
4461b26270 | ||
|
|
19fd2ac86d | ||
|
|
e9ba874103 | ||
|
|
dfb1413b05 | ||
|
|
b5d03c84c4 | ||
|
|
40d8a5458d | ||
|
|
ef41c0ad96 | ||
|
|
a07fadc30e | ||
|
|
4bf351cf66 | ||
|
|
f55a37867c | ||
|
|
ae42bc46ed | ||
|
|
c38355c817 | ||
|
|
0c004f0cdf | ||
|
|
16c0b399c8 | ||
|
|
3867540a4c | ||
|
|
32cab01a8b | ||
|
|
2b606b8473 | ||
|
|
e0ac41da91 | ||
|
|
86bed62ac0 | ||
|
|
1eaf8f8c8f | ||
|
|
0c3db967b0 | ||
|
|
04eb0f0185 | ||
|
|
b2d965d604 | ||
|
|
c4e05a4376 | ||
|
|
92c4edfb4f | ||
|
|
79f2aa0263 | ||
|
|
5878edc4cd | ||
|
|
f4122263dd | ||
|
|
20faff13ec | ||
|
|
73315457a6 | ||
|
|
2703f46575 | ||
|
|
261f97eee0 | ||
|
|
f4b8d0884c | ||
|
|
1ddc5c42c5 | ||
|
|
47fb41105a | ||
|
|
4394ced772 | ||
|
|
15fc57da51 | ||
|
|
3c910fa0e4 | ||
|
|
c1cba4bd4c | ||
|
|
d43c406820 | ||
|
|
398df55f50 | ||
|
|
5888a71b36 | ||
|
|
c707064dfb | ||
|
|
8e56b59122 | ||
|
|
6fa5792e5e | ||
|
|
116492baca | ||
|
|
b1fee136ce | ||
|
|
95ce3a47fc | ||
|
|
6962b49771 | ||
|
|
4a17157643 | ||
|
|
503377e3bc | ||
|
|
171e87f575 | ||
|
|
b37718e792 | ||
|
|
eba78a080e | ||
|
|
204e419fed | ||
|
|
0d18ee49f3 | ||
|
|
65e428f4c2 | ||
|
|
195fd2d55b | ||
|
|
5d13b07c73 | ||
|
|
d8aca8ee3e | ||
|
|
495c7d34e5 | ||
|
|
39fdb23942 | ||
|
|
0d2c7f93be | ||
|
|
7c68a5cd71 | ||
|
|
b69fe4e15c | ||
|
|
873e4bbbec | ||
|
|
ba86d417b4 | ||
|
|
513489e790 | ||
|
|
185d2c3aa2 | ||
|
|
ca6c132bb9 | ||
|
|
f2cf83f63b | ||
|
|
512356e106 | ||
|
|
309fecf008 | ||
|
|
29c954227f | ||
|
|
1f70f9fe2d |
@@ -0,0 +1,337 @@
|
||||
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()
|
||||
@@ -0,0 +1,611 @@
|
||||
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()
|
||||
@@ -0,0 +1,943 @@
|
||||
{
|
||||
"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
@@ -0,0 +1,136 @@
|
||||
{
|
||||
"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
@@ -0,0 +1,198 @@
|
||||
{
|
||||
"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
@@ -0,0 +1,99 @@
|
||||
{
|
||||
"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
@@ -0,0 +1,146 @@
|
||||
{
|
||||
"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
@@ -0,0 +1,626 @@
|
||||
[
|
||||
{
|
||||
"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
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,984 @@
|
||||
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()
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,134 @@
|
||||
# Evaluation Results
|
||||
|
||||
## Executive summary
|
||||
|
||||
Gemma4-e4b was evaluated in two complementary ways:
|
||||
|
||||
1. **Semantic benchmark:** comparison with a consensus of four stronger LLMs on 50 research works.
|
||||
2. **Index validation audit:** structural validation of all 1,000 documents currently stored in `work-classifications`.
|
||||
|
||||
| Key result | Score |
|
||||
| --------------------------------------------- | -------------------: |
|
||||
| Consensus-compatible category | **43/50 (86.0%)** |
|
||||
| Agreement on unanimous reference items | **25/28 (89.3%)** |
|
||||
| Pasteur-quadrant compatibility | **41/43 (95.3%)** |
|
||||
| Valid documents in the 1,000-work index audit | **978/1000 (97.8%)** |
|
||||
|
||||
---
|
||||
|
||||
## 1. Semantic benchmark: 50 works
|
||||
|
||||
### Reference construction
|
||||
|
||||
The reference is based on four independent model outputs:
|
||||
|
||||
- GLM-5.1
|
||||
- Gemini 3.1 Pro
|
||||
- GPT-5.6-sol
|
||||
- Sonnet 5
|
||||
|
||||
| Reference agreement | Works |
|
||||
| --------------------- | ----: |
|
||||
| Unanimous `4:0` | 28 |
|
||||
| Majority `3:1` | 13 |
|
||||
| Split `2:2` | 7 |
|
||||
| Low consensus `2:1:1` | 2 |
|
||||
|
||||
This reference measures **compatibility with a multi-model consensus**, not objective ground truth or expert adjudication.
|
||||
|
||||
### Category performance
|
||||
|
||||
| Metric | Result |
|
||||
| ------------------------------------------------- | -----------------: |
|
||||
| Coverage | **50/50 (100.0%)** |
|
||||
| Overall consensus compatibility | **43/50 (86.0%)** |
|
||||
| Strict accuracy on resolved `4:0` and `3:1` items | **35/41 (85.4%)** |
|
||||
| Unanimous `4:0` accuracy | **25/28 (89.3%)** |
|
||||
| Majority `3:1` accuracy | **10/13 (76.9%)** |
|
||||
| Acceptance on split `2:2` items | **7/7 (100.0%)** |
|
||||
| Agreement-weighted compatibility | **86.4%** |
|
||||
|
||||
### Score performance
|
||||
|
||||
The score is evaluated against the score interval produced by reference models that selected the same accepted category.
|
||||
|
||||
| Metric | Result |
|
||||
| ------------------------------------------ | ----------------: |
|
||||
| Inside the exact reference interval | **20/36 (55.6%)** |
|
||||
| Inside or within 5 points of the interval | **28/36 (77.8%)** |
|
||||
| Inside or within 10 points of the interval | **34/36 (94.4%)** |
|
||||
| Mean distance to the accepted interval | **2.86 points** |
|
||||
| Median distance to the accepted interval | **0.00 points** |
|
||||
| Correct `null` score for `non_research` | **7/7 (100.0%)** |
|
||||
|
||||
### Technical and confidence checks
|
||||
|
||||
| Metric | Result |
|
||||
| -------------------------------------------- | ---------------: |
|
||||
| JSON/schema validity | **100.0%** |
|
||||
| Category-score-quadrant consistency | **94.0%** |
|
||||
| Confidence-cap compliance | **92.0%** |
|
||||
| `signals_used` validity | **100.0%** |
|
||||
| High-confidence incompatible classifications | **5/40 (12.5%)** |
|
||||
|
||||
### Main semantic disagreements
|
||||
|
||||
There are **7 category mismatches**:
|
||||
|
||||
| Work ID | Reference agreement | Accepted category | Gemma category |
|
||||
| ------------- | ------------------- | -------------------------- | -------------------------- |
|
||||
| `W4394954564` | `low_consensus` | `basic_research` | `experimental_development` |
|
||||
| `W3194249507` | `majority_3_1` | `applied_research` | `experimental_development` |
|
||||
| `W4411148338` | `unanimous_4_0` | `basic_research` | `applied_research` |
|
||||
| `W4399679289` | `unanimous_4_0` | `applied_research` | `basic_research` |
|
||||
| `W4410930081` | `unanimous_4_0` | `applied_research` | `basic_research` |
|
||||
| `W4400540671` | `majority_3_1` | `experimental_development` | `applied_research` |
|
||||
| `W2889224812` | `majority_3_1` | `applied_research` | `basic_research` |
|
||||
|
||||
---
|
||||
|
||||
## 2. Validation audit: 1,000 indexed works
|
||||
|
||||
The index contained exactly 1,000 documents, so the audit covered the full index rather than a partial sample.
|
||||
|
||||
| Status | Count | Rate |
|
||||
| ------------------ | ------: | --------: |
|
||||
| Valid | **978** | **97.8%** |
|
||||
| Invalid | **22** | **2.2%** |
|
||||
| Missing validation | **0** | **0.0%** |
|
||||
|
||||
### Validation errors
|
||||
|
||||
| Error | Count | Share of invalid works | Share of all works |
|
||||
| ----------------------------------------------- | ----: | ---------------------: | -----------------: |
|
||||
| `applied_research_score_outside_expected_range` | 15 | 68.2% | 1.5% |
|
||||
| `basic_research_quadrant_score_mismatch` | 6 | 27.3% | 0.6% |
|
||||
| `basic_research_score_outside_expected_range` | 1 | 4.5% | 0.1% |
|
||||
|
||||
### Validity by predicted category
|
||||
|
||||
| Category | Documents | Invalid | Valid rate |
|
||||
| -------------------------- | --------: | ------: | ---------: |
|
||||
| `basic_research` | 457 | 7 | 98.5% |
|
||||
| `applied_research` | 369 | 15 | 95.9% |
|
||||
| `experimental_development` | 141 | 0 | 100.0% |
|
||||
| `non_research` | 33 | 0 | 100.0% |
|
||||
|
||||
The dominant technical issue is an `applied_research` classification with a score above the allowed maximum of 70. This accounts for **15/22 invalid documents**.
|
||||
|
||||
---
|
||||
|
||||
## Reproducibility
|
||||
|
||||
- Semantic evaluator: `evaluate_candidate_against_consensus.py`
|
||||
- Index validation audit: `audit_index_validation_1000.py`
|
||||
- Semantic result: `evaluation/gemma_consensus_evaluation/gemma4-e4b_evaluation.json`
|
||||
- Index audit result: `evaluation/index_validation_audit_1000.json`
|
||||
- Blind benchmark input: `evaluation/golden_set_50_inputs_blind_v1.json`
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
python evaluate_candidate_against_consensus.py
|
||||
python audit_index_validation_1000.py
|
||||
```
|
||||
@@ -0,0 +1,606 @@
|
||||
{
|
||||
"batch_id": "golden_set_50_blind_v1",
|
||||
"n_items": 50,
|
||||
"items": [
|
||||
{
|
||||
"work_id": "W2951658790",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 85,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The paper describes the design, full prototype implementation on Raspberry Pi, and evaluation of a new security service for embedded systems, indicating experimental development of a practical tool."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W2792069854",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 60,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "venue", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Without an abstract, the title and venue (European Journal of Operational Research) suggest the development of applied mathematical models specifically targeted at urban evacuation planning."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W3157145095",
|
||||
"classification": {
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 10,
|
||||
"pasteur_quadrant": "pure_basic",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The work investigates the mathematical structure of the 3x + 1 problem (Collatz conjecture), aiming purely at fundamental knowledge without any specific practical application."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4211082810",
|
||||
"classification": {
|
||||
"primary_category": "non_research",
|
||||
"applied_orientation_score": null,
|
||||
"pasteur_quadrant": "not_applicable",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "work_type"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The item is titled 'References' and classified as a book chapter, indicating it is supporting material rather than original research."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W1970644787",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 65,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Although the abstract is missing, the title clearly states the development of nanocomposites specifically designed for a practical aim as an advanced MRI contrast agent."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4389566044",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 60,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The study formulates a mathematical program aimed specifically at finding optimal policies for controlling a pandemic outbreak and minimizing economic and humanitarian damage."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4387698137",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 65,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The work presents TOMOSCO, a topic modelling framework designed with the specific practical aim of identifying scientific collaborations and evaluating it on bibliometric data."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4393082582",
|
||||
"classification": {
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 40,
|
||||
"pasteur_quadrant": "use_inspired_basic",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The study conducts an original investigation into the microstructural development and fundamental properties of Al-doped ZnO during sintering, motivated by materials science applications."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4415655215",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 55,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The title suggests the development of a specific algorithmic approach for mining data from websites to fulfill the practical task of identifying organizational structures."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W2330632819",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 80,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The research synthesizes a stable ink and uses it to successfully print structures on glass substrates via ink-jet printing, demonstrating prototyping for printable electronics."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4415031709",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 75,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The authors implement a targeted fuzzing approach by extending the Rust compiler toolchain and evaluating its performance in generating vulnerability-triggering inputs."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W3022958510",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 60,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The paper develops an optimization model and an exact solution method aimed at the specific practical challenge of disaster road clearance and relief distribution."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W7138882770",
|
||||
"classification": {
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 35,
|
||||
"pasteur_quadrant": "use_inspired_basic",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "This is a bibliometric review mapping the field of AI for wildfire management, gaining fundamental knowledge about the structure of an applied research domain."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W7138856433",
|
||||
"classification": {
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 35,
|
||||
"pasteur_quadrant": "use_inspired_basic",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The study aims at a fundamental understanding of the underlying transformation mechanisms of nanoparticles during chemical vapor synthesis, motivated by materials optimization."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W2405896199",
|
||||
"classification": {
|
||||
"primary_category": "non_research",
|
||||
"applied_orientation_score": null,
|
||||
"pasteur_quadrant": "not_applicable",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "work_type"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The item is explicitly labeled as an editorial and introduction to a special issue, serving as supporting front-matter rather than original research."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4400944359",
|
||||
"classification": {
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 30,
|
||||
"pasteur_quadrant": "use_inspired_basic",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The paper performs a bibliometric analysis to understand the fundamental structure of data ecosystem research, establishing a research agenda for the field."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W2931917074",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 75,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The study follows design science research to develop and evaluate an Augmented Reality head-mounted display prototype for decision-making in Enterprise Architecture."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4403369135",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 60,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The authors apply machine learning to integrate data and classify potential startup founders among academics, aiming directly at improving the practical university scouting process."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4411506896",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 65,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Despite the lack of an abstract, the title signifies the creation of a specialized compiler designed to harden smart contracts against vulnerabilities, a practical software engineering aim."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W3153370821",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 85,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The paper introduces EVMPatch, features a proof-of-concept implementation that automatically rewrites/hardens smart contracts, and demonstrates its practicality via extensive real-world evaluation."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W3038557399",
|
||||
"classification": {
|
||||
"primary_category": "non_research",
|
||||
"applied_orientation_score": null,
|
||||
"pasteur_quadrant": "not_applicable",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "work_type"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The work is explicitly labeled as an erratum correcting a previously published paper, lacking independent research content."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4394954564",
|
||||
"classification": {
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 40,
|
||||
"pasteur_quadrant": "use_inspired_basic",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The study elucidates the fundamental mechanism of unidirectional hole transfer in specific heterostructures, which is motivated by improving photodetector applications."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4409545335",
|
||||
"classification": {
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 35,
|
||||
"pasteur_quadrant": "use_inspired_basic",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "This is a bibliometric synthesis outlining the status, structure, and future research gaps regarding artificial intelligence in smart city environments."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W7133313486",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 75,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The paper demonstrates the feasibility of using a calibrated high-speed camera setup for practical operando temperature measurements during the laser sintering process."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4394855570",
|
||||
"classification": {
|
||||
"primary_category": "non_research",
|
||||
"applied_orientation_score": null,
|
||||
"pasteur_quadrant": "not_applicable",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "work_type"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The item is a correction to a previously published article and therefore qualifies as non-research support material."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W7140663985",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 65,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The work presents a framework (Walma) leveraging machine learning to detect memory corruption in WebAssembly and evaluates its detection accuracy and performance overhead."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4226316500",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 80,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The authors introduce a practical smart contract compiler that automatically inserts security checks and validate its capability by preventing attack transactions in a large-scale real-world evaluation."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4289778746",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 55,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Without an abstract, the title points to the development of a model formulation directly targeting an industry-relevant optimization and packing problem."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W3194249507",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 60,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The paper aims to develop a framework for evaluating and comparing software fuzzers, which is an applied research endeavor targeting software testing practices."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4411446448",
|
||||
"classification": {
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 35,
|
||||
"pasteur_quadrant": "use_inspired_basic",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "This bibliometric analysis maps the academic landscape of virtual coaches to establish a comprehensive overview and propose a future research agenda."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W7140643534",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 75,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The study designs HammerWatch and implements it on commodity hardware to detect microarchitectural Rowhammer attacks, demonstrating an implemented, detection-oriented technical artifact."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4411449729",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 60,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The paper formulates a mixed integer linear model specifically aimed at optimizing practical logistical problems like premarshalling, block relocation, and stack loading."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W3207748302",
|
||||
"classification": {
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 35,
|
||||
"pasteur_quadrant": "use_inspired_basic",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The paper is a comprehensive bibliometric review of the data governance field intended to explore its evolution and point out future research strands."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4411148338",
|
||||
"classification": {
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 40,
|
||||
"pasteur_quadrant": "use_inspired_basic",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The authors perform an original experimental investigation into the structural evolution and deagglomeration dynamics of nanoparticles, driven by materials engineering motivations."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4399679289",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 50,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The work explores system-level effects (bitflips) of Non-Volatile Memories (NVMs) built on memristors, targeting practical concerns in computer hardware design."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4206963266",
|
||||
"classification": {
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 20,
|
||||
"pasteur_quadrant": "pure_basic",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The paper proposes a theoretical process model and quality criteria to advance the philosophy and cumulative nature of Design Science Research itself."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4243361268",
|
||||
"classification": {
|
||||
"primary_category": "non_research",
|
||||
"applied_orientation_score": null,
|
||||
"pasteur_quadrant": "not_applicable",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "work_type"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Appendices are explicitly listed as supporting materials and do not represent a standalone research contribution."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4384502134",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 55,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "This review summarizes recent methodological advances in the chemical vapor synthesis process with an explicit focus on materials development and practical process design."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4235102872",
|
||||
"classification": {
|
||||
"primary_category": "non_research",
|
||||
"applied_orientation_score": null,
|
||||
"pasteur_quadrant": "not_applicable",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "work_type"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The item is simply titled 'Discussion and Conclusion' and categorized as a book chapter, acting as structural supporting text rather than an independent research piece."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4410919853",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 60,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The title indicates the design of a practical diagnosis and intervention platform tailored for the mental health of knowledge workers."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4410623858",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 65,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The paper solves a specific practical problem (truck-drone delivery routing) by developing and validating a mixed-integer linear programming model for geometric trajectory planning."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4386126998",
|
||||
"classification": {
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 30,
|
||||
"pasteur_quadrant": "pure_basic",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The research is fundamentally focused on acquiring new knowledge regarding the local, crystal, and micro-structure of ultra-small SnO2 nanoparticles."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4411523072",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 65,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The paper presents Wemby, an approach to analyze WebAssembly-powered websites for memory corruption errors using fine-grained binary instrumentation and fuzzing."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W2903880611",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 75,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The authors introduce Scadman, implement it on a real-world water treatment testbed, and evaluate its efficacy in detecting cyber-physical attacks."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4410930081",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 55,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The title points to the development of design principles for stakeholder management in ports, indicating research focused on a specific practical and organizational aim."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4301212620",
|
||||
"classification": {
|
||||
"primary_category": "non_research",
|
||||
"applied_orientation_score": null,
|
||||
"pasteur_quadrant": "not_applicable",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "work_type"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The item is simply titled 'Introduction' within a book structure, which is considered non-research supporting material."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4365601033",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 68,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The paper introduces EF/CF, a transpilation-based high-performance fuzzer for smart contracts, applying advanced software engineering methods to improve vulnerability detection."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4400540671",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 75,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Researchers developed a smartphone application for device attestation and evaluated it in a qualitative study with A/B testing to understand its practical impact on user trust."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W2889224812",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 65,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The work presents novel exploitation techniques against Intel SGX to demonstrate cybersecurity vulnerabilities, which corresponds to practical applied software security research."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W3184661191",
|
||||
"classification": {
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 35,
|
||||
"pasteur_quadrant": "use_inspired_basic",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "This paper overviews a priority program's philosophy and scientific objectives involving the fundamental interplay between hardware security and emerging nano-electronics."
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
+255
@@ -0,0 +1,255 @@
|
||||
{
|
||||
"evaluation": {
|
||||
"candidate_model": "gemma4-e4b",
|
||||
"source_index": "work-classifications",
|
||||
"reference_models": ["glm-5.1", "gemini-3.1-pro", "gpt-5.6-sol", "sonnet5"],
|
||||
"works": 50,
|
||||
"interpretation": "Compatibility with a four-model consensus reference, not objective ground truth."
|
||||
},
|
||||
"reference_agreement": {
|
||||
"unanimous_4_0": 28,
|
||||
"majority_3_1": 13,
|
||||
"split_2_2": 7,
|
||||
"low_consensus": 2
|
||||
},
|
||||
"results": {
|
||||
"coverage": {
|
||||
"matched": 50,
|
||||
"total": 50,
|
||||
"rate": 1.0,
|
||||
"missing_ids": []
|
||||
},
|
||||
"category": {
|
||||
"overall_consensus_compatible": {
|
||||
"matched": 43,
|
||||
"total": 50,
|
||||
"rate": 0.86
|
||||
},
|
||||
"strict_resolved_items": {
|
||||
"matched": 35,
|
||||
"total": 41,
|
||||
"rate": 0.8536585365853658
|
||||
},
|
||||
"unanimous_items": {
|
||||
"matched": 25,
|
||||
"total": 28,
|
||||
"rate": 0.8928571428571429
|
||||
},
|
||||
"majority_3_1_items": {
|
||||
"matched": 10,
|
||||
"total": 13,
|
||||
"rate": 0.7692307692307693
|
||||
},
|
||||
"split_2_2_items": {
|
||||
"matched": 7,
|
||||
"total": 7,
|
||||
"rate": 1.0
|
||||
},
|
||||
"low_consensus_items": {
|
||||
"matched": 1,
|
||||
"total": 2,
|
||||
"rate": 0.5
|
||||
},
|
||||
"agreement_weighted_rate": 0.863905325443787
|
||||
},
|
||||
"score": {
|
||||
"numeric_items": 36,
|
||||
"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,
|
||||
"non_research_score_null": {
|
||||
"matched": 7,
|
||||
"total": 7,
|
||||
"rate": 1.0
|
||||
}
|
||||
},
|
||||
"quadrant": {
|
||||
"matched": 41,
|
||||
"total": 43,
|
||||
"rate": 0.9534883720930233
|
||||
},
|
||||
"technical": {
|
||||
"index_validation": {
|
||||
"valid": 47,
|
||||
"invalid": 3,
|
||||
"valid_rate": 0.94
|
||||
},
|
||||
"full_evaluator_validation": {
|
||||
"valid": 43,
|
||||
"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": {
|
||||
"by_level": {
|
||||
"high": {
|
||||
"count": 40,
|
||||
"compatible": 35,
|
||||
"compatibility_rate": 0.875
|
||||
},
|
||||
"medium": {
|
||||
"count": 8,
|
||||
"compatible": 6,
|
||||
"compatibility_rate": 0.75
|
||||
},
|
||||
"low": {
|
||||
"count": 2,
|
||||
"compatible": 2,
|
||||
"compatibility_rate": 1.0
|
||||
}
|
||||
},
|
||||
"high_confidence_incompatible": {
|
||||
"count": 5,
|
||||
"total": 40,
|
||||
"rate": 0.125
|
||||
}
|
||||
}
|
||||
},
|
||||
"issues": {
|
||||
"category_mismatches": [
|
||||
{
|
||||
"work_id": "W4394954564",
|
||||
"title": "Photogating through Unidirectional Charge Carrier Funneling in Two-Dimensional Transition Metal Dichalcogenide/Perovskite Heterostructure Photodetectors",
|
||||
"agreement_level": "low_consensus",
|
||||
"accepted_categories": ["basic_research"],
|
||||
"candidate_category": "experimental_development",
|
||||
"candidate_score": 92,
|
||||
"candidate_confidence": "high"
|
||||
},
|
||||
{
|
||||
"work_id": "W3194249507",
|
||||
"title": "My Fuzzer Beats Them All! Developing a Framework for Fair Evaluation and Comparison of Fuzzers",
|
||||
"agreement_level": "majority_3_1",
|
||||
"accepted_categories": ["applied_research"],
|
||||
"candidate_category": "experimental_development",
|
||||
"candidate_score": 85,
|
||||
"candidate_confidence": "medium"
|
||||
},
|
||||
{
|
||||
"work_id": "W4411148338",
|
||||
"title": "In situ probing of structure and deagglomeration of SnO2 colloids via small-angle X-ray scattering",
|
||||
"agreement_level": "unanimous_4_0",
|
||||
"accepted_categories": ["basic_research"],
|
||||
"candidate_category": "applied_research",
|
||||
"candidate_score": 65,
|
||||
"candidate_confidence": "high"
|
||||
},
|
||||
{
|
||||
"work_id": "W4399679289",
|
||||
"title": "NVM-Flip: Non-Volatile-Memory BitFlips on the System Level",
|
||||
"agreement_level": "unanimous_4_0",
|
||||
"accepted_categories": ["applied_research"],
|
||||
"candidate_category": "basic_research",
|
||||
"candidate_score": 30,
|
||||
"candidate_confidence": "high"
|
||||
},
|
||||
{
|
||||
"work_id": "W4410930081",
|
||||
"title": "Anchoring Collaboration: Design Principles for Stakeholder Management in Ports",
|
||||
"agreement_level": "unanimous_4_0",
|
||||
"accepted_categories": ["applied_research"],
|
||||
"candidate_category": "basic_research",
|
||||
"candidate_score": 35,
|
||||
"candidate_confidence": "medium"
|
||||
},
|
||||
{
|
||||
"work_id": "W4400540671",
|
||||
"title": "Building trust in remote attestation through transparency – a qualitative user study on observable attestation",
|
||||
"agreement_level": "majority_3_1",
|
||||
"accepted_categories": ["experimental_development"],
|
||||
"candidate_category": "applied_research",
|
||||
"candidate_score": 70,
|
||||
"candidate_confidence": "high"
|
||||
},
|
||||
{
|
||||
"work_id": "W2889224812",
|
||||
"title": "The guard's dilemma: efficient code-reuse attacks against intel SGX",
|
||||
"agreement_level": "majority_3_1",
|
||||
"accepted_categories": ["applied_research"],
|
||||
"candidate_category": "basic_research",
|
||||
"candidate_score": 35,
|
||||
"candidate_confidence": "high"
|
||||
}
|
||||
],
|
||||
"technical_issues": [
|
||||
{
|
||||
"work_id": "W4211082810",
|
||||
"title": "References",
|
||||
"errors": ["confidence_exceeds_context_cap"],
|
||||
"indexed_validation_valid": true,
|
||||
"indexed_validation_errors": []
|
||||
},
|
||||
{
|
||||
"work_id": "W1970644787",
|
||||
"title": "Blocked-micropores, surface functionalized, bio-compatible and silica-coated iron oxide nanocomposites as advanced MRI contrast agent",
|
||||
"errors": ["applied_research_score_outside_expected_range"],
|
||||
"indexed_validation_valid": false,
|
||||
"indexed_validation_errors": [
|
||||
"applied_research_score_outside_expected_range"
|
||||
]
|
||||
},
|
||||
{
|
||||
"work_id": "W4387698137",
|
||||
"title": "Exploiting Topic Modelling for the Identification of Untapped Scientific Collaborations",
|
||||
"errors": ["applied_research_score_outside_expected_range"],
|
||||
"indexed_validation_valid": false,
|
||||
"indexed_validation_errors": [
|
||||
"applied_research_score_outside_expected_range"
|
||||
]
|
||||
},
|
||||
{
|
||||
"work_id": "W2405896199",
|
||||
"title": "Editorial: Introduction to the Special Issue on Information Modeling and Ontologies.",
|
||||
"errors": ["confidence_exceeds_context_cap"],
|
||||
"indexed_validation_valid": true,
|
||||
"indexed_validation_errors": []
|
||||
},
|
||||
{
|
||||
"work_id": "W4403369135",
|
||||
"title": "Discovering potential founders within academic institutions",
|
||||
"errors": ["applied_research_score_outside_expected_range"],
|
||||
"indexed_validation_valid": false,
|
||||
"indexed_validation_errors": [
|
||||
"applied_research_score_outside_expected_range"
|
||||
]
|
||||
},
|
||||
{
|
||||
"work_id": "W4394855570",
|
||||
"title": "Correction to: Making Sense of Projects—Developing Project Portfolio Management Capabilities",
|
||||
"errors": ["confidence_exceeds_context_cap"],
|
||||
"indexed_validation_valid": true,
|
||||
"indexed_validation_errors": []
|
||||
},
|
||||
{
|
||||
"work_id": "W4243361268",
|
||||
"title": "Appendices",
|
||||
"errors": ["confidence_exceeds_context_cap"],
|
||||
"indexed_validation_valid": true,
|
||||
"indexed_validation_errors": []
|
||||
}
|
||||
]
|
||||
},
|
||||
"assessment": {
|
||||
"overall": "good",
|
||||
"summary": "43/50 classifications are compatible with the four-model consensus reference.",
|
||||
"category_mismatch_count": 7,
|
||||
"technical_issue_count": 7
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,613 @@
|
||||
{
|
||||
"batch_id": "golden_set_50_blind_v1",
|
||||
"n_items": 50,
|
||||
"items": [
|
||||
{
|
||||
"work_id": "W2951658790",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 65,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Presents a design and prototype implementation of a control-flow attestation system directed at a specific practical aim in IoT security."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W2792069854",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 60,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "venue", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Optimization model for urban evacuation planning targets a specific practical aim; no abstract limits confidence."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W3157145095",
|
||||
"classification": {
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 5,
|
||||
"pasteur_quadrant": "pure_basic",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Investigates the mathematical structure of the Collatz conjecture to acquire fundamental knowledge without any application in view."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4211082810",
|
||||
"classification": {
|
||||
"primary_category": "non_research",
|
||||
"applied_orientation_score": null,
|
||||
"pasteur_quadrant": "not_applicable",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "work_type"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "This item is a references section of a book chapter, which is non-research supporting material."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W1970644787",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 65,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "venue", "topics", "funders"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Developing nanocomposites as an advanced MRI contrast agent indicates a specific practical aim; no abstract limits confidence."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4389566044",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 65,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics", "funders"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Mathematical programming model targeting the specific practical aim of minimizing economic and humanitarian damage during a pandemic."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4387698137",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 65,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Develops and evaluates a topic modelling framework directed towards the specific practical aim of identifying scientific collaborators."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4393082582",
|
||||
"classification": {
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 35,
|
||||
"pasteur_quadrant": "use_inspired_basic",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics", "funders"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Investigates fundamental microstructural development mechanisms in sintered ZnO, motivated by eventual material design applications."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4415655215",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 60,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Hybrid data mining approach targeting the specific practical aim of extracting organizational structure; no abstract limits confidence."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W2330632819",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 75,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics", "funders"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Synthesis and successful ink-jet printing of silicon nanoparticles for printable electronics constitutes prototyping and process development."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4415031709",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 65,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "work_type", "topics", "funders"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Develops and implements a targeted fuzzing approach for the specific practical aim of detecting vulnerabilities in unsafe Rust code."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W3022958510",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 65,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics", "funders"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Develops an exact solution method and mathematical model for the practical aim of disaster road clearance and relief distribution."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W7138882770",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 55,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Bibliometric review of an application-oriented research field (AI for wildfire management); classifies based on reviewed body of work."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W7138856433",
|
||||
"classification": {
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 35,
|
||||
"pasteur_quadrant": "use_inspired_basic",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Investigates fundamental (trans-)formation mechanisms of nanocrystals, motivated by the practical aim of optimizing particle characteristics."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W2405896199",
|
||||
"classification": {
|
||||
"primary_category": "non_research",
|
||||
"applied_orientation_score": null,
|
||||
"pasteur_quadrant": "not_applicable",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "work_type"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Editorial introducing a special issue, classified as non-research supporting material."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4400944359",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 55,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Bibliometric study reviewing data ecosystem research, an applied field; classification follows the reviewed body of work."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W2931917074",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 75,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Designs, develops, and evaluates an AR head-mounted display prototype for enterprise architecture decision-making."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4403369135",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 65,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics", "funders"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Develops a machine learning approach for the specific practical aim of identifying potential startup founders in academia."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4411506896",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 65,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "A compiler for smart contract hardening targets a specific practical aim; lack of abstract limits confidence."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W3153370821",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 80,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Implements and evaluates a framework for automatically patching faulty smart contracts, demonstrating practical feasibility and deployment readiness."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W3038557399",
|
||||
"classification": {
|
||||
"primary_category": "non_research",
|
||||
"applied_orientation_score": null,
|
||||
"pasteur_quadrant": "not_applicable",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "work_type"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Erratum correcting a previous publication, classified as non-research."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4394954564",
|
||||
"classification": {
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 40,
|
||||
"pasteur_quadrant": "use_inspired_basic",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics", "funders"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Investigates fundamental charge carrier transfer mechanisms in photodetectors, motivated by improving device performance."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4409545335",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 55,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics", "funders"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Bibliometric analysis of AI in smart cities; classifies based on the applied orientation of the reviewed body of work."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W7133313486",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 65,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics", "funders"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Develops and demonstrates a measurement technique for laser sintering, directed towards the practical aim of operando temperature monitoring."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4394855570",
|
||||
"classification": {
|
||||
"primary_category": "non_research",
|
||||
"applied_orientation_score": null,
|
||||
"pasteur_quadrant": "not_applicable",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "work_type"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Correction notice to a previously published article, classified as non-research."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W7140663985",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 65,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Develops and evaluates a machine learning framework for the practical aim of detecting memory corruption in WebAssembly."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4226316500",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 65,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Proposes and evaluates a practical compiler that automatically hardens smart contracts against vulnerabilities, fulfilling a specific practical aim."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4289778746",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 65,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "venue", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Extended model for strip packing targeting industry-relevant aspects; classified as applied research. No abstract limits confidence."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W3194249507",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 60,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Develops a framework for fuzzer evaluation, serving a specific practical aim in software testing. No abstract limits confidence."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4411446448",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 55,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics", "funders"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Bibliometric review of virtual coach research, an applied field; classifies based on the orientation of the reviewed literature."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W7140643534",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 65,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Proposes and implements a remote attestation protocol for detecting microarchitectural attacks, directed at a specific practical security aim."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4411449729",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 65,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics", "funders"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Proposes a mixed integer linear model for specific practical optimization problems in storage and container terminals."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W3207748302",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 55,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics", "funders"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Bibliometric review of data governance research, an applied field; classifies based on the orientation of the reviewed literature."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4411148338",
|
||||
"classification": {
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 40,
|
||||
"pasteur_quadrant": "use_inspired_basic",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics", "funders"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Investigates fundamental deagglomeration dynamics and structural mechanisms, motivated by the practical aim of improving microstructural quality."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4399679289",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 60,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "abstract", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Focuses on non-volatile memory bitflips at the system level, a practical security topic; abstract lacks specific aim, limiting confidence."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4206963266",
|
||||
"classification": {
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 35,
|
||||
"pasteur_quadrant": "use_inspired_basic",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Proposes a theoretical process model for scientific progress in DSR, aiming to establish foundational knowledge motivated by practical impact."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4243361268",
|
||||
"classification": {
|
||||
"primary_category": "non_research",
|
||||
"applied_orientation_score": null,
|
||||
"pasteur_quadrant": "not_applicable",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "work_type"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Item is an appendix of a book chapter, which is non-research supporting material."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4384502134",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 55,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Review of methodological advances for chemical vapor synthesis directed towards the practical aim of materials and process development."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4235102872",
|
||||
"classification": {
|
||||
"primary_category": "non_research",
|
||||
"applied_orientation_score": null,
|
||||
"pasteur_quadrant": "not_applicable",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "work_type"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Item is a discussion and conclusion section of a book, classified as non-research supporting material."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4410919853",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 65,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "venue", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Designing a diagnosis and intervention platform targets a specific practical aim; no abstract limits confidence."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4410623858",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 65,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics", "funders"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Develops a mixed-integer linear program for drone trajectory planning directed at the practical aim of last-mile delivery."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4386126998",
|
||||
"classification": {
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 35,
|
||||
"pasteur_quadrant": "use_inspired_basic",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics", "funders"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Investigates fundamental local, crystal, and micro-structure of SnO2 nanoparticles, motivated by their relevance to applied properties like catalysis."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4411523072",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 65,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Develops and evaluates a fuzzer for the specific practical aim of detecting memory corruption vulnerabilities in WebAssembly."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W2903880611",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 75,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Implements and evaluates an anomaly detection system prototype on a real-world testbed, constituting experimental development."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4410930081",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 60,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Designing stakeholder management principles for ports targets a specific practical aim; lack of abstract limits confidence."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4301212620",
|
||||
"classification": {
|
||||
"primary_category": "non_research",
|
||||
"applied_orientation_score": null,
|
||||
"pasteur_quadrant": "not_applicable",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "work_type"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Item is an introduction section of a book, classified as non-research supporting material."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4365601033",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 65,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": [
|
||||
"title",
|
||||
"abstract",
|
||||
"venue",
|
||||
"work_type",
|
||||
"topics",
|
||||
"funders"
|
||||
],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Introduces a high-performance fuzzer for smart contracts directed towards the practical aim of vulnerability and exploit detection."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4400540671",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 65,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics", "funders"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Conducts a user study to improve trust in IoT remote attestation, directed towards the practical aim of usable security."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W2889224812",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 60,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Develops novel exploitation techniques against Intel SGX to demonstrate practical security vulnerabilities under weak adversarial assumptions."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W3184661191",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 55,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics", "funders"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Overview of a research program directed at the practical aim of establishing system security based on nano-electronics."
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
+1120
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,606 @@
|
||||
{
|
||||
"batch_id": "golden_set_50_blind_v1",
|
||||
"n_items": 50,
|
||||
"items": [
|
||||
{
|
||||
"work_id": "W2951658790",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 90,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Designs, implements, and evaluates a Raspberry Pi prototype for runtime control-flow attestation against concrete attacks."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W2792069854",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 62,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Targets the practical problem of safe, resilient urban evacuation through bi-objective planning, but no prototype or deployment evidence is provided."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W3157145095",
|
||||
"classification": {
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 5,
|
||||
"pasteur_quadrant": "pure_basic",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Investigates the mathematical structure of the Collatz problem to advance foundational knowledge, with no practical use in view."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4211082810",
|
||||
"classification": {
|
||||
"primary_category": "non_research",
|
||||
"applied_orientation_score": null,
|
||||
"pasteur_quadrant": "not_applicable",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "work_type", "venue"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "A references section is supporting material rather than an independent research contribution."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W1970644787",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 66,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Develops biocompatible iron oxide nanocomposites for the specific practical objective of improved MRI contrast, without clear trial or deployment evidence."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4389566044",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 67,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Builds an optimization model to select pandemic-control measures while limiting economic and mortality harms, addressing a specific policy-planning objective."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4387698137",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 68,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Develops and experimentally evaluates a topic-modeling framework for recommending scientific collaborators, serving a defined organizational decision-support need."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4393082582",
|
||||
"classification": {
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 40,
|
||||
"pasteur_quadrant": "use_inspired_basic",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Primarily investigates mechanisms by which electric current alters ZnO microstructure and composition, motivated by improved sintering control rather than an immediate product."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4415655215",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 60,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Proposes a hybrid data-mining approach for extracting university organizational structures from websites, a specific information-management task; implementation evidence is unavailable."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W2330632819",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 86,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Produces stable silicon nanoparticle ink and demonstrates ink-jet printed structures and films, constituting process and product prototyping for printable electronics."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4415031709",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 89,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Implements selective instrumentation by extending the Rust compiler toolchain and validates improved vulnerability-fuzzing performance, yielding a working security-testing capability."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W3022958510",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 68,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Develops and computationally tests an optimization model and exact algorithm for disaster road clearance and relief distribution, addressing a concrete emergency-logistics problem."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W7138882770",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 56,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Reviews an application-oriented body of AI research focused on wildfire detection, prediction, monitoring, and management, and proposes a practical research agenda."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W7138856433",
|
||||
"classification": {
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 42,
|
||||
"pasteur_quadrant": "use_inspired_basic",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Seeks mechanistic understanding of tin oxide nanoparticle formation through operando diffraction and simulation, motivated by eventual control of application-relevant material properties."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W2405896199",
|
||||
"classification": {
|
||||
"primary_category": "non_research",
|
||||
"applied_orientation_score": null,
|
||||
"pasteur_quadrant": "not_applicable",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "work_type", "venue"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "An editorial introducing a special issue is supporting scholarly material, not an independent research investigation."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4400944359",
|
||||
"classification": {
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 35,
|
||||
"pasteur_quadrant": "use_inspired_basic",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Bibliometrically maps data-ecosystem scholarship and develops a research agenda; the reviewed field's practical orientation is mixed and no specific intervention is central."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W2931917074",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 84,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Develops and evaluates a HoloLens augmented-reality prototype to support enterprise-architecture decisions, directly testing a working artifact for practical use."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4403369135",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 67,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Creates and evaluates machine-learning models to support university scouting of potential founders, pursuing a specific technology-transfer decision objective without deployment."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4411506896",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 78,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "The work centers on a language-independent compiler for hardening smart contracts, indicating a working security artifact, though implementation details are unavailable."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W3153370821",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 94,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Implements and extensively evaluates an automated Ethereum contract-patching framework on 14,000 real contracts, demonstrating a practical working system."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W3038557399",
|
||||
"classification": {
|
||||
"primary_category": "non_research",
|
||||
"applied_orientation_score": null,
|
||||
"pasteur_quadrant": "not_applicable",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "abstract", "work_type"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "An erratum corrects a prior publication and is not an independent research contribution."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4394954564",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 64,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Investigates charge-transfer mechanisms while fabricating photodetectors with improved responsivity, dark current, and detectivity, serving the practical objective of better photosensing devices."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4409545335",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 54,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Reviews an application-oriented literature on AI solutions for urban mobility, waste, energy, and security, with practical implications for smart-city development."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W7133313486",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 82,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Develops and demonstrates a high-speed near-infrared imaging setup for operando temperature measurement during laser sintering, establishing a working measurement capability."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4394855570",
|
||||
"classification": {
|
||||
"primary_category": "non_research",
|
||||
"applied_orientation_score": null,
|
||||
"pasteur_quadrant": "not_applicable",
|
||||
"confidence": "low",
|
||||
"signals_used": ["title"],
|
||||
"insufficient_context": true,
|
||||
"classification_reason": "The title explicitly identifies a correction, which is supporting material; no abstract or other confirming content is available."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W7140663985",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 87,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Presents and evaluates a deployable framework for WebAssembly memory attestation across real vulnerable applications and multiple execution backends."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4226316500",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 91,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Builds a smart-contract compiler that automatically inserts hardening checks and validates it on 10,000 real contracts and verified attacks."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4289778746",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 64,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Formulates an optimization model for an industry-relevant irregular strip-packing problem, a concrete manufacturing objective, without evidence of implementation or deployment."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W3194249507",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 62,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Develops an evaluation framework for fair comparison of fuzzers, addressing a specific software-testing need; the available fields do not establish a working implementation."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4411446448",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 54,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Maps an application-oriented literature on virtual coaching for health, education, fitness, and professional development, emphasizing future development and implementation."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W7140643534",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 89,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Implements and evaluates HammerWatch, a hardware-backed remote-attestation protocol for detecting Rowhammer behavior on commodity systems."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4411449729",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 64,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Develops and computationally evaluates a compact optimization model for practical stacking, relocation, loading, and terminal-logistics problems."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W3207748302",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 52,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Reviews a practically oriented research field concerned with governing organizational data and identifies future work for companies and public institutions."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4411148338",
|
||||
"classification": {
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 43,
|
||||
"pasteur_quadrant": "use_inspired_basic",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Primarily investigates nanoscale deagglomeration dynamics and structure, motivated by eventual control of colloidal processing and functional-material quality."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4399679289",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 55,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "abstract", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Examines system-level bit-flip behavior and security implications of non-volatile memory for a concrete computing problem, but the abstract lacks method and implementation details."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4206963266",
|
||||
"classification": {
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 35,
|
||||
"pasteur_quadrant": "use_inspired_basic",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Develops a conceptual model and quality criteria for cumulative design-science knowledge, primarily advancing research methodology while seeking eventual practical impact."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4243361268",
|
||||
"classification": {
|
||||
"primary_category": "non_research",
|
||||
"applied_orientation_score": null,
|
||||
"pasteur_quadrant": "not_applicable",
|
||||
"confidence": "low",
|
||||
"signals_used": ["title"],
|
||||
"insufficient_context": true,
|
||||
"classification_reason": "An appendices section is supporting material rather than independent research; no substantive context is provided."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4384502134",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 60,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Reviews methods for controlling, characterizing, and designing chemical-vapor nanoparticle synthesis processes and materials, an application-oriented body of work."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4235102872",
|
||||
"classification": {
|
||||
"primary_category": "non_research",
|
||||
"applied_orientation_score": null,
|
||||
"pasteur_quadrant": "not_applicable",
|
||||
"confidence": "low",
|
||||
"signals_used": ["title", "work_type"],
|
||||
"insufficient_context": true,
|
||||
"classification_reason": "A standalone discussion-and-conclusion chapter is supporting material, and no abstract clarifies any independent research contribution."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4410919853",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 66,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Targets the practical design of a diagnosis and intervention platform for knowledge-worker stress, but available evidence does not confirm a prototype or implementation."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4410623858",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 68,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Develops and computationally tests a trajectory-optimization model for collision-free, energy-aware drone delivery with moving launch and recovery vehicles."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4386126998",
|
||||
"classification": {
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 34,
|
||||
"pasteur_quadrant": "use_inspired_basic",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Investigates fundamental size, surface, interface, and defect structures in ultrasmall tin dioxide nanocrystals, with applications mentioned mainly as motivation."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4411523072",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 93,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Implements and deploys a WebAssembly fuzzing and instrumentation system on real websites, finding memory-corruption bugs and substantially improving speed and coverage."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W2903880611",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 91,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Implements and evaluates Scadman on a real-world water-treatment testbed as a working anomaly-detection system for cyber-physical controllers."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4410930081",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 56,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Derives design principles for the specific practical problem of stakeholder management in ports; no abstract establishes implementation or field deployment."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4301212620",
|
||||
"classification": {
|
||||
"primary_category": "non_research",
|
||||
"applied_orientation_score": null,
|
||||
"pasteur_quadrant": "not_applicable",
|
||||
"confidence": "low",
|
||||
"signals_used": ["title", "work_type", "venue"],
|
||||
"insufficient_context": true,
|
||||
"classification_reason": "An introduction chapter is supporting material, and the available metadata provides no evidence of an independent research investigation."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4365601033",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 94,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Builds and comprehensively evaluates a high-performance smart-contract fuzzer that generates working exploits and outperforms existing tools."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4400540671",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 78,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Develops a user-facing remote-attestation application and evaluates explanatory interface variants with participants, constituting a tested intervention prototype."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W2889224812",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 64,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Develops practical exploitation techniques for Intel SGX under realistic adversarial assumptions, addressing a concrete security problem without evidence of a deployable product."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W3184661191",
|
||||
"classification": {
|
||||
"primary_category": "non_research",
|
||||
"applied_orientation_score": null,
|
||||
"pasteur_quadrant": "not_applicable",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Provides an overview of a research priority program and its planned projects rather than reporting an original investigation or development activity."
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
+1227
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,606 @@
|
||||
{
|
||||
"batch_id": "golden_set_50_blind_v1",
|
||||
"n_items": 50,
|
||||
"items": [
|
||||
{
|
||||
"work_id": "W2951658790",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 85,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Full prototype (C-FLAT) implemented on real ARM TrustZone hardware, evaluated against real control-flow attacks; an engineered security artifact, not fundamental inquiry."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W2792069854",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 55,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Optimization model for urban evacuation planning in an OR journal; targets a specific practical aim without a described prototype, pilot, or deployment."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W3157145095",
|
||||
"classification": {
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 5,
|
||||
"pasteur_quadrant": "pure_basic",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Purely theoretical investigation of structural properties of the Collatz conjecture; no application or use is mentioned or implied."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4211082810",
|
||||
"classification": {
|
||||
"primary_category": "non_research",
|
||||
"applied_orientation_score": null,
|
||||
"pasteur_quadrant": "not_applicable",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "work_type"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Bibliographic reference list of a book chapter; supporting material, not original research."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W1970644787",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 58,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Synthesis and surface functionalization of nanocomposites explicitly designed as an MRI contrast agent; specific practical biomedical aim, no abstract available."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4389566044",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 55,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Mathematical program to select pandemic-control measures minimizing economic and health damage, illustrated with case study; practical policy aim, no deployed system."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4387698137",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 75,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "TOMOSCO framework implemented and experimentally evaluated (over 90% accuracy) for identifying research collaborations; a working tool tested on real data."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4393082582",
|
||||
"classification": {
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 35,
|
||||
"pasteur_quadrant": "use_inspired_basic",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Investigates mechanisms (electromigration, Joule heating) underlying microstructure formation during flash sintering; fundamental understanding motivated by materials processing."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4415655215",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 55,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "topics", "work_type"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Method for mining organizational structure from university websites; practical data-extraction aim inferred from title and topics, no abstract or venue given."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W2330632819",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 80,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Synthesizes silicon nanoparticle ink and demonstrates ink-jet printed structures on glass substrates for printable electronics; a produced and tested artifact."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4415031709",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 78,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Implements a modified Rust compiler toolchain for targeted fuzzing of unsafe code and evaluates vulnerability detection; a built and tested tool."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W3022958510",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 55,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Formal MIP model and branch-and-bound method for disaster road clearance and relief delivery; practical optimization aim, computational study only, no deployment."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W7138882770",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 55,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Bibliometric review characterizing an application-oriented field (AI for wildfire detection/management); reviewed body is technology- and deployment-focused."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W7138856433",
|
||||
"classification": {
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 35,
|
||||
"pasteur_quadrant": "use_inspired_basic",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "In situ/operando XRD combined with simulation to uncover nanoparticle formation mechanisms; fundamental mechanistic aim motivated by optimizing future particle properties."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W2405896199",
|
||||
"classification": {
|
||||
"primary_category": "non_research",
|
||||
"applied_orientation_score": null,
|
||||
"pasteur_quadrant": "not_applicable",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "work_type"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Editorial introducing a special issue; not original research."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4400944359",
|
||||
"classification": {
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 30,
|
||||
"pasteur_quadrant": "use_inspired_basic",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Bibliometric study mapping the data-ecosystem research field and proposing a future research agenda for scholars; knowledge-mapping aim, not itself a practical tool."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W2931917074",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 75,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Design-science approach used to build and evaluate an AR head-mounted-display prototype for enterprise-architecture decision making; a developed and tested artifact."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4403369135",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 55,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Data-driven machine-learning approach (random forest) to identify potential startup founders among academic staff, supporting a real technology-transfer scouting process."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4411506896",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 75,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Title describes a hardening 'compiler' for smart contracts, indicating a built tool; no abstract available, so evidence rests on title, venue and topics."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W3153370821",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 85,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "EVMPatch framework with proof-of-concept implementation, evaluated on 14,000 real-world smart contracts and a developer study; a deployed, tested patching tool."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W3038557399",
|
||||
"classification": {
|
||||
"primary_category": "non_research",
|
||||
"applied_orientation_score": null,
|
||||
"pasteur_quadrant": "not_applicable",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "work_type"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Erratum correcting a prior publication; supporting material, not original research."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4394954564",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 71,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Fabricates MoS2/perovskite heterostructure photodetectors and reports measured device performance (responsivity, detectivity); device engineering alongside mechanistic discussion."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4409545335",
|
||||
"classification": {
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 30,
|
||||
"pasteur_quadrant": "use_inspired_basic",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Bibliometric analysis mapping AI-in-smart-cities research and proposing a future research agenda; field-mapping aim motivated by urban application challenges."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W7133313486",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 72,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Develops and demonstrates a new operando high-speed NIR imaging technique for temperature measurement during laser sintering; new measurement process/instrumentation."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4394855570",
|
||||
"classification": {
|
||||
"primary_category": "non_research",
|
||||
"applied_orientation_score": null,
|
||||
"pasteur_quadrant": "not_applicable",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "work_type"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Correction notice to a previously published article; supporting material, not original research."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W7140663985",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 80,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Walma framework implemented and evaluated on real CVE-affected WebAssembly applications across multiple backends; a built and benchmarked detection tool."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4226316500",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 82,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "HCC compiler implemented and evaluated at scale on 10k real-world smart contracts, outperforming prior hardening tools; a deployed, tested artifact."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4289778746",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 55,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Extended optimization model formulation for an industry-relevant strip-packing problem in an OR journal; practical aim, no described prototype or deployment."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W3194249507",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 73,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Title indicates development of an evaluation framework/tool for fuzzers; software-engineering venue and topics support a built-artifact orientation, no abstract available."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4411446448",
|
||||
"classification": {
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 30,
|
||||
"pasteur_quadrant": "use_inspired_basic",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Bibliometric analysis of 540 articles mapping the virtual-coaching research field and proposing a future research agenda; field-mapping, not itself an intervention."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W7140643534",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 78,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "HammerWatch protocol implemented on commodity hardware and evaluated on 20,000 simulated access patterns for Rowhammer detection; a built and tested system."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4411449729",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 55,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Novel MILP model formulation applicable to stacking/relocation logistics problems, examined via computational study; practical optimization aim, no deployment described."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W3207748302",
|
||||
"classification": {
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 30,
|
||||
"pasteur_quadrant": "use_inspired_basic",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Bibliometric review tracing 16 years of data-governance research to provide a field blueprint and future research paths; field-mapping aim."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4411148338",
|
||||
"classification": {
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 35,
|
||||
"pasteur_quadrant": "use_inspired_basic",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "In situ SAXS study of deagglomeration dynamics and mechanisms in SnO2 colloids; fundamental structural understanding motivated by improving functional-material applications."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4399679289",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 55,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "abstract", "topics", "work_type"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Discusses non-volatile memory (memristor) bit-flip behavior at the system level; available abstract is largely introductory background, limiting certainty of orientation."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4206963266",
|
||||
"classification": {
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 35,
|
||||
"pasteur_quadrant": "use_inspired_basic",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Proposes a theoretical process model and quality criteria for cumulative progress in design science research; meta-scientific aim motivated by improving field practice."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4243361268",
|
||||
"classification": {
|
||||
"primary_category": "non_research",
|
||||
"applied_orientation_score": null,
|
||||
"pasteur_quadrant": "not_applicable",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "work_type"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Appendices of a book chapter; supporting material, not original research."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4384502134",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 71,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Review of methodological advances for controlling and characterizing the chemical-vapor-synthesis process and materials development; reviewed body is process/technique-development oriented."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4235102872",
|
||||
"classification": {
|
||||
"primary_category": "non_research",
|
||||
"applied_orientation_score": null,
|
||||
"pasteur_quadrant": "not_applicable",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "venue", "work_type"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Discussion and Conclusion chapter of a larger work; a structural, supporting section rather than a standalone original research contribution."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4410919853",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 73,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Title indicates designing a diagnosis-and-intervention platform for knowledge-worker stress; a system-building aim inferred from topics and venue, no abstract available."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4410623858",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 55,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Mixed-integer linear program for collision-free drone trajectory planning with moving vehicles, validated via computational study; practical aim, no field deployment."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4386126998",
|
||||
"classification": {
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 35,
|
||||
"pasteur_quadrant": "use_inspired_basic",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Detailed structural characterization of very small SnO2 nanocrystals using multiple techniques; fundamental understanding of defects, motivated by relevance to electronics/catalysis applications."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4411523072",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 85,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Wemby tool built and applied across 37,797 real domains, uncovering actual memory-corruption bugs (e.g., on Zoom); a deployed, benchmarked security tool."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W2903880611",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 80,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Scadman anomaly detection system implemented and evaluated on a real-world water-treatment testbed for industrial control systems; a built and tested artifact."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4410930081",
|
||||
"classification": {
|
||||
"primary_category": "applied_research",
|
||||
"applied_orientation_score": 50,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Title indicates design principles for stakeholder management in ports; a practical organizational aim inferred from topics, no abstract or working artifact described."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4301212620",
|
||||
"classification": {
|
||||
"primary_category": "non_research",
|
||||
"applied_orientation_score": null,
|
||||
"pasteur_quadrant": "not_applicable",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "venue", "work_type"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Introductory chapter of a book in a security/privacy lecture series; supporting material rather than an original research contribution."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4365601033",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 85,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "EF/CF fuzzer implemented (bytecode-to-C++ transpilation) and evaluated at scale, automatically generating exploit transaction sequences; a built and benchmarked tool."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W4400540671",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 71,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Application built to let users observe IoT remote attestation, evaluated via qualitative study and A/B testing with 35 participants; prototype plus piloting."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W2889224812",
|
||||
"classification": {
|
||||
"primary_category": "experimental_development",
|
||||
"applied_orientation_score": 75,
|
||||
"pasteur_quadrant": "pure_applied",
|
||||
"confidence": "high",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Novel exploitation techniques against Intel SGX developed and demonstrated under weak adversarial assumptions on standard SDK enclaves; a working attack technique."
|
||||
}
|
||||
},
|
||||
{
|
||||
"work_id": "W3184661191",
|
||||
"classification": {
|
||||
"primary_category": "basic_research",
|
||||
"applied_orientation_score": 35,
|
||||
"pasteur_quadrant": "use_inspired_basic",
|
||||
"confidence": "medium",
|
||||
"signals_used": ["title", "abstract", "venue", "work_type", "topics"],
|
||||
"insufficient_context": false,
|
||||
"classification_reason": "Overview of a research program spanning fundamental nano-electronics phenomena and their security implications/applications; describes both threats and use-motivated approaches."
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
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
@@ -0,0 +1,243 @@
|
||||
{
|
||||
"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
@@ -0,0 +1,337 @@
|
||||
{
|
||||
"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": []
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
{
|
||||
"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
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,410 @@
|
||||
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,291 @@
|
||||
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. Assign an `applied_orientation_score` from **0 (pure basic) to 100 (pure
|
||||
experimental development)**. Rough anchors: 0–30 basic, 31–70 applied,
|
||||
71–100 experimental development. `use_inspired_basic` typically 25–45.
|
||||
5. Set `confidence` — **capped by the signals available** (see next section).
|
||||
|
||||
### 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 systems,
|
||||
device, protocol, pilot, or benchmark aimed at a working artifact is usually
|
||||
applied or experimental development, not basic.
|
||||
- **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`.
|
||||
- Clinical trial, field trial, prototype, scale-up, deployment →
|
||||
`experimental_development`.
|
||||
- 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`.
|
||||
`non_research` → score `null`, `pasteur_quadrant: not_applicable`.
|
||||
`confidence` must respect the caps above. `signals_used` lists only fields that
|
||||
actually informed the decision.
|
||||
|
||||
---
|
||||
|
||||
## 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."
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
openai>=1.0.0
|
||||
requests>=2.31.0
|
||||
@@ -0,0 +1,757 @@
|
||||
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()
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
{
|
||||
"run_id": "20260713_212701_723948",
|
||||
"started_at": "2026-07-13T21:27:01Z",
|
||||
"finished_at": "2026-07-13T21:30:12Z",
|
||||
"duration_seconds": 191.047,
|
||||
"status": "completed",
|
||||
"error": null,
|
||||
"parameters": {
|
||||
"limit": 186,
|
||||
"workers": 20,
|
||||
"model": "gemma4-e4b",
|
||||
"prompt_version": "frascati_v1"
|
||||
},
|
||||
"classification": {
|
||||
"llm_completed": 186,
|
||||
"valid": 176,
|
||||
"invalid": 10,
|
||||
"categories": {
|
||||
"basic_research": 105,
|
||||
"applied_research": 69,
|
||||
"experimental_development": 8,
|
||||
"non_research": 4
|
||||
},
|
||||
"validation_errors": {
|
||||
"applied_research_score_outside_expected_range": 8,
|
||||
"basic_research_quadrant_score_mismatch": 2
|
||||
}
|
||||
},
|
||||
"indexing": {
|
||||
"newly_indexed": 186,
|
||||
"recovered_from_ready": 0
|
||||
},
|
||||
"token_usage": {
|
||||
"prompt_tokens": 603490,
|
||||
"cached_prompt_tokens": 541728,
|
||||
"uncached_prompt_tokens": 61762,
|
||||
"completion_tokens": 158741,
|
||||
"real_total_usage": 220503
|
||||
},
|
||||
"throughput_indexed_per_hour": 3504.9,
|
||||
"sqlite_counts_after_run": {
|
||||
"indexed": 388,
|
||||
"pending": 6
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
[
|
||||
{
|
||||
"id": "https://openalex.org/A5089242868",
|
||||
"display_name": "Lucas Davi"
|
||||
},
|
||||
{
|
||||
"id": "https://openalex.org/A5093075883",
|
||||
"display_name": "Arman Arzani"
|
||||
},
|
||||
{
|
||||
"id": "https://openalex.org/A5075352419",
|
||||
"display_name": "Markus Winterer"
|
||||
},
|
||||
{
|
||||
"id": "https://openalex.org/A5048213587",
|
||||
"display_name": "Frederik Ahlemann"
|
||||
},
|
||||
{
|
||||
"id": "https://openalex.org/A5088184531",
|
||||
"display_name": "Alf Kimms"
|
||||
},
|
||||
{
|
||||
"id": "https://openalex.org/A5075663980",
|
||||
"display_name": "Ursula Neumann"
|
||||
},
|
||||
{
|
||||
"id": "https://openalex.org/A5035144962",
|
||||
"display_name": "Christine Arentz"
|
||||
},
|
||||
{
|
||||
"id": "https://openalex.org/A5058038339",
|
||||
"display_name": "Pascal Dreher"
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,382 @@
|
||||
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()
|
||||
@@ -0,0 +1,50 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -38,6 +38,7 @@ def add_entry(index: str, entry: dict):
|
||||
"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)
|
||||
@@ -47,6 +48,13 @@ def add_entry(index: str, entry: dict):
|
||||
|
||||
return created_id
|
||||
|
||||
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="")
|
||||
@@ -103,4 +111,18 @@ def delete_all_entries(index: str):
|
||||
"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)
|
||||
@@ -23,6 +23,17 @@ SYSTEM_PROMPT_NAMES = ("""
|
||||
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,
|
||||
@@ -62,3 +73,14 @@ def extract_names(text: str) -> list[str]:
|
||||
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 []
|
||||
|
||||
@@ -16,10 +16,12 @@ def sync_single_news(news_id, max_retries=3):
|
||||
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
|
||||
@@ -32,6 +34,25 @@ def sync_single_news(news_id, max_retries=3):
|
||||
print(f"Error: {news_id} - {error}")
|
||||
return False
|
||||
|
||||
def update_keywords_single(postproc_entry, max_retries=3):
|
||||
doc_id = postproc_entry["_id"]
|
||||
news_id = postproc_entry["_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)
|
||||
es_client.update_entry("aktuell_postproc", doc_id, {"keywords": keywords})
|
||||
return True
|
||||
except Exception as error:
|
||||
attempt += 1
|
||||
print(f"Warning updating keywords for news_id {news_id} (Attempt {attempt}/{max_retries})")
|
||||
if attempt < max_retries:
|
||||
time.sleep(1)
|
||||
else:
|
||||
print(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.")
|
||||
|
||||
@@ -47,6 +68,18 @@ def main():
|
||||
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",
|
||||
@@ -60,11 +93,22 @@ def main():
|
||||
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).",
|
||||
)
|
||||
|
||||
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")
|
||||
print(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"])
|
||||
@@ -96,23 +140,58 @@ def main():
|
||||
end_time = time.time()
|
||||
print(f"Sync DONE: {succeeded} entries synced.")
|
||||
print(f"Time taken: {end_time - start_time} seconds.")
|
||||
|
||||
|
||||
if args.update_keywords:
|
||||
start_time = time.time()
|
||||
postproc_entries = es_client.get_all_entries("aktuell_postproc", fields=["news_id", "keywords"])
|
||||
|
||||
pending = [entry for entry in postproc_entries if not entry["_source"].get("keywords")]
|
||||
print(f"Number of entries without keywords: {len(pending)}")
|
||||
|
||||
if args.limit is not None:
|
||||
pending = pending[:args.limit]
|
||||
|
||||
total = len(pending)
|
||||
print(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) for entry in pending]
|
||||
for future in as_completed(futures):
|
||||
was_successful = future.result()
|
||||
with progress_lock:
|
||||
processed += 1
|
||||
if was_successful:
|
||||
succeeded += 1
|
||||
print(f"Update keywords: {processed} / {total}")
|
||||
|
||||
end_time = time.time()
|
||||
print(f"Update keywords DONE: {succeeded} entries updated.")
|
||||
print(f"Time taken: {end_time - start_time} seconds.")
|
||||
|
||||
if args.stats:
|
||||
aktuell_entries = es_client.get_all_entries("aktuell", fields=["_id"])
|
||||
print(f"Total entries in 'aktuell': {len(aktuell_entries)}")
|
||||
|
||||
postproc_entries = es_client.get_all_entries("aktuell_postproc", fields=["_id", "news_id", "relevant", "authors"])
|
||||
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
|
||||
|
||||
print(f"Total entries in 'aktuell_postproc': {total_entries}")
|
||||
print(f"Relevant entries: {relevant_count}")
|
||||
print(f"Irrelevant entries: {irrelevant_count}")
|
||||
print(f"Entries with extracted names: {news_with_extracted_names}")
|
||||
print(f"Entries without extracted names: {news_without_extracted_names}")
|
||||
print(f"Entries with keywords: {news_with_keywords}")
|
||||
print(f"Entries without keywords: {news_without_keywords}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
File diff suppressed because one or more lines are too long
+2
-1
@@ -18,7 +18,8 @@ RUN pip install --root-user-action=ignore --no-cache-dir --disable-pip-version-c
|
||||
"websockets==12.0" \
|
||||
"partial-json-parser==0.2.1.1.post7" \
|
||||
"sqlmodel~=0.0.33" \
|
||||
"argon2-cffi~=25.1.0"
|
||||
"argon2-cffi~=25.1.0" \
|
||||
"pypdf==6.14.2"
|
||||
|
||||
COPY [ "src/main", "/home" ]
|
||||
COPY [ "src/data", "/data" ]
|
||||
|
||||
@@ -15,3 +15,34 @@ This mounts the source directory into the container and enables uvicorn hot-relo
|
||||
## Testing
|
||||
|
||||
Run tests: `./gradlew :service:test`
|
||||
|
||||
## Scripts
|
||||
|
||||
### index_org_patents.py
|
||||
|
||||
Builds the `org_patents` Elasticsearch index for a given institution: fetches its
|
||||
OpenAlex authors, searches EPO/USPTO for patents matched via institution assignee
|
||||
and/or inventor name, and reindexes. Each patent is tagged with a `match_type`
|
||||
(`institution`, `name`, or `both`, the latter being highest confidence). For common
|
||||
inventor names, a name match is only kept if the assignee is the institution itself or
|
||||
the person, to avoid pulling in unrelated patents via a shared name.
|
||||
|
||||
```bash
|
||||
python scripts/index_org_patents.py --institution-id <OpenAlex-ID>
|
||||
```
|
||||
|
||||
**Example — University of Duisburg-Essen:**
|
||||
|
||||
```bash
|
||||
python scripts/index_org_patents.py --institution-id I62318514
|
||||
```
|
||||
|
||||
The OpenAlex institution ID appears in the app URL, e.g. `/institution/I62318514/overview`.
|
||||
|
||||
**Runtime:** ~30–40 minutes for large institutions (author count is the main driver).
|
||||
Re-running is safe — existing documents for the institution are deleted (via search +
|
||||
`_bulk` delete-by-id, not `_delete_by_query`, which the patent-cluster API key rejects)
|
||||
before reindexing, so stale documents don't linger.
|
||||
|
||||
**Note:** This script is intended to be integrated into an Admin Panel in a later sprint,
|
||||
so that organisation admins can trigger the indexing as a background job via the UI.
|
||||
|
||||
@@ -10,6 +10,7 @@ dependencies = [
|
||||
"fastapi~=0.115.0",
|
||||
"httpx~=0.27.0",
|
||||
"openai~=2.41.0",
|
||||
"pypdf==6.14.2",
|
||||
"pydantic~=2.7.1",
|
||||
"pydantic-settings~=2.2.1",
|
||||
"pyjwt~=2.8.0",
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Index org_patents for an institution."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import logging
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
current_dir = Path(__file__).resolve().parent
|
||||
sys.path.insert(0, str(current_dir.parent / "src" / "main"))
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv(dotenv_path=current_dir.parent / "src" / "main" / "inse" / ".env")
|
||||
|
||||
from inse.patents.org.logic import index_org_patents_for_institution
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
parser = argparse.ArgumentParser(description="Index org_patents for an institution.")
|
||||
parser.add_argument(
|
||||
"--institution-id",
|
||||
required=True,
|
||||
help="OpenAlex institution ID, e.g. I62318514",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
count = await index_org_patents_for_institution(args.institution_id)
|
||||
logger.info("Finished indexing %d patents for institution %s", count, args.institution_id)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,12 @@
|
||||
# Define here the models for your scraped items
|
||||
#
|
||||
# See documentation in:
|
||||
# https://docs.scrapy.org/en/latest/topics/items.html
|
||||
|
||||
import scrapy
|
||||
|
||||
|
||||
class AktuellItem(scrapy.Item):
|
||||
# define the fields for your item here like:
|
||||
# name = scrapy.Field()
|
||||
pass
|
||||
@@ -0,0 +1,103 @@
|
||||
# Define here the models for your spider middleware
|
||||
#
|
||||
# See documentation in:
|
||||
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html
|
||||
|
||||
from scrapy import signals
|
||||
|
||||
# useful for handling different item types with a single interface
|
||||
from itemadapter import is_item, ItemAdapter
|
||||
|
||||
|
||||
class AktuellSpiderMiddleware:
|
||||
# Not all methods need to be defined. If a method is not defined,
|
||||
# scrapy acts as if the spider middleware does not modify the
|
||||
# passed objects.
|
||||
|
||||
@classmethod
|
||||
def from_crawler(cls, crawler):
|
||||
# This method is used by Scrapy to create your spiders.
|
||||
s = cls()
|
||||
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
|
||||
return s
|
||||
|
||||
def process_spider_input(self, response, spider):
|
||||
# Called for each response that goes through the spider
|
||||
# middleware and into the spider.
|
||||
|
||||
# Should return None or raise an exception.
|
||||
return None
|
||||
|
||||
def process_spider_output(self, response, result, spider):
|
||||
# Called with the results returned from the Spider, after
|
||||
# it has processed the response.
|
||||
|
||||
# Must return an iterable of Request, or item objects.
|
||||
for i in result:
|
||||
yield i
|
||||
|
||||
def process_spider_exception(self, response, exception, spider):
|
||||
# Called when a spider or process_spider_input() method
|
||||
# (from other spider middleware) raises an exception.
|
||||
|
||||
# Should return either None or an iterable of Request or item objects.
|
||||
pass
|
||||
|
||||
def process_start_requests(self, start_requests, spider):
|
||||
# Called with the start requests of the spider, and works
|
||||
# similarly to the process_spider_output() method, except
|
||||
# that it doesn’t have a response associated.
|
||||
|
||||
# Must return only requests (not items).
|
||||
for r in start_requests:
|
||||
yield r
|
||||
|
||||
def spider_opened(self, spider):
|
||||
spider.logger.info("Spider opened: %s" % spider.name)
|
||||
|
||||
|
||||
class AktuellDownloaderMiddleware:
|
||||
# Not all methods need to be defined. If a method is not defined,
|
||||
# scrapy acts as if the downloader middleware does not modify the
|
||||
# passed objects.
|
||||
|
||||
@classmethod
|
||||
def from_crawler(cls, crawler):
|
||||
# This method is used by Scrapy to create your spiders.
|
||||
s = cls()
|
||||
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
|
||||
return s
|
||||
|
||||
def process_request(self, request, spider):
|
||||
# Called for each request that goes through the downloader
|
||||
# middleware.
|
||||
|
||||
# Must either:
|
||||
# - return None: continue processing this request
|
||||
# - or return a Response object
|
||||
# - or return a Request object
|
||||
# - or raise IgnoreRequest: process_exception() methods of
|
||||
# installed downloader middleware will be called
|
||||
return None
|
||||
|
||||
def process_response(self, request, response, spider):
|
||||
# Called with the response returned from the downloader.
|
||||
|
||||
# Must either;
|
||||
# - return a Response object
|
||||
# - return a Request object
|
||||
# - or raise IgnoreRequest
|
||||
return response
|
||||
|
||||
def process_exception(self, request, exception, spider):
|
||||
# Called when a download handler or a process_request()
|
||||
# (from other downloader middleware) raises an exception.
|
||||
|
||||
# Must either:
|
||||
# - return None: continue processing this exception
|
||||
# - return a Response object: stops process_exception() chain
|
||||
# - return a Request object: stops process_exception() chain
|
||||
pass
|
||||
|
||||
def spider_opened(self, spider):
|
||||
spider.logger.info("Spider opened: %s" % spider.name)
|
||||
@@ -0,0 +1,13 @@
|
||||
# Define your item pipelines here
|
||||
#
|
||||
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
|
||||
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
|
||||
|
||||
|
||||
# useful for handling different item types with a single interface
|
||||
from itemadapter import ItemAdapter
|
||||
|
||||
|
||||
class AktuellPipeline:
|
||||
def process_item(self, item, spider):
|
||||
return item
|
||||
@@ -0,0 +1,93 @@
|
||||
# Scrapy settings for aktuell project
|
||||
#
|
||||
# For simplicity, this file contains only settings considered important or
|
||||
# commonly used. You can find more settings consulting the documentation:
|
||||
#
|
||||
# https://docs.scrapy.org/en/latest/topics/settings.html
|
||||
# https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
|
||||
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html
|
||||
|
||||
BOT_NAME = "aktuell"
|
||||
|
||||
SPIDER_MODULES = ["aktuell.spiders"]
|
||||
NEWSPIDER_MODULE = "aktuell.spiders"
|
||||
|
||||
|
||||
# Crawl responsibly by identifying yourself (and your website) on the user-agent
|
||||
#USER_AGENT = "aktuell (+http://www.yourdomain.com)"
|
||||
|
||||
# Obey robots.txt rules
|
||||
ROBOTSTXT_OBEY = True
|
||||
|
||||
# Configure maximum concurrent requests performed by Scrapy (default: 16)
|
||||
#CONCURRENT_REQUESTS = 32
|
||||
|
||||
# Configure a delay for requests for the same website (default: 0)
|
||||
# See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay
|
||||
# See also autothrottle settings and docs
|
||||
DOWNLOAD_DELAY = 5
|
||||
# The download delay setting will honor only one of:
|
||||
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
|
||||
#CONCURRENT_REQUESTS_PER_IP = 16
|
||||
|
||||
# Disable cookies (enabled by default)
|
||||
#COOKIES_ENABLED = False
|
||||
|
||||
# Disable Telnet Console (enabled by default)
|
||||
#TELNETCONSOLE_ENABLED = False
|
||||
|
||||
# Override the default request headers:
|
||||
#DEFAULT_REQUEST_HEADERS = {
|
||||
# "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
|
||||
# "Accept-Language": "en",
|
||||
#}
|
||||
|
||||
# Enable or disable spider middlewares
|
||||
# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
|
||||
#SPIDER_MIDDLEWARES = {
|
||||
# "aktuell.middlewares.AktuellSpiderMiddleware": 543,
|
||||
#}
|
||||
|
||||
# Enable or disable downloader middlewares
|
||||
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
|
||||
#DOWNLOADER_MIDDLEWARES = {
|
||||
# "aktuell.middlewares.AktuellDownloaderMiddleware": 543,
|
||||
#}
|
||||
|
||||
# Enable or disable extensions
|
||||
# See https://docs.scrapy.org/en/latest/topics/extensions.html
|
||||
#EXTENSIONS = {
|
||||
# "scrapy.extensions.telnet.TelnetConsole": None,
|
||||
#}
|
||||
|
||||
# Configure item pipelines
|
||||
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
|
||||
#ITEM_PIPELINES = {
|
||||
# "aktuell.pipelines.AktuellPipeline": 300,
|
||||
#}
|
||||
|
||||
# Enable and configure the AutoThrottle extension (disabled by default)
|
||||
# See https://docs.scrapy.org/en/latest/topics/autothrottle.html
|
||||
#AUTOTHROTTLE_ENABLED = True
|
||||
# The initial download delay
|
||||
#AUTOTHROTTLE_START_DELAY = 5
|
||||
# The maximum download delay to be set in case of high latencies
|
||||
#AUTOTHROTTLE_MAX_DELAY = 60
|
||||
# The average number of requests Scrapy should be sending in parallel to
|
||||
# each remote server
|
||||
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
|
||||
# Enable showing throttling stats for every response received:
|
||||
#AUTOTHROTTLE_DEBUG = False
|
||||
|
||||
# Enable and configure HTTP caching (disabled by default)
|
||||
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
|
||||
#HTTPCACHE_ENABLED = True
|
||||
#HTTPCACHE_EXPIRATION_SECS = 0
|
||||
#HTTPCACHE_DIR = "httpcache"
|
||||
#HTTPCACHE_IGNORE_HTTP_CODES = []
|
||||
#HTTPCACHE_STORAGE = "scrapy.extensions.httpcache.FilesystemCacheStorage"
|
||||
|
||||
# Set settings whose default value is deprecated to a future-proof value
|
||||
REQUEST_FINGERPRINTER_IMPLEMENTATION = "2.7"
|
||||
TWISTED_REACTOR = "twisted.internet.asyncioreactor.AsyncioSelectorReactor"
|
||||
FEED_EXPORT_ENCODING = "utf-8"
|
||||
@@ -0,0 +1,4 @@
|
||||
# This package will contain the spiders of your Scrapy project
|
||||
#
|
||||
# Please refer to the documentation for information on how to create and manage
|
||||
# your spiders.
|
||||
@@ -0,0 +1,45 @@
|
||||
import scrapy
|
||||
|
||||
class LinksCrawler(scrapy.Spider):
|
||||
name = "aktuell-links"
|
||||
|
||||
current = 1
|
||||
first = True
|
||||
max_num = 100
|
||||
|
||||
def start_requests(self):
|
||||
url = 'https://www.uni-due.de/aktuell/?page=1&list_max=250'
|
||||
yield scrapy.Request(url=url, callback=self.parse)
|
||||
|
||||
def parse(self, response):
|
||||
if self.first:
|
||||
self.first = False
|
||||
max_num_text = response.selector.xpath('//div[contains(@id,"content__old__main")]/form/div/div/div[1]/div[1]/text()[2]').get()
|
||||
self.max_num = int(max_num_text[4:])
|
||||
|
||||
rows = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[contains(@class,"row")]').getall()
|
||||
|
||||
for i in range(len(rows)):
|
||||
cols = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[contains(@class,"row")][' + str(i + 1) + ']/div/div/div/div').getall()
|
||||
|
||||
for o in range(len(cols)):
|
||||
link = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[contains(@class,"row")][' + str(i + 1) + ']/div/div/div/div[' + str(o + 1) + ']/div/a/@href').get()
|
||||
tags_num = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[contains(@class,"row")][' + str(i + 1) + ']/div/div/div/div[' + str(o + 1) + ']/div/ul/li').getall()
|
||||
tags = []
|
||||
|
||||
for p in range(len(tags_num)):
|
||||
tag = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[contains(@class,"row")][' + str(i + 1) + ']/div/div/div/div[' + str(o + 1) + ']/div/ul/li[' + str(p + 1) + ']/a/text()').get()
|
||||
|
||||
if tag != None:
|
||||
tags.append(tag)
|
||||
|
||||
yield {
|
||||
"link": "https://www.uni-due.de" + link,
|
||||
"tags": tags
|
||||
}
|
||||
|
||||
self.current = self.current + 1
|
||||
if self.current <= self.max_num:
|
||||
next_page = "https://www.uni-due.de/aktuell/?page=" + str(self.current) + "&list_max=250"
|
||||
|
||||
yield response.follow(next_page, callback=self.parse)
|
||||
@@ -0,0 +1,153 @@
|
||||
import scrapy
|
||||
import json
|
||||
from scrapy.linkextractors import LinkExtractor
|
||||
import os
|
||||
|
||||
class MetaDataCrawler(scrapy.Spider):
|
||||
name = "aktuell-metadata"
|
||||
|
||||
link_extractor = LinkExtractor()
|
||||
log = {}
|
||||
|
||||
def start_requests(self):
|
||||
with open("out/links.json", "r") as file:
|
||||
urls = json.load(file)
|
||||
print("file loaded")
|
||||
|
||||
print("start logging")
|
||||
# start log
|
||||
if os.path.exists("out/aktuell_crawler_log.json"):
|
||||
# if json exists -> read in file
|
||||
with open('out/aktuell_crawler_log.json', 'r') as jsonfile:
|
||||
self.log = json.load(jsonfile)
|
||||
else:
|
||||
# if json doesn't exist -> #1 create json -> #2 write in initial structure -> #3 read it in
|
||||
# 1
|
||||
open("out/aktuell_crawler_log.json", "x")
|
||||
# 2
|
||||
initial_dict = {"done": []}
|
||||
with open("out/aktuell_crawler_log.json", "w") as jsonfile:
|
||||
jsonfile.write(json.dumps(initial_dict))
|
||||
# 3
|
||||
with open('out/aktuell_crawler_log.json', 'r') as jsonfile:
|
||||
self.log = json.load(jsonfile)
|
||||
|
||||
for url in urls:
|
||||
if url["link"] not in self.log["done"]:
|
||||
yield scrapy.Request(url=url["link"], callback=self.parse)
|
||||
self.log["done"].append(url["link"])
|
||||
with open("out/aktuell_crawler_log.json", "w") as jsonfile:
|
||||
jsonfile.write(json.dumps(self.log))
|
||||
else:
|
||||
continue
|
||||
|
||||
def parse(self, response):
|
||||
subtitle = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/h2[contains(@class, "card-subtitle")]/text()').get()
|
||||
maintitle = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/h2[contains(@class, "card-title")]/text()').get()
|
||||
|
||||
tags_num = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/ul/li').getall()
|
||||
tags = []
|
||||
|
||||
for p in range(len(tags_num)):
|
||||
tag = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/ul/li[' + str(p + 1) + ']/a/text()').get()
|
||||
|
||||
if tag != None:
|
||||
tags.append(tag)
|
||||
|
||||
author = ""
|
||||
date = ""
|
||||
if response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/div[contains(@class, "card-text")]/ul/li[1]/text()').get() == "von ":
|
||||
author = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/div[contains(@class, "card-text")]/ul/li[1]/b/text()').get()
|
||||
date = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/div[contains(@class, "card-text")]/ul/li[2]/text()').get()
|
||||
else:
|
||||
date = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/div[contains(@class, "card-text")]/ul/li[1]/text()').get()
|
||||
|
||||
content_num = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/div[contains(@class, "card-text")]/p').getall()
|
||||
main_content = ""
|
||||
intro_content = ""
|
||||
further_content = ""
|
||||
is_further = False
|
||||
redaktion = ""
|
||||
|
||||
for p in range(len(content_num)):
|
||||
if p == 0:
|
||||
current_content = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/div[contains(@class, "card-text")]/p[' + str(p + 1) + ']/strong').get()
|
||||
check_h2 = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/div[contains(@class, "card-text")]/h2').get()
|
||||
|
||||
if current_content is not None and check_h2 is None:
|
||||
current_contents = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/div[contains(@class, "card-text")]/p[' + str(p + 1) + ']//text()').getall()
|
||||
current_content = "".join(current_contents)
|
||||
intro_content = current_content + " "
|
||||
else:
|
||||
current_contents = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/div[contains(@class, "card-text")]/p[' + str(p + 1) + ']//text()').getall()
|
||||
current_content = "".join(current_contents)
|
||||
main_content = main_content + current_content + " "
|
||||
elif is_further:
|
||||
current_contents = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/div[contains(@class, "card-text")]/p[' + str(p + 1) + ']//text()').getall()
|
||||
current_content = "".join(current_contents)
|
||||
|
||||
if current_content.startswith("Redaktion: "):
|
||||
redaktion = current_content + " "
|
||||
else:
|
||||
further_content = further_content + current_content + " "
|
||||
else:
|
||||
current_content = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/div[contains(@class, "card-text")]/p[' + str(p + 1) + ']/strong/text()').get()
|
||||
|
||||
if current_content is not None and current_content.startswith("Weitere Informationen"):
|
||||
is_further = True
|
||||
current_contents = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/div[contains(@class, "card-text")]/p[' + str(p + 1) + ']//text()').getall()
|
||||
current_content = "".join(current_contents)
|
||||
|
||||
if current_content.startswith("Redaktion: "):
|
||||
redaktion = current_content + " "
|
||||
else:
|
||||
further_content = further_content + current_content + " "
|
||||
else:
|
||||
current_contents = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/div[contains(@class, "card-text")]/p[' + str(p + 1) + ']//text()').getall()
|
||||
current_content = "".join(current_contents)
|
||||
|
||||
if current_content.startswith("Redaktion: "):
|
||||
current_contents = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/div[contains(@class, "card-text")]/p[' + str(p + 1) + ']//text()').getall()
|
||||
current_content = "".join(current_contents)
|
||||
redaktion = current_content + " "
|
||||
else:
|
||||
main_content = main_content + current_content + " "
|
||||
|
||||
full_content = intro_content + " " + main_content
|
||||
main_content = main_content.replace("\n", " ").replace("\r", " ").replace("\t", " ").replace("\b", " ")
|
||||
intro_content = intro_content.replace("\n", " ").replace("\r", " ").replace("\t", " ").replace("\b", " ")
|
||||
further_content = further_content.replace("\n", " ").replace("\r", " ").replace("\t", " ").replace("\b", " ")
|
||||
|
||||
links = self.link_extractor.extract_links(response)
|
||||
filtered_links = []
|
||||
for link in links:
|
||||
l = {"url": link.url, "text": link.text.replace("\n", " ").replace("\r", " ").replace("\t", " ").replace("\b", " ")}
|
||||
filtered_links.append(l)
|
||||
|
||||
date_year = ""
|
||||
if not date == "":
|
||||
date_year = date[-4:]
|
||||
|
||||
date_full = ""
|
||||
if not date == "":
|
||||
d1 = date[:2]
|
||||
d2 = date[3:5]
|
||||
d3 = date[6:]
|
||||
date_full = d3 + d2 + d1
|
||||
|
||||
yield {
|
||||
"subtitle": subtitle,
|
||||
"maintitle": maintitle,
|
||||
"tags": tags,
|
||||
"author": author,
|
||||
"date": date,
|
||||
"date_year": date_year,
|
||||
"date_full": date_full,
|
||||
"intro_content": intro_content,
|
||||
"main_content": main_content,
|
||||
"further_content": further_content,
|
||||
"redaktion": redaktion,
|
||||
"full_content": full_content,
|
||||
"links": filtered_links,
|
||||
"url": response.request.url
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
# Automatically created by: scrapy startproject
|
||||
#
|
||||
# For more information about the [deploy] section see:
|
||||
# https://scrapyd.readthedocs.io/en/latest/deploy.html
|
||||
|
||||
[settings]
|
||||
default = aktuell.settings
|
||||
|
||||
[deploy]
|
||||
#url = http://localhost:6800/
|
||||
project = aktuell
|
||||
@@ -0,0 +1,153 @@
|
||||
from selenium import webdriver
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.common.exceptions import NoSuchElementException
|
||||
from selenium.webdriver.firefox.options import Options
|
||||
from random import randint
|
||||
import time
|
||||
import sys
|
||||
from elasticsearch import Elasticsearch
|
||||
|
||||
es = Elasticsearch()
|
||||
|
||||
index_name = "aktuell-test" #test indices to make sure everything works before uploading to the real index, ps. you lack rights to push to the real index, please contact the admin if you want to push to the real index
|
||||
|
||||
def getLinks(link, driver):
|
||||
print("--- Getting Links")
|
||||
driver.get(link)
|
||||
|
||||
time.sleep(randint(5, 7))
|
||||
|
||||
links = []
|
||||
dates = []
|
||||
dates_year = []
|
||||
dates_num = []
|
||||
counter = 1
|
||||
|
||||
while True:
|
||||
# increment counter (counter starts one lower than needed, so the increment is at the start instead of at the end)
|
||||
counter += 1
|
||||
|
||||
# check if end is reached
|
||||
try:
|
||||
elem = driver.find_element(By.XPATH, "/html/body/main/div[2]/div/div/div/div/div/div/div[" + str(counter) + "]/b").text
|
||||
if elem == "Zurück zum Gesamtüberblick":
|
||||
break
|
||||
except NoSuchElementException as nsee:
|
||||
break
|
||||
|
||||
# get date
|
||||
elem = driver.find_element(By.XPATH, "/html/body/main/div[2]/div/div/div/div/div/div/div[" + str(counter) + "]/span[1]/small").text
|
||||
y = elem[1:5]
|
||||
m = elem[6:8]
|
||||
d = elem[9:11]
|
||||
|
||||
# get link
|
||||
link = ""
|
||||
try:
|
||||
link = driver.find_element(By.XPATH, "/html/body/main/div[2]/div/div/div/div/div/div/div[" + str(counter) + "]/b/a").get_attribute('href')
|
||||
except NoSuchElementException as nsee:
|
||||
continue
|
||||
|
||||
links.append(link)
|
||||
dates.append(d + "." + m + "." + y)
|
||||
dates_year.append(y)
|
||||
dates_num.append(y + m + d)
|
||||
|
||||
print(f"--- Number of found links: {len(links)}")
|
||||
|
||||
return links, dates, dates_year, dates_num
|
||||
|
||||
def getData(driver, link, date, date_year, date_num):
|
||||
print(f"--- --- {link}")
|
||||
|
||||
driver.get(link)
|
||||
|
||||
time.sleep(randint(5, 7))
|
||||
|
||||
subtitle = ""
|
||||
try:
|
||||
subtitle = driver.find_element(By.XPATH, "/html/body/main/div[3]/div/div/div/div[1]/div[1]/div/hgroup/h3").text
|
||||
except NoSuchElementException as nsee:
|
||||
pass
|
||||
maintitle = ""
|
||||
try:
|
||||
maintitle = driver.find_element(By.XPATH, "/html/body/main/div[3]/div/div/div/div[1]/div[1]/div/hgroup/h2").text
|
||||
except NoSuchElementException as nsee:
|
||||
pass
|
||||
redaktion = ""
|
||||
try:
|
||||
redaktion = driver.find_element(By.XPATH, "/html/body/main/div[3]/div/div/div/div[1]/div[1]/div/p[2]").text
|
||||
except NoSuchElementException as nsee:
|
||||
pass
|
||||
author = ""
|
||||
if redaktion != "":
|
||||
if redaktion.startswith("Redaktion: ") and redaktion.find(",") != -1:
|
||||
author = redaktion[11:redaktion.find(",")]
|
||||
main_content = ""
|
||||
try:
|
||||
main_content = driver.find_element(By.XPATH, "/html/body/main/div[3]/div/div/div/div[1]/div[1]/div/p[1]").text
|
||||
except NoSuchElementException as nsee:
|
||||
pass
|
||||
|
||||
full_content = main_content
|
||||
|
||||
dict = {
|
||||
"subtitle": subtitle,
|
||||
"maintitle": maintitle,
|
||||
"author": author,
|
||||
"date": date,
|
||||
"main_content": main_content,
|
||||
"redaktion": redaktion,
|
||||
"full_content": full_content,
|
||||
"date_year": date_year,
|
||||
"date_full": date_num,
|
||||
"url": link
|
||||
}
|
||||
|
||||
id = (str(date) + "_" + str(author) + "_" + str(maintitle)).replace(" ", "").replace("/", "").replace("ö", "").replace("ä", "").replace("ü", "").replace("Ö", "").replace("Ä", "").replace("Ü", "").replace(".", "").replace("?", "")
|
||||
id = id + "_archiv"
|
||||
|
||||
upload(dict, id)
|
||||
|
||||
|
||||
def upload(dict, id):
|
||||
print("--- Uploading")
|
||||
try:
|
||||
es.index(index=index_name, id=id, document=dict)
|
||||
except Exception as e:
|
||||
print("--- Error while uploading")
|
||||
print(e)
|
||||
|
||||
def check_elastic_online():
|
||||
if not es.ping():
|
||||
sys.exit("No connection to Elasticsearch")
|
||||
|
||||
# main - entry point
|
||||
if __name__ == '__main__':
|
||||
print("Starting")
|
||||
|
||||
check_elastic_online()
|
||||
|
||||
years = [2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016]
|
||||
link_1 = "https://www.uni-due.de/aktuell/archiv-"
|
||||
link_2 = ".php"
|
||||
|
||||
options = Options()
|
||||
options.add_argument("--headless")
|
||||
|
||||
driver = webdriver.Firefox(options=options)
|
||||
|
||||
for year in years:
|
||||
print(f"Crawling year {year}")
|
||||
link = link_1 + str(year) + link_2
|
||||
|
||||
# get year links
|
||||
links, dates, dates_year, dates_num = getLinks(link, driver)
|
||||
|
||||
for i in range(len(links)):
|
||||
print(f"--- Crawling Data for current year {year} at {i} / {len(links)}")
|
||||
getData(driver, links[i], dates[i], dates_year[i], dates_num[i])
|
||||
|
||||
driver.close()
|
||||
|
||||
print("Finished")
|
||||
@@ -0,0 +1,3 @@
|
||||
#please check for right versions of the packages in your environment and update them if necessary
|
||||
spacy
|
||||
selenium
|
||||
@@ -0,0 +1,49 @@
|
||||
import subprocess
|
||||
import sys
|
||||
import os
|
||||
import shutil
|
||||
import time
|
||||
|
||||
def run_command(command, cwd=None):
|
||||
"""Run a shell command and exit if it fails."""
|
||||
result = subprocess.run(command,
|
||||
shell=True,
|
||||
cwd=cwd,
|
||||
#capture_output=True, #supresses output from subprocess
|
||||
text=True)
|
||||
if result.returncode != 0:
|
||||
print(f"Command failed: {command}")
|
||||
print("Error output:\n", result.stderr)
|
||||
sys.exit(result.returncode)
|
||||
|
||||
if __name__ == "__main__":
|
||||
start_time = time.time()
|
||||
|
||||
base_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
crawler_dir = os.path.join(base_dir, "aktuell")
|
||||
out_dir = os.path.join(crawler_dir, "out")
|
||||
|
||||
if os.path.exists(out_dir):
|
||||
shutil.rmtree(out_dir)
|
||||
os.makedirs(out_dir)
|
||||
|
||||
output_file_links = os.path.join(out_dir, "links.json")
|
||||
output_file_meta = os.path.join(out_dir, "meta.json")
|
||||
|
||||
|
||||
print("Running Scrapy link crawler...")
|
||||
run_command(f"scrapy crawl aktuell-links -O \"{output_file_links}\"", cwd=crawler_dir)
|
||||
|
||||
print("Running Scrapy meta crawler...")
|
||||
run_command(f"scrapy crawl aktuell-metadata -O \"{output_file_meta}\"", cwd=crawler_dir)
|
||||
|
||||
print("Running upload script")
|
||||
run_command(f"{sys.executable} upload_aktuell.py {output_file_meta}", cwd=base_dir)
|
||||
|
||||
end_time = time.time()
|
||||
runtime_seconds = end_time - start_time
|
||||
runtime_hours = runtime_seconds / 3600
|
||||
|
||||
print(f"Runtime: {runtime_hours:.2f} hours")
|
||||
print("Finished crawling and uploading UDE news articles.")
|
||||
|
||||
@@ -0,0 +1,275 @@
|
||||
from elasticsearch import Elasticsearch
|
||||
import sys
|
||||
import os
|
||||
import json
|
||||
from datetime import datetime
|
||||
import time
|
||||
|
||||
# elasticsearch-connection should be adjusted
|
||||
# uni-server
|
||||
es = Elasticsearch()
|
||||
|
||||
index_name = "aktuell-test" #test indices to make sure everything works before uploading to the real index, ps. you lack rights to push to the real index, please contact the admin if you want to push to the real index
|
||||
|
||||
|
||||
# checks if elastic is up and creates the index if not already done
|
||||
def check_elastic():
|
||||
if not es.ping():
|
||||
sys.exit("No connection to Elasticsearch")
|
||||
|
||||
if not es.indices.exists(index=index_name):
|
||||
settings = {
|
||||
"analysis": {
|
||||
"analyzer": {
|
||||
"searchabilityAnalyzer": {
|
||||
"type": "custom",
|
||||
"tokenizer": "standard",
|
||||
"filter": [
|
||||
"lowercase",
|
||||
"asciifolding"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
mappings = {
|
||||
"properties": {
|
||||
"subtitle": {
|
||||
"type": "text",
|
||||
"analyzer": "searchabilityAnalyzer",
|
||||
"search_analyzer": "searchabilityAnalyzer",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 256
|
||||
}
|
||||
}
|
||||
},
|
||||
"maintitle": {
|
||||
"type": "text",
|
||||
"analyzer": "searchabilityAnalyzer",
|
||||
"search_analyzer": "searchabilityAnalyzer",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 256
|
||||
}
|
||||
}
|
||||
},
|
||||
"author": {
|
||||
"type": "text",
|
||||
"analyzer": "searchabilityAnalyzer",
|
||||
"search_analyzer": "searchabilityAnalyzer",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 256
|
||||
}
|
||||
}
|
||||
},
|
||||
"date": {
|
||||
"type": "text",
|
||||
"analyzer": "searchabilityAnalyzer",
|
||||
"search_analyzer": "searchabilityAnalyzer",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 256
|
||||
}
|
||||
}
|
||||
},
|
||||
"date_year": {
|
||||
"type": "long",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 256
|
||||
}
|
||||
}
|
||||
},
|
||||
"date_full": {
|
||||
"type": "long",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 256
|
||||
}
|
||||
}
|
||||
},
|
||||
"intro_content": {
|
||||
"type": "text",
|
||||
"analyzer": "searchabilityAnalyzer",
|
||||
"search_analyzer": "searchabilityAnalyzer",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 256
|
||||
}
|
||||
}
|
||||
},
|
||||
"main_content": {
|
||||
"type": "text",
|
||||
"analyzer": "searchabilityAnalyzer",
|
||||
"search_analyzer": "searchabilityAnalyzer",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 256
|
||||
}
|
||||
}
|
||||
},
|
||||
"further_content": {
|
||||
"type": "text",
|
||||
"analyzer": "searchabilityAnalyzer",
|
||||
"search_analyzer": "searchabilityAnalyzer",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 256
|
||||
}
|
||||
}
|
||||
},
|
||||
"redaktion": {
|
||||
"type": "text",
|
||||
"analyzer": "searchabilityAnalyzer",
|
||||
"search_analyzer": "searchabilityAnalyzer",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 256
|
||||
}
|
||||
}
|
||||
},
|
||||
"full_content": {
|
||||
"type": "text",
|
||||
"analyzer": "searchabilityAnalyzer",
|
||||
"search_analyzer": "searchabilityAnalyzer",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 256
|
||||
}
|
||||
}
|
||||
},
|
||||
"tags": {
|
||||
"type": "text",
|
||||
"analyzer": "searchabilityAnalyzer",
|
||||
"search_analyzer": "searchabilityAnalyzer",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 256
|
||||
}
|
||||
}
|
||||
},
|
||||
"tags_nested": {
|
||||
"type": "nested",
|
||||
"properties": {
|
||||
"tag": {
|
||||
"type": "text",
|
||||
"analyzer": "searchabilityAnalyzer",
|
||||
"search_analyzer": "searchabilityAnalyzer",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 250
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
#"links": {
|
||||
# "type": "text",
|
||||
# "analyzer": "searchabilityAnalyzer",
|
||||
# "search_analyzer": "searchabilityAnalyzer",
|
||||
# "fields": {
|
||||
# "keyword": {
|
||||
# "type": "keyword",
|
||||
# "ignore_above": 256
|
||||
# }
|
||||
# }
|
||||
#},
|
||||
"links_nested": {
|
||||
"type": "nested",
|
||||
"properties": {
|
||||
"url": {
|
||||
"type": "text",
|
||||
"analyzer": "searchabilityAnalyzer",
|
||||
"search_analyzer": "searchabilityAnalyzer",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 250
|
||||
}
|
||||
}
|
||||
},
|
||||
"text": {
|
||||
"type": "text",
|
||||
"analyzer": "searchabilityAnalyzer",
|
||||
"search_analyzer": "searchabilityAnalyzer",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 250
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
es.indices.create(index=index_name, mappings=mappings, settings=settings)
|
||||
|
||||
def upload(path):
|
||||
with open(path, "r", encoding='utf-8') as json_file:
|
||||
|
||||
try:
|
||||
json_loaded = json.load(json_file)
|
||||
|
||||
for news in json_loaded:
|
||||
time.sleep(10 / 1000)
|
||||
id = (str(news["date"]) + "_" + str(news["author"]) + "_" + str(news["maintitle"])).replace(" ", "").replace("/", "").replace("ö", "").replace("ä", "").replace("ü", "").replace("Ö", "").replace("Ä", "").replace("Ü", "").replace(".", "").replace("?", "")
|
||||
|
||||
links_nested = []
|
||||
links = news["links"]
|
||||
|
||||
for link in links:
|
||||
links_nested.append({"url": link["url"], "text": link["text"].replace(" ", "")})
|
||||
|
||||
tags_nested = []
|
||||
tags = news["tags"]
|
||||
for p in range(len(tags)):
|
||||
tags_nested.append({"tag": tags[p]})
|
||||
|
||||
dict = {
|
||||
"subtitle": news["subtitle"],
|
||||
"maintitle": news["maintitle"],
|
||||
"tags": news["tags"],
|
||||
"author": news["author"],
|
||||
"date": news["date"],
|
||||
"intro_content": news["intro_content"],
|
||||
"main_content": news["main_content"],
|
||||
"further_content": news["further_content"],
|
||||
"redaktion": news["redaktion"],
|
||||
"full_content": news["full_content"],
|
||||
"tags_nested": tags_nested,
|
||||
"date_year": news["date_year"],
|
||||
"date_full": news["date_full"],
|
||||
#"links": news["links"],
|
||||
"links_nested": links_nested,
|
||||
"url": news["url"]
|
||||
}
|
||||
|
||||
es.index(index=index_name, id=id, document=dict)
|
||||
|
||||
except Exception as e:
|
||||
print("--- Failed to upload news.")
|
||||
print(e)
|
||||
|
||||
# main - entry point
|
||||
if __name__ == '__main__':
|
||||
check_elastic()
|
||||
|
||||
if len(sys.argv) != 2:
|
||||
sys.exit("No path given.")
|
||||
upload(sys.argv[1])
|
||||
@@ -0,0 +1,143 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
build_patents_openalex_keywords.py — Build IPC/CPC → OpenAlex topic/keyword matches.
|
||||
|
||||
Fetches IPC/CPC metadata from the `ipc` index, matches labels against OpenAlex topics
|
||||
(from topic_hierarchy_cache.json) and keywords (from openalex-topics) using
|
||||
SentenceTransformer embeddings, then writes results to the patents_openalex_keywords
|
||||
Elasticsearch index and a local JSON backup.
|
||||
|
||||
Usage:
|
||||
python scripts/build_patents_openalex_keywords.py
|
||||
python scripts/build_patents_openalex_keywords.py --top-k 3 --min-score 0.55
|
||||
python scripts/build_patents_openalex_keywords.py --levels section class subclass
|
||||
python scripts/build_patents_openalex_keywords.py --skip-keywords
|
||||
|
||||
Requires src/main/inse/.env with PATENT_ELASTICSEARCH credentials (INSE) and, unless
|
||||
--skip-keywords is set, NES Elasticsearch credentials for openalex-topics.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
current_dir = Path(__file__).resolve().parent
|
||||
sys.path.insert(0, str(current_dir.parent / "src" / "main"))
|
||||
|
||||
from inse.patents.patents_openalex_keywords.client import PatentsOpenAlexKeywordsClient
|
||||
from inse.patents.patents_openalex_keywords.ipc_entries import (
|
||||
DEFAULT_BUILD_LEVELS,
|
||||
fetch_unique_ipc_entries,
|
||||
)
|
||||
from inse.patents.patents_openalex_keywords.matching import (
|
||||
TopicVectorsMatcher,
|
||||
build_documents_from_topicvectors,
|
||||
documents_to_json_mapping,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def run(args: argparse.Namespace) -> None:
|
||||
levels = tuple(args.levels)
|
||||
|
||||
ipc_entries = await fetch_unique_ipc_entries(levels=levels)
|
||||
counts = {level: len(ipc_entries.get(level, {})) for level in levels}
|
||||
logger.info("Fetched unique IPC/CPC symbols: %s", counts)
|
||||
|
||||
if args.skip_keywords:
|
||||
logger.info("--skip-keywords is ignored in topicvectors mode")
|
||||
if args.topic_cache:
|
||||
logger.info("--topic-cache is ignored in topicvectors mode")
|
||||
if args.batch_size != 64:
|
||||
logger.info("--batch-size is ignored in topicvectors mode")
|
||||
|
||||
matcher = TopicVectorsMatcher(min_score=args.min_score)
|
||||
logger.info("Matching IPC/CPC labels against topicvectors index...")
|
||||
documents = await build_documents_from_topicvectors(
|
||||
ipc_entries, matcher, levels=levels, top_k=args.top_k
|
||||
)
|
||||
logger.info("Built %d IPC/CPC mapping documents", len(documents))
|
||||
|
||||
if args.output:
|
||||
output_path = Path(args.output)
|
||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
mapping = documents_to_json_mapping(documents)
|
||||
output_path.write_text(
|
||||
json.dumps(mapping, indent=2, ensure_ascii=True),
|
||||
encoding="utf-8",
|
||||
)
|
||||
logger.info("Wrote local JSON backup to %s", output_path)
|
||||
|
||||
if not args.dry_run:
|
||||
client = PatentsOpenAlexKeywordsClient(timeout=60.0)
|
||||
await client.ensure_index()
|
||||
await client.bulk_index(documents)
|
||||
logger.info("Indexed %d documents into patents_openalex_keywords", len(documents))
|
||||
else:
|
||||
logger.info("Dry run — skipped Elasticsearch indexing")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Build IPC/CPC → OpenAlex topic/keyword matches with SentenceTransformer.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--output",
|
||||
default=str(
|
||||
current_dir.parent / "src" / "data" / "patents_openalex_keywords_mapping.json"
|
||||
),
|
||||
help="Local JSON backup path",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--topic-cache",
|
||||
default=None,
|
||||
help="Deprecated in topicvectors mode (kept for CLI compatibility)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--levels",
|
||||
nargs="+",
|
||||
default=list(DEFAULT_BUILD_LEVELS),
|
||||
choices=list(DEFAULT_BUILD_LEVELS),
|
||||
help="IPC/CPC hierarchy levels to map",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--top-k",
|
||||
type=int,
|
||||
default=3,
|
||||
help="Number of top topic/keyword matches per IPC/CPC code",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--min-score",
|
||||
type=float,
|
||||
default=0.5,
|
||||
help="Minimum cosine similarity for a match",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--batch-size",
|
||||
type=int,
|
||||
default=64,
|
||||
help="Deprecated in topicvectors mode (kept for CLI compatibility)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--skip-keywords",
|
||||
action="store_true",
|
||||
help="Deprecated in topicvectors mode (kept for CLI compatibility)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--dry-run",
|
||||
action="store_true",
|
||||
help="Build matches locally without indexing into Elasticsearch",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
|
||||
asyncio.run(run(args))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,61 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
index_org_patents.py — Build the org_patents Elasticsearch index for one institution.
|
||||
|
||||
Fetches all OpenAlex authors affiliated with the institution, searches EPO/USPTO for
|
||||
patents matched via institution assignee and/or author name (match_type: "institution",
|
||||
"name", or "both"), deletes existing documents for the institution, and reindexes.
|
||||
|
||||
Usage:
|
||||
python scripts/index_org_patents.py --institution-id <OpenAlex-ID>
|
||||
|
||||
Example (University of Duisburg-Essen):
|
||||
python scripts/index_org_patents.py --institution-id I62318514
|
||||
|
||||
Requires src/main/inse/.env with PATENT_ELASTICSEARCH_URL/API_KEY (and OpenAlex ES
|
||||
credentials for author lookup). Runtime scales with author count (~30-40 min for UDE's
|
||||
4,740 authors). Re-running is safe: existing documents are deleted before reindexing.
|
||||
|
||||
Future: integrate into an Admin Panel so admins can trigger this via the UI.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import logging
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
current_dir = Path(__file__).resolve().parent
|
||||
sys.path.insert(0, str(current_dir.parent / "src" / "main"))
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv(dotenv_path=current_dir.parent / "src" / "main" / "inse" / ".env")
|
||||
|
||||
from inse.patents.org.logic import index_org_patents_for_institution
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Build the org_patents index for one institution.",
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
epilog="Example: python scripts/index_org_patents.py --institution-id I62318514",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--institution-id",
|
||||
required=True,
|
||||
help="OpenAlex institution ID, e.g. I62318514 (University of Duisburg-Essen)",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
logger.info("Starting org_patents indexing for institution %s ...", args.institution_id)
|
||||
count = await index_org_patents_for_institution(args.institution_id)
|
||||
logger.info("Done. Indexed %d patents for institution %s.", count, args.institution_id)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"FKZ": "Förderkennzeichen",
|
||||
"Thema des geförderten Vorhabens": "Thema",
|
||||
"Ressort": "Ressort",
|
||||
"Ressort_fullname": "Ressort_fullname",
|
||||
"Referat": "Referat",
|
||||
"Administrierende Stelle": "Projektträger",
|
||||
"PT_fullname": "Projektträger_fullname",
|
||||
"Arb.-Einh.": "Arb.-Einh.",
|
||||
"Laufzeit von": "funding_start",
|
||||
"Laufzeit bis": "funding_end",
|
||||
"Laufzeit":"Laufzeit",
|
||||
"Förderart": "Förderart",
|
||||
"Förderempfänger /Auftragnehmer": "Zuwendungsempfänger",
|
||||
"Gemeindekennziffer": "Gemeindekennziffer",
|
||||
"Förder- / Auftragssumme (Anteil des Bundes) in EUR": "Fördersumme",
|
||||
"Stadt/Gemeinde": "Stadt/Gemeinde",
|
||||
"Ort": "Ort",
|
||||
"Bundesland": "Bundesland",
|
||||
"Staat": "Staat",
|
||||
"Leistungsplansystematik": "Leistungsplansystematik",
|
||||
"Leistungsplansystematik_fullname": "Leistungsplansystematik_fullname",
|
||||
"Klartext Leistungsplansystematik": "Klartext Leistungsplansystematik",
|
||||
"Förderprofil": "Förderprofil",
|
||||
"Projekt": "Verbundprojekt",
|
||||
"Ausführende Stelle": "Ausführende Stelle"
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,262 @@
|
||||
from selenium import webdriver
|
||||
from selenium.common.exceptions import NoSuchElementException
|
||||
from selenium.webdriver.chrome.options import Options
|
||||
from selenium.webdriver.chrome.service import Service
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
from selenium.webdriver.common.alert import Alert
|
||||
from random import randint
|
||||
import time
|
||||
import pandas as pd
|
||||
import json
|
||||
from datetime import datetime
|
||||
import sys
|
||||
from elasticsearch import Elasticsearch, helpers
|
||||
from elasticsearch.helpers import bulk,BulkIndexError
|
||||
import os
|
||||
import hashlib
|
||||
|
||||
|
||||
download_path=os.path.abspath(os.getcwd())
|
||||
es = Elasticsearch()
|
||||
|
||||
def crawl_data(link,driver):
|
||||
driver.get(link)
|
||||
search_field = driver.find_element(By.ID,"suche_schnellSuche")
|
||||
if search_field.is_displayed():
|
||||
# The element is visible, safe to interact
|
||||
search_field.send_keys("*")
|
||||
start_search_btn = driver.find_element(By.XPATH,'/html/body/div[1]/div/div/form[1]/div/fieldset/table/tbody/tr[1]/td[2]/input')
|
||||
start_search_btn.click()
|
||||
|
||||
WebDriverWait(driver, 30).until(
|
||||
EC.element_to_be_clickable((By.XPATH,'//*[@id="unterNavigation"]/ul/li[4]/div/a'))
|
||||
)
|
||||
|
||||
#Click the Export button to trigger data export
|
||||
export_button = driver.find_element(By.XPATH,'//*[@id="unterNavigation"]/ul/li[4]/div/a')
|
||||
export_button.click()
|
||||
# Wait for the prompt to appear
|
||||
time.sleep(2)
|
||||
# Switch to the alert and Clicks the "OK" button
|
||||
Alert(driver).accept()
|
||||
print("downloading data")
|
||||
else:
|
||||
# The element is likely a honeypot, do not interact
|
||||
print("Honeypot detected, skipping interaction")
|
||||
|
||||
|
||||
def check_elastic_online():
|
||||
if not es.ping():
|
||||
sys.exit("No connection to Elasticsearch")
|
||||
else :
|
||||
print("Elasticsearch connection established")
|
||||
|
||||
def check_elastic_index(df, index_name):
|
||||
|
||||
if not es.indices.exists(index=index_name):
|
||||
print(index_name + " index wasn't found. Creating a new one..")
|
||||
settings = {
|
||||
"analysis": {
|
||||
"analyzer": {
|
||||
"searchabilityAnalyzer": {
|
||||
"type": "custom",
|
||||
"tokenizer": "standard",
|
||||
"filter": [
|
||||
"lowercase",
|
||||
"asciifolding"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
mappings = {}
|
||||
properties = {}
|
||||
|
||||
for key in list(df.columns):
|
||||
if key in ("funding_start", "funding_end", "datum"):
|
||||
properties[key] = {
|
||||
"type": "date",
|
||||
"format": "dd.MM.yyyy"
|
||||
}
|
||||
elif key == "Publikationsdatum":
|
||||
properties[key] = {
|
||||
"type": "date",
|
||||
"format": "yyyy"
|
||||
}
|
||||
elif key == "unix_timestamp":
|
||||
properties[key] = {
|
||||
"type": "long"
|
||||
}
|
||||
elif key == "Fördersumme":
|
||||
properties[key] = {
|
||||
"type": "float"
|
||||
}
|
||||
elif key == "new":
|
||||
properties[key] = {
|
||||
"type": "boolean"
|
||||
}
|
||||
else:
|
||||
properties[key] = {
|
||||
"type": "text",
|
||||
"analyzer": "searchabilityAnalyzer",
|
||||
"search_analyzer": "searchabilityAnalyzer",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 256
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mappings["properties"] = properties
|
||||
|
||||
es.indices.create(index=index_name, mappings=mappings, settings=settings)
|
||||
es.indices.refresh(index=index_name)
|
||||
print("The new index '"+index_name+"' has been created")
|
||||
else:
|
||||
print(index_name + " already exists. Uploading data...")
|
||||
|
||||
def upload_data(df,index_name):
|
||||
def fill_docs_to_upload(row):
|
||||
doc_id = hashlib.sha256(str(row['Förderkennzeichen']).encode('utf-8')).hexdigest()
|
||||
doc = {
|
||||
"_op_type": "update", # Update existing documents
|
||||
"_index": index_name,
|
||||
"_id": doc_id,
|
||||
"doc": {
|
||||
"new":False
|
||||
},
|
||||
"upsert":{
|
||||
**row.to_dict(),
|
||||
"new":True
|
||||
}
|
||||
}
|
||||
|
||||
docs_to_upload.append(doc)
|
||||
print("Uploading data...")
|
||||
|
||||
try:
|
||||
check_elastic_index(df, index_name)
|
||||
except Exception as e:
|
||||
print("Error while creating index")
|
||||
print(e)
|
||||
|
||||
docs_to_upload = []
|
||||
df.apply(fill_docs_to_upload,axis=1)
|
||||
def bulk_docs(docs,data_rate):
|
||||
response_sum = 0
|
||||
for i in range(0, len(docs), data_rate):
|
||||
try:
|
||||
response = helpers.bulk(es,docs[i:i + data_rate])
|
||||
response_sum = response_sum + response[0]
|
||||
except BulkIndexError as e:
|
||||
print(f"{len(e.errors)} document(s) failed to index.")
|
||||
for error in e.errors:
|
||||
print("Error details:", error)
|
||||
print ("Upload is completed. "+ str(response_sum) +" documents have been uploaded." )
|
||||
data_rate = 200
|
||||
bulk_docs(docs_to_upload,data_rate)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def wait_for_file_complete(download_path,file_name):
|
||||
while True:
|
||||
file_path = os.path.join(download_path, file_name)
|
||||
if os.path.exists(file_path) and not any(
|
||||
fname.endswith(".part") or fname.endswith(".crdownload")
|
||||
for fname in os.listdir(download_path)
|
||||
):
|
||||
print(f"Download complete: {file_name}")
|
||||
return True
|
||||
if any(fname.endswith((".part", ".crdownload")) for fname in os.listdir(download_path)):
|
||||
time.sleep(1)
|
||||
else:
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
|
||||
def format_data(df):
|
||||
print("Formattind data...")
|
||||
df.drop(list(df.filter(regex='.1|Unnamed')), axis=1, inplace=True)
|
||||
def clean_format(text):
|
||||
if isinstance(text, str):
|
||||
if text.startswith('="') and text.endswith('"'):
|
||||
return text[2:-1]
|
||||
return text
|
||||
df.columns = [clean_format(col) for col in df.columns]
|
||||
|
||||
df = df.applymap(clean_format)
|
||||
df["FKZ"] = df["FKZ"].str.replace(' /','/')
|
||||
json_path = os.path.join(os.path.abspath(os.getcwd()), 'extendingColumns.json')
|
||||
|
||||
with open(json_path, 'r', encoding='utf-8') as f:
|
||||
columnsObj = json.load(f)
|
||||
for column_name, content in columnsObj.items():
|
||||
alias_map = content['aliases']
|
||||
df[content['column_alias']] = df[column_name].map(alias_map)
|
||||
|
||||
|
||||
|
||||
df['Publikationsdatum'] = df['Laufzeit von'].str.split('.').str[2]
|
||||
df['unix_timestamp'] = int(time.time())
|
||||
df['datum'] = datetime.now().strftime("%d.%m.%Y")
|
||||
df['new'] = True
|
||||
if len(df['Laufzeit von']) and len(df['Laufzeit bis']):
|
||||
df['Laufzeit'] = "von " + df['Laufzeit von'] + " bis " + df['Laufzeit bis']
|
||||
|
||||
config_path = os.path.join(os.path.abspath(os.getcwd()), 'data_config.json')
|
||||
with open(config_path, 'r', encoding='utf-8') as f:
|
||||
config = json.load(f)
|
||||
df.rename(columns=config,inplace=True)
|
||||
|
||||
df = df.where(pd.notnull(df), "")
|
||||
df['Fördersumme'] = pd.to_numeric(
|
||||
df['Fördersumme'].astype(str)
|
||||
.str.replace('.', '', regex=False)
|
||||
.str.replace(',', '.', regex=False),
|
||||
errors='coerce'
|
||||
)
|
||||
return df
|
||||
|
||||
def setup_chrome_driver(download_path):
|
||||
options = Options()
|
||||
options.add_argument("--headless")
|
||||
options.add_argument("--no-sandbox")
|
||||
options.add_argument("--disable-dev-shm-usage")
|
||||
options.add_experimental_option("prefs", {
|
||||
"download.default_directory": download_path,
|
||||
"download.prompt_for_download": False,
|
||||
"download.directory_upgrade": True,
|
||||
"plugins.always_open_pdf_externally": True,
|
||||
})
|
||||
chromedriver_path = "/home/inse/miniconda3/envs/airflow/bin/chromedriver"
|
||||
service = Service(executable_path=chromedriver_path)
|
||||
driver = webdriver.Chrome(service=service, options=options)
|
||||
return driver
|
||||
|
||||
|
||||
# main - entry point
|
||||
if __name__ == '__main__':
|
||||
print("Starting")
|
||||
file_path = os.path.join(os.path.abspath(os.getcwd()), 'Suchliste.csv')
|
||||
if not os.path.exists(file_path):
|
||||
driver = setup_chrome_driver(download_path)
|
||||
link_to_crawl= "https://foerderportal.bund.de/foekat/jsp/SucheAction.do?actionMode=searchreset"
|
||||
crawl_data(link_to_crawl,driver)
|
||||
wait_for_file_complete(download_path, "Suchliste.csv")
|
||||
driver.close()
|
||||
|
||||
|
||||
file = pd.read_csv(file_path,encoding = "latin1",sep=";")
|
||||
df = pd.DataFrame(file)
|
||||
df_formatted = format_data(df)
|
||||
|
||||
index_name = "projects_bund_test" #test indices to make sure everything works before uploading to the real index, ps. you lack rights to push to the real index, please contact the admin if you want to push to the real index
|
||||
check_elastic_online()
|
||||
upload_data(df_formatted,index_name)
|
||||
os.remove(file_path)
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
# Project → OpenAlex topic mapping
|
||||
|
||||
Self-contained script that maps a keyword field of a project index to OpenAlex
|
||||
topics via the backend's `/api/topics/vector-search` endpoint, and persists one
|
||||
document per (project, keyword) pair into an output index with the explicit
|
||||
mapping from `mapping.py`:
|
||||
|
||||
```json
|
||||
{
|
||||
"project_id": "...",
|
||||
"keyword": "<value of the source text field>",
|
||||
"source_index": "...",
|
||||
"source_field": "...",
|
||||
"topic_matches": [
|
||||
{"rank": 1, "topic_id": "...", "topic_display_name": "...",
|
||||
"subfield": "...", "field": "...", "domain": "...", "match_score": null}
|
||||
],
|
||||
"match_method": "sentence_transformer",
|
||||
"model_name": "...",
|
||||
"built_at": "..."
|
||||
}
|
||||
```
|
||||
|
||||
`match_score` is `null` because the endpoint does not expose Elasticsearch
|
||||
scores; `rank` preserves the search result order.
|
||||
|
||||
## Setup
|
||||
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
Credentials are read from `service/src/main/inse/.env` by default (override
|
||||
with `--env-file` or plain environment variables): `ELASTICSEARCH_INSE_URL` /
|
||||
`ELASTICSEARCH_INSE_API_KEY` for the `inse` cluster, `ELASTICSEARCH_URL` /
|
||||
`ELASTICSEARCH_API_KEY` for `nes`. The backend must be running (e.g.
|
||||
`./gradlew serve`, default `http://localhost:8000`, override with
|
||||
`--api-base-url`).
|
||||
|
||||
## Runs
|
||||
|
||||
Bund (keyword is the Leistungsplansystematik full text, one per project,
|
||||
project id = document `_id`):
|
||||
|
||||
```bash
|
||||
python map_project_topics.py \
|
||||
--source-index projects_bund_v1 \
|
||||
--text-field Leistungsplansystematik_fullname \
|
||||
--output-index projects_bund_openalex_topics
|
||||
```
|
||||
|
||||
EU EuroSciVoc (keyword is the `title` term, several per project, project id in
|
||||
the `projectID` field) — all three framework programmes into one output index:
|
||||
|
||||
```bash
|
||||
for idx in cordis_eu_fp7_euroscivoc cordis_eu_horizon_2020_euroscivoc cordis_eu_horizon_europe_euroscivoc; do
|
||||
python map_project_topics.py \
|
||||
--source-index "$idx" \
|
||||
--text-field title \
|
||||
--project-id-field projectID \
|
||||
--output-index projects_eu_openalex_topics
|
||||
done
|
||||
```
|
||||
|
||||
## Behaviour
|
||||
|
||||
- **Resumable**: source documents whose id already exists in the output index
|
||||
are skipped; the coverage is logged at startup (`Coverage: X/Y already in
|
||||
index, Z still to be processed`). Just rerun after an interruption.
|
||||
- **Incremental**: each unique keyword is searched once, results are
|
||||
bulk-indexed chunk by chunk with progress logs.
|
||||
- **Fail-fast**: exits immediately with a clear message if the backend or the
|
||||
Elasticsearch credentials are missing.
|
||||
- Keywords whose search failed are not persisted (and are retried on the next
|
||||
run); a warning at the end tells how many documents remain.
|
||||
- `--dry-run` matches without creating/writing the output index, `--output
|
||||
file.json` writes a local JSON backup, `--max-docs N` limits the scan for
|
||||
test runs, `--top-k` sets matches per keyword (default 3).
|
||||
@@ -0,0 +1,548 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
map_project_topics.py — Map project keywords to OpenAlex topics.
|
||||
|
||||
Streams all documents from a source index, reads a configurable text field
|
||||
(the "project-specific keyword"), matches every unique keyword against
|
||||
OpenAlex topics, and persists one document per (project, keyword) pair into
|
||||
the output index using mapping.PROJECT_TOPICS_MAPPING:
|
||||
|
||||
{project_id, keyword, source_index, source_field, topic_matches[],
|
||||
match_method, model_name, built_at}
|
||||
|
||||
The run is resumable: source documents whose id already exists in the output
|
||||
index are skipped, so a crashed or interrupted run can simply be restarted.
|
||||
Each unique keyword is searched only once and results are bulk-indexed
|
||||
incrementally, chunk by chunk.
|
||||
|
||||
Usage (bund, keyword unique per project, project id is the document _id):
|
||||
python map_project_topics.py \
|
||||
--source-index projects_bund_v1 \
|
||||
--text-field Leistungsplansystematik_fullname \
|
||||
--output-index projects_bund_openalex_topics
|
||||
|
||||
Usage (EU EuroSciVoc, project id in the projectID source field):
|
||||
python map_project_topics.py \
|
||||
--source-index cordis_eu_fp7_euroscivoc \
|
||||
--text-field title \
|
||||
--project-id-field projectID \
|
||||
--output-index projects_eu_openalex_topics
|
||||
|
||||
Requires ELASTICSEARCH_INSE_URL/ELASTICSEARCH_INSE_API_KEY (and for
|
||||
--*-cluster nes: ELASTICSEARCH_URL/ELASTICSEARCH_API_KEY) in the environment
|
||||
or in the service .env, plus a running backend serving
|
||||
/api/topics/vector-search (e.g. ./gradlew serve).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any, AsyncIterator
|
||||
|
||||
import httpx
|
||||
from dotenv import load_dotenv
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
from service.scripts.projects.topic_mapper.mapping import PROJECT_TOPICS_MAPPING
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
DEFAULT_ENV_FILE = Path(__file__).resolve().parents[2] / "src" / "main" / "inse" / ".env"
|
||||
DEFAULT_API_BASE_URL = "http://localhost:8000" #backend TODO replace with env variable
|
||||
VECTOR_SEARCH_PATH = "/api/topics/vector-search"
|
||||
MATCH_METHOD = "sentence_transformer"
|
||||
SEARCH_CONCURRENCY = 8
|
||||
TEXT_BATCH_SIZE = 100
|
||||
SCAN_PAGE_SIZE = 1000
|
||||
BULK_BATCH_SIZE = 500
|
||||
MAX_RETRIES = 3
|
||||
RETRY_BACKOFF_SECONDS = 5
|
||||
|
||||
_http_client: httpx.AsyncClient | None = None
|
||||
|
||||
|
||||
def get_http_client() -> httpx.AsyncClient:
|
||||
global _http_client
|
||||
if _http_client is None:
|
||||
_http_client = httpx.AsyncClient(timeout=60.0)
|
||||
return _http_client
|
||||
|
||||
|
||||
def es_credentials(cluster: str) -> tuple[str, str]:
|
||||
"""Returns (url, api_key) for a cluster from the environment."""
|
||||
env_names = {
|
||||
"inse": ("ELASTICSEARCH_INSE_URL", "ELASTICSEARCH_INSE_API_KEY"),
|
||||
"nes": ("ELASTICSEARCH_URL", "ELASTICSEARCH_API_KEY"),
|
||||
}
|
||||
url_var, key_var = env_names[cluster]
|
||||
url, api_key = os.getenv(url_var), os.getenv(key_var)
|
||||
if not url or not api_key:
|
||||
raise SystemExit(
|
||||
f"{url_var} and {key_var} must be set (via environment or --env-file)."
|
||||
)
|
||||
return url.rstrip("/"), api_key
|
||||
|
||||
|
||||
def es_headers(cluster: str, content_type: str = "application/json") -> tuple[str, dict]:
|
||||
url, api_key = es_credentials(cluster)
|
||||
return url, {"Authorization": f"ApiKey {api_key}", "Content-Type": content_type}
|
||||
|
||||
|
||||
async def with_retries(coro_factory, description: str):
|
||||
"""Retries transient network failures with a linear backoff."""
|
||||
for attempt in range(1, MAX_RETRIES):
|
||||
try:
|
||||
return await coro_factory()
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"%s failed (attempt %d/%d), retrying in %ds...",
|
||||
description,
|
||||
attempt,
|
||||
MAX_RETRIES,
|
||||
RETRY_BACKOFF_SECONDS * attempt,
|
||||
)
|
||||
await asyncio.sleep(RETRY_BACKOFF_SECONDS * attempt)
|
||||
return await coro_factory()
|
||||
|
||||
|
||||
async def scan(
|
||||
index: str, cluster: str, query: dict, source: list[str]
|
||||
) -> AsyncIterator[dict[str, Any]]:
|
||||
"""Yields every hit matching query via point-in-time + search_after."""
|
||||
url, headers = es_headers(cluster)
|
||||
client = get_http_client()
|
||||
|
||||
response = await client.post(
|
||||
f"{url}/{index}/_pit?keep_alive=1m", headers=headers
|
||||
)
|
||||
response.raise_for_status()
|
||||
pit_id = response.json()["id"]
|
||||
search_after: list | None = None
|
||||
|
||||
try:
|
||||
while True:
|
||||
payload: dict[str, Any] = {
|
||||
"size": SCAN_PAGE_SIZE,
|
||||
"query": query,
|
||||
"pit": {"id": pit_id, "keep_alive": "1m"},
|
||||
"sort": [{"_shard_doc": "asc"}],
|
||||
"track_total_hits": False,
|
||||
"_source": source,
|
||||
}
|
||||
if search_after is not None:
|
||||
payload["search_after"] = search_after
|
||||
|
||||
response = await with_retries(
|
||||
lambda: client.post(f"{url}/_search", json=payload, headers=headers),
|
||||
f"Scanning '{index}'",
|
||||
)
|
||||
response.raise_for_status()
|
||||
result = response.json()
|
||||
|
||||
hits = result.get("hits", {}).get("hits", [])
|
||||
if not hits:
|
||||
break
|
||||
for hit in hits:
|
||||
yield hit
|
||||
|
||||
pit_id = result.get("pit_id", pit_id)
|
||||
search_after = hits[-1].get("sort")
|
||||
if search_after is None or len(hits) < SCAN_PAGE_SIZE:
|
||||
break
|
||||
finally:
|
||||
try:
|
||||
await client.request(
|
||||
"DELETE", f"{url}/_pit", json={"id": pit_id}, headers=headers
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Failed to close Elasticsearch point-in-time.")
|
||||
|
||||
|
||||
async def check_backend(api_base_url: str) -> None:
|
||||
"""Fails fast with a clear message if the backend is not reachable."""
|
||||
client = get_http_client()
|
||||
try:
|
||||
response = await client.get(
|
||||
f"{api_base_url}{VECTOR_SEARCH_PATH}", params={"query": "test", "limit": 1}
|
||||
)
|
||||
response.raise_for_status()
|
||||
except Exception as exc:
|
||||
raise SystemExit(
|
||||
f"Backend not reachable at {api_base_url}{VECTOR_SEARCH_PATH} ({exc}). "
|
||||
"Start the service (e.g. ./gradlew serve) or pass --api-base-url."
|
||||
) from exc
|
||||
logger.info("Backend reachable at %s%s.", api_base_url, VECTOR_SEARCH_PATH)
|
||||
|
||||
|
||||
async def ensure_index(index: str, cluster: str) -> None:
|
||||
"""Creates the output index with the explicit mapping if it does not exist."""
|
||||
url, headers = es_headers(cluster)
|
||||
client = get_http_client()
|
||||
|
||||
response = await client.head(f"{url}/{index}", headers=headers)
|
||||
if response.status_code == 200:
|
||||
logger.info("Output index '%s' already exists.", index)
|
||||
return
|
||||
|
||||
response = await client.put(
|
||||
f"{url}/{index}", json={"mappings": PROJECT_TOPICS_MAPPING}, headers=headers
|
||||
)
|
||||
response.raise_for_status()
|
||||
logger.info("Created output index '%s' with explicit mapping.", index)
|
||||
|
||||
|
||||
async def fetch_source_entries(
|
||||
index: str, cluster: str, text_field: str, id_field: str | None, max_docs: int | None
|
||||
) -> dict[str, tuple[str, str]]:
|
||||
"""Returns doc_id -> (project_id, keyword) for every source document."""
|
||||
entries: dict[str, tuple[str, str]] = {}
|
||||
total = 0
|
||||
if id_field == "_id":
|
||||
id_field = None
|
||||
source_fields = [text_field] + ([id_field] if id_field else [])
|
||||
|
||||
async for hit in scan(
|
||||
index=index,
|
||||
cluster=cluster,
|
||||
query={"exists": {"field": text_field}},
|
||||
source=source_fields,
|
||||
):
|
||||
total += 1
|
||||
doc_source = hit.get("_source", {})
|
||||
text = str(doc_source.get(text_field) or "").strip()
|
||||
project_id = str(doc_source.get(id_field) or "").strip() if id_field else hit["_id"]
|
||||
if text and project_id:
|
||||
entries[hit["_id"]] = (project_id, text)
|
||||
if total % 50000 == 0:
|
||||
logger.info("Scanned %d source documents...", total)
|
||||
if max_docs and total >= max_docs:
|
||||
logger.info("Stopping scan at --max-docs=%d.", max_docs)
|
||||
break
|
||||
|
||||
logger.info(
|
||||
"Scanned %d documents from '%s', %d with a non-empty '%s'.",
|
||||
total,
|
||||
index,
|
||||
len(entries),
|
||||
text_field,
|
||||
)
|
||||
return entries
|
||||
|
||||
|
||||
async def fetch_covered_doc_ids(index: str, cluster: str) -> set[str]:
|
||||
"""Returns the document ids that already exist in the output index."""
|
||||
covered: set[str] = set()
|
||||
try:
|
||||
async for hit in scan(index=index, cluster=cluster, query={"match_all": {}}, source=[]):
|
||||
covered.add(hit["_id"])
|
||||
except Exception:
|
||||
logger.info("Output index '%s' not readable yet — starting from scratch.", index)
|
||||
return set()
|
||||
return covered
|
||||
|
||||
|
||||
def build_topic_matches(topics: list[dict]) -> list[dict]:
|
||||
"""Maps /api/topics/vector-search results to ranked topic_matches entries.
|
||||
|
||||
The endpoint does not expose Elasticsearch scores, so match_score stays null;
|
||||
rank preserves the search result order.
|
||||
"""
|
||||
matches = []
|
||||
seen_ids = set()
|
||||
|
||||
for topic in topics:
|
||||
topic_id = topic.get("id")
|
||||
if not topic_id or topic_id in seen_ids:
|
||||
continue
|
||||
seen_ids.add(topic_id)
|
||||
matches.append(
|
||||
{
|
||||
"rank": len(matches) + 1,
|
||||
"topic_id": topic_id,
|
||||
"topic_display_name": topic.get("display_name"),
|
||||
"subfield": (topic.get("subfield") or {}).get("display_name"),
|
||||
"field": (topic.get("field") or {}).get("display_name"),
|
||||
"domain": (topic.get("domain") or {}).get("display_name"),
|
||||
"match_score": None,
|
||||
}
|
||||
)
|
||||
|
||||
return matches
|
||||
|
||||
|
||||
async def match_keywords(
|
||||
keywords: list[str], api_base_url: str, top_k: int, search_type: str
|
||||
) -> dict[str, list[dict]]:
|
||||
"""Searches topics for a chunk of keywords via the backend API, concurrently.
|
||||
|
||||
Keywords whose search failed are missing from the result, so they are
|
||||
retried on the next run instead of being persisted with empty matches.
|
||||
"""
|
||||
client = get_http_client()
|
||||
semaphore = asyncio.Semaphore(SEARCH_CONCURRENCY)
|
||||
|
||||
async def search_one(keyword: str) -> tuple[str, list[dict] | None]:
|
||||
async def request():
|
||||
response = await client.get(
|
||||
f"{api_base_url}{VECTOR_SEARCH_PATH}",
|
||||
params={"query": keyword, "limit": top_k, "searchType": search_type},
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
async with semaphore:
|
||||
try:
|
||||
data = await with_retries(request, f"Topic search for '{keyword[:60]}'")
|
||||
except Exception:
|
||||
logger.exception("Topic-Matching fuer Keyword '%s' fehlgeschlagen.", keyword)
|
||||
return keyword, None
|
||||
return keyword, build_topic_matches(data.get("results") or [])
|
||||
|
||||
results = await asyncio.gather(*(search_one(keyword) for keyword in keywords))
|
||||
return {keyword: matches for keyword, matches in results if matches is not None}
|
||||
|
||||
|
||||
async def bulk_index(index: str, cluster: str, documents: list[tuple[str, dict]]) -> None:
|
||||
"""Bulk-indexes (doc_id, document) pairs in batches."""
|
||||
url, headers = es_headers(cluster, content_type="application/x-ndjson")
|
||||
client = get_http_client()
|
||||
|
||||
for start in range(0, len(documents), BULK_BATCH_SIZE):
|
||||
batch = documents[start : start + BULK_BATCH_SIZE]
|
||||
lines = []
|
||||
for doc_id, doc in batch:
|
||||
lines.append(json.dumps({"index": {"_index": index, "_id": doc_id}}))
|
||||
lines.append(json.dumps(doc, ensure_ascii=False))
|
||||
payload = "\n".join(lines) + "\n"
|
||||
|
||||
async def send():
|
||||
response = await client.post(f"{url}/_bulk", content=payload, headers=headers)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
result = await with_retries(send, f"Bulk indexing {len(batch)} documents")
|
||||
if result.get("errors"):
|
||||
failed = [
|
||||
item["index"].get("error")
|
||||
for item in result.get("items", [])
|
||||
if item.get("index", {}).get("error")
|
||||
]
|
||||
logger.error("Bulk batch had %d failures, first: %s", len(failed), failed[:1])
|
||||
|
||||
|
||||
async def run(args: argparse.Namespace) -> None:
|
||||
built_at = datetime.now(timezone.utc).isoformat()
|
||||
model_name = os.getenv("SENTENCE_TRANSFORMERS_MODEL_NAME")
|
||||
|
||||
await check_backend(args.api_base_url)
|
||||
|
||||
if not args.dry_run:
|
||||
await ensure_index(index=args.output_index, cluster=args.output_cluster)
|
||||
|
||||
entries = await fetch_source_entries(
|
||||
index=args.source_index,
|
||||
cluster=args.source_cluster,
|
||||
text_field=args.text_field,
|
||||
id_field=args.project_id_field,
|
||||
max_docs=args.max_docs,
|
||||
)
|
||||
if not entries:
|
||||
logger.warning("No usable documents in '%s' — nothing to do.", args.source_index)
|
||||
return
|
||||
|
||||
covered = await fetch_covered_doc_ids(index=args.output_index, cluster=args.output_cluster)
|
||||
pending = {doc_id: entry for doc_id, entry in entries.items() if doc_id not in covered}
|
||||
logger.info(
|
||||
"Coverage: %d/%d documents already in '%s', %d still to be processed.",
|
||||
len(entries) - len(pending),
|
||||
len(entries),
|
||||
args.output_index,
|
||||
len(pending),
|
||||
)
|
||||
if not pending:
|
||||
logger.info("Nothing left to process.")
|
||||
return
|
||||
|
||||
docs_by_keyword: dict[str, list[tuple[str, str]]] = {}
|
||||
for doc_id, (project_id, keyword) in pending.items():
|
||||
docs_by_keyword.setdefault(keyword, []).append((doc_id, project_id))
|
||||
unique_keywords = sorted(docs_by_keyword)
|
||||
logger.info(
|
||||
"%d unique keywords cover the %d pending documents.",
|
||||
len(unique_keywords),
|
||||
len(pending),
|
||||
)
|
||||
|
||||
backup_docs: list[dict] = []
|
||||
docs_done = 0
|
||||
keywords_done = 0
|
||||
|
||||
for start in range(0, len(unique_keywords), args.text_batch_size):
|
||||
chunk = unique_keywords[start : start + args.text_batch_size]
|
||||
matches_by_keyword = await match_keywords(
|
||||
chunk,
|
||||
api_base_url=args.api_base_url,
|
||||
top_k=args.top_k,
|
||||
search_type=args.search_type,
|
||||
)
|
||||
|
||||
documents = []
|
||||
for keyword in chunk:
|
||||
if keyword not in matches_by_keyword:
|
||||
continue # search failed — left for the next run
|
||||
for doc_id, project_id in docs_by_keyword[keyword]:
|
||||
documents.append(
|
||||
(
|
||||
doc_id,
|
||||
{
|
||||
"project_id": project_id,
|
||||
"keyword": keyword,
|
||||
"source_index": args.source_index,
|
||||
"source_field": args.text_field,
|
||||
"topic_matches": matches_by_keyword[keyword],
|
||||
"match_method": MATCH_METHOD,
|
||||
"model_name": model_name,
|
||||
"built_at": built_at,
|
||||
},
|
||||
)
|
||||
)
|
||||
|
||||
if documents and not args.dry_run:
|
||||
await bulk_index(
|
||||
index=args.output_index, cluster=args.output_cluster, documents=documents
|
||||
)
|
||||
if args.output:
|
||||
backup_docs.extend(doc for _, doc in documents)
|
||||
|
||||
keywords_done += len(chunk)
|
||||
docs_done += len(documents)
|
||||
logger.info(
|
||||
"Progress: %d/%d keywords, %d/%d pending documents indexed into '%s'.",
|
||||
keywords_done,
|
||||
len(unique_keywords),
|
||||
docs_done,
|
||||
len(pending),
|
||||
args.output_index,
|
||||
)
|
||||
|
||||
skipped = len(pending) - docs_done
|
||||
if skipped:
|
||||
logger.warning(
|
||||
"%d documents were NOT indexed due to failed searches — rerun the script to retry.",
|
||||
skipped,
|
||||
)
|
||||
|
||||
if args.output:
|
||||
output_path = Path(args.output)
|
||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
output_path.write_text(
|
||||
json.dumps(backup_docs, indent=2, ensure_ascii=False), encoding="utf-8"
|
||||
)
|
||||
logger.info("Wrote local JSON backup (%d documents) to %s", len(backup_docs), output_path)
|
||||
|
||||
logger.info(
|
||||
"Done. %d documents indexed this run, %d covered in total.",
|
||||
docs_done,
|
||||
len(covered) + docs_done,
|
||||
)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Map a project index's keyword field to OpenAlex topics.",
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
epilog=(
|
||||
"Examples:\n"
|
||||
" python map_project_topics.py --source-index projects_bund_v1 "
|
||||
"--text-field Leistungsplansystematik_fullname --output-index projects_bund_openalex_topics\n"
|
||||
" python map_project_topics.py --source-index cordis_eu_fp7_euroscivoc "
|
||||
"--text-field title --project-id-field projectID --output-index projects_eu_openalex_topics"
|
||||
),
|
||||
)
|
||||
parser.add_argument("--source-index", required=True, help="Index to read projects from")
|
||||
parser.add_argument(
|
||||
"--text-field",
|
||||
required=True,
|
||||
help="Source field holding the project-specific keyword to match",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--output-index", required=True, help="Index to persist the topic mappings into"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--project-id-field",
|
||||
default="_id",
|
||||
help=(
|
||||
"Source field holding the project id, e.g. projectID for the EuroSciVoc "
|
||||
"indices (default: _id, the Elasticsearch document id)"
|
||||
),
|
||||
)
|
||||
parser.add_argument(
|
||||
"--source-cluster",
|
||||
default="inse",
|
||||
choices=["inse", "nes"],
|
||||
help="Cluster of the source index (default: inse)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--output-cluster",
|
||||
default="inse",
|
||||
choices=["inse", "nes"],
|
||||
help="Cluster of the output index (default: inse)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--api-base-url",
|
||||
default=DEFAULT_API_BASE_URL,
|
||||
help=f"Base URL of the running backend (default: {DEFAULT_API_BASE_URL})",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--top-k", type=int, default=3, help="Number of topic matches per keyword (default: 3)"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--search-type",
|
||||
default="hybrid",
|
||||
choices=["hybrid", "semantic"],
|
||||
help="Topic search type, mirrors vector_search_topics (default: hybrid)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--text-batch-size",
|
||||
type=int,
|
||||
default=TEXT_BATCH_SIZE,
|
||||
help=f"Unique keywords searched per chunk (default: {TEXT_BATCH_SIZE})",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--env-file",
|
||||
default=str(DEFAULT_ENV_FILE),
|
||||
help=f"Path to a .env with Elasticsearch credentials (default: {DEFAULT_ENV_FILE})",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--max-docs",
|
||||
type=int,
|
||||
default=None,
|
||||
help="Stop scanning the source index after N documents (for test runs)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--output",
|
||||
default=None,
|
||||
help="Optional path for a local JSON backup of the documents built this run",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--dry-run",
|
||||
action="store_true",
|
||||
help="Build the mapping without creating/writing the output index",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.env_file and Path(args.env_file).exists():
|
||||
load_dotenv(dotenv_path=args.env_file)
|
||||
|
||||
asyncio.run(run(args))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,30 @@
|
||||
"""Elasticsearch mapping for project -> OpenAlex topic mapping indices.
|
||||
|
||||
One document per (project, keyword) pair. For sources where the keyword field
|
||||
is unique per project (e.g. projects_bund_v1 Leistungsplansystematik_fullname)
|
||||
this means one document per project.
|
||||
"""
|
||||
|
||||
PROJECT_TOPICS_MAPPING = {
|
||||
"properties": {
|
||||
"project_id": {"type": "keyword"},
|
||||
"keyword": {"type": "text", "fields": {"keyword": {"type": "keyword"}}},
|
||||
"source_index": {"type": "keyword"},
|
||||
"source_field": {"type": "keyword"},
|
||||
"topic_matches": {
|
||||
"type": "nested",
|
||||
"properties": {
|
||||
"rank": {"type": "integer"},
|
||||
"topic_id": {"type": "keyword"},
|
||||
"topic_display_name": {"type": "keyword"},
|
||||
"subfield": {"type": "keyword"},
|
||||
"field": {"type": "keyword"},
|
||||
"domain": {"type": "keyword"},
|
||||
"match_score": {"type": "float"},
|
||||
},
|
||||
},
|
||||
"match_method": {"type": "keyword"},
|
||||
"model_name": {"type": "keyword"},
|
||||
"built_at": {"type": "date"},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
httpx>=0.27
|
||||
python-dotenv>=1.0
|
||||
@@ -1,9 +1,9 @@
|
||||
import uuid
|
||||
from typing import List, Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic import BaseModel, Field, model_validator
|
||||
|
||||
from inse.auth.model import UserRole
|
||||
from inse.auth.model import UserRole, normalize_roles
|
||||
|
||||
|
||||
class OrganizationProfile(BaseModel):
|
||||
@@ -16,7 +16,7 @@ class AccountProfile(BaseModel):
|
||||
id: uuid.UUID
|
||||
email: str
|
||||
name: str
|
||||
role: UserRole
|
||||
roles: List[UserRole]
|
||||
organization_id: uuid.UUID
|
||||
organization_name: str
|
||||
deleted: bool
|
||||
@@ -34,20 +34,45 @@ class AccountPage(BaseModel):
|
||||
|
||||
|
||||
class CreateAccountRequest(BaseModel):
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def _role_to_roles(cls, values):
|
||||
if isinstance(values, dict) and "roles" not in values and "role" in values:
|
||||
values = {**values, "roles": [values["role"]]}
|
||||
return values
|
||||
|
||||
email: str = Field(min_length=3)
|
||||
name: str = Field(min_length=1)
|
||||
role: UserRole = UserRole.USER
|
||||
roles: List[UserRole] = Field(default_factory=lambda: [UserRole.USER])
|
||||
organization_id: uuid.UUID
|
||||
password: str = Field(min_length=8)
|
||||
openalex_person_id: Optional[str] = None
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _normalize_roles(self):
|
||||
self.roles = normalize_roles(self.roles)
|
||||
return self
|
||||
|
||||
|
||||
class UpdateAccountRequest(BaseModel):
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def _role_to_roles(cls, values):
|
||||
if isinstance(values, dict) and "roles" not in values and "role" in values:
|
||||
values = {**values, "roles": [values["role"]]}
|
||||
return values
|
||||
|
||||
email: Optional[str] = Field(default=None, min_length=3)
|
||||
name: Optional[str] = Field(default=None, min_length=1)
|
||||
role: Optional[UserRole] = None
|
||||
roles: Optional[List[UserRole]] = None
|
||||
organization_id: Optional[uuid.UUID] = None
|
||||
password: Optional[str] = Field(default=None, min_length=8)
|
||||
openalex_person_id: Optional[str] = None
|
||||
deleted: Optional[bool] = None
|
||||
activated: Optional[bool] = None
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _normalize_roles(self):
|
||||
if self.roles is not None:
|
||||
self.roles = normalize_roles(self.roles)
|
||||
return self
|
||||
|
||||
@@ -5,7 +5,13 @@ from fastapi import HTTPException, status
|
||||
from sqlmodel import Session, func, or_, select
|
||||
|
||||
from inse.auth import service as auth_service
|
||||
from inse.auth.model import AccessTokenMetadata, Account, Organization, UserRole
|
||||
from inse.auth.model import (
|
||||
AccessTokenMetadata,
|
||||
Account,
|
||||
Organization,
|
||||
UserRole,
|
||||
normalize_roles,
|
||||
)
|
||||
|
||||
from .model import (
|
||||
AccountPage,
|
||||
@@ -28,13 +34,17 @@ def _role_allowed_for_editor(editor_role: UserRole, role: UserRole) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _roles_allowed_for_editor(editor_role: UserRole, roles: list[UserRole]) -> bool:
|
||||
return all(_role_allowed_for_editor(editor_role, role) for role in roles)
|
||||
|
||||
|
||||
def _account_to_profile(account: Account, token: AccessTokenMetadata) -> AccountProfile:
|
||||
organization_name = account.organization.name if account.organization else ""
|
||||
return AccountProfile(
|
||||
id=account.id,
|
||||
email=account.email,
|
||||
name=account.name,
|
||||
role=account.role,
|
||||
roles=normalize_roles(account.roles),
|
||||
organization_id=account.organization_id,
|
||||
organization_name=organization_name,
|
||||
deleted=account.deleted,
|
||||
@@ -175,7 +185,7 @@ def create_account(
|
||||
detail="Admins can only create accounts in their own organization.",
|
||||
)
|
||||
|
||||
if not _role_allowed_for_editor(access_token.effective_role, payload.role):
|
||||
if not _roles_allowed_for_editor(access_token.effective_role, payload.roles):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="You cannot assign this role.",
|
||||
@@ -194,7 +204,7 @@ def create_account(
|
||||
account = Account(
|
||||
email=email,
|
||||
name=payload.name.strip(),
|
||||
role=payload.role,
|
||||
roles=payload.roles,
|
||||
organization_id=payload.organization_id,
|
||||
password_hash=auth_service._hash_password(payload.password),
|
||||
openalex_person_id=payload.openalex_person_id,
|
||||
@@ -215,9 +225,19 @@ def list_organizations(
|
||||
.where(Organization.deleted.is_not(True))
|
||||
.order_by(Organization.name)
|
||||
).all()
|
||||
elif access_token.effective_role == UserRole.ADMIN:
|
||||
organization = session.get(Organization, access_token.effective_organization_id)
|
||||
organizations = [organization] if organization and not organization.deleted else []
|
||||
elif access_token.effective_role in {
|
||||
UserRole.ADMIN,
|
||||
UserRole.MANAGER,
|
||||
}:
|
||||
organization = session.get(
|
||||
Organization,
|
||||
access_token.effective_organization_id,
|
||||
)
|
||||
organizations = (
|
||||
[organization]
|
||||
if organization and not organization.deleted
|
||||
else []
|
||||
)
|
||||
else:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
|
||||
|
||||
@@ -261,15 +281,15 @@ def update_account(
|
||||
if payload.openalex_person_id is not None:
|
||||
account.openalex_person_id = payload.openalex_person_id
|
||||
|
||||
if payload.role is not None:
|
||||
if payload.roles is not None:
|
||||
if not can_admin_update:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
|
||||
if not _role_allowed_for_editor(access_token.effective_role, payload.role):
|
||||
if not _roles_allowed_for_editor(access_token.effective_role, payload.roles):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="You cannot assign this role.",
|
||||
)
|
||||
account.role = payload.role
|
||||
account.roles = payload.roles
|
||||
account.epoch += 1
|
||||
|
||||
if payload.organization_id is not None:
|
||||
|
||||
@@ -3,7 +3,8 @@ from datetime import datetime
|
||||
from enum import StrEnum
|
||||
from typing import List
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic import BaseModel, model_validator
|
||||
from sqlalchemy import JSON, Column, UniqueConstraint
|
||||
from sqlmodel import Field, Relationship, SQLModel
|
||||
|
||||
|
||||
@@ -14,12 +15,50 @@ class UserRole(StrEnum):
|
||||
USER = "USER"
|
||||
|
||||
|
||||
ROLE_PRIORITY = {
|
||||
UserRole.SUPER_ADMIN: 0,
|
||||
UserRole.ADMIN: 1,
|
||||
UserRole.MANAGER: 2,
|
||||
UserRole.USER: 3,
|
||||
}
|
||||
|
||||
|
||||
def normalize_roles(
|
||||
roles: List[UserRole] | List[str] | UserRole | str | None,
|
||||
) -> List[UserRole]:
|
||||
if roles is None:
|
||||
return [UserRole.USER]
|
||||
if isinstance(roles, (str, UserRole)):
|
||||
roles = [roles]
|
||||
|
||||
normalized = []
|
||||
seen = set()
|
||||
for role in roles:
|
||||
user_role = role if isinstance(role, UserRole) else UserRole(role)
|
||||
if user_role not in seen:
|
||||
normalized.append(user_role)
|
||||
seen.add(user_role)
|
||||
|
||||
return sorted(normalized or [UserRole.USER], key=lambda role: ROLE_PRIORITY[role])
|
||||
|
||||
|
||||
def effective_role_for_roles(
|
||||
roles: List[UserRole] | List[str] | UserRole | str | None,
|
||||
) -> UserRole:
|
||||
return normalize_roles(roles)[0]
|
||||
|
||||
|
||||
class TokenType(StrEnum):
|
||||
ID_TOKEN = "ID_TOKEN"
|
||||
REFRESH_TOKEN = "REFRESH_TOKEN"
|
||||
ACCESS_TOKEN = "ACCESS_TOKEN"
|
||||
|
||||
|
||||
class SecretPurpose(StrEnum):
|
||||
LOGIN_OTK = "LOGIN_OTK"
|
||||
PASSWORD_RESET = "PASSWORD_RESET"
|
||||
|
||||
|
||||
class Durable(SQLModel):
|
||||
deleted: bool = Field(
|
||||
default=False,
|
||||
@@ -51,6 +90,13 @@ class Organization(Durable, table=True):
|
||||
|
||||
|
||||
class Account(Durable, table=True):
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def _role_to_roles(cls, values):
|
||||
if isinstance(values, dict) and "roles" not in values and "role" in values:
|
||||
values = {**values, "roles": [values["role"]]}
|
||||
return values
|
||||
|
||||
id: uuid.UUID | None = Field(
|
||||
default_factory=uuid.uuid4,
|
||||
primary_key=True,
|
||||
@@ -95,17 +141,27 @@ class Account(Durable, table=True):
|
||||
nullable=False,
|
||||
description="The unique identifier of the organization strictly associated with this account.",
|
||||
)
|
||||
role: UserRole = Field(
|
||||
default=UserRole.USER,
|
||||
index=True,
|
||||
nullable=False,
|
||||
description="The specific role this account holds within its organization.",
|
||||
roles: List[UserRole] = Field(
|
||||
default_factory=lambda: [UserRole.USER],
|
||||
sa_column=Column(JSON, nullable=False, default=lambda: [UserRole.USER.value]),
|
||||
description="The roles this account holds within its organization.",
|
||||
)
|
||||
|
||||
organization: Organization = Relationship(back_populates="accounts")
|
||||
|
||||
@property
|
||||
def role(self) -> UserRole:
|
||||
return effective_role_for_roles(self.roles)
|
||||
|
||||
@role.setter
|
||||
def role(self, value: UserRole) -> None:
|
||||
self.roles = normalize_roles(value)
|
||||
|
||||
|
||||
class Secret(SQLModel, table=True):
|
||||
__table_args__ = (
|
||||
UniqueConstraint("account_id", "purpose", name="uq_secret_account_purpose"),
|
||||
)
|
||||
id: uuid.UUID | None = Field(
|
||||
default_factory=uuid.uuid4,
|
||||
primary_key=True,
|
||||
@@ -113,10 +169,16 @@ class Secret(SQLModel, table=True):
|
||||
)
|
||||
account_id: uuid.UUID = Field(
|
||||
foreign_key="account.id",
|
||||
unique=True, # Ensure that each account can have only one associated secret
|
||||
index=True,
|
||||
nullable=False,
|
||||
description="The unique identifier of the account associated with this secret.",
|
||||
)
|
||||
purpose: SecretPurpose = Field(
|
||||
default=SecretPurpose.LOGIN_OTK,
|
||||
index=True,
|
||||
nullable=False,
|
||||
description="The purpose of the secret, such as login OTK or password reset.",
|
||||
)
|
||||
secret_value: str = Field(
|
||||
index=False,
|
||||
nullable=False,
|
||||
@@ -127,6 +189,16 @@ class Secret(SQLModel, table=True):
|
||||
nullable=False,
|
||||
description="The timestamp indicating when the secret will expire.",
|
||||
)
|
||||
request_count: int = Field(
|
||||
default=0,
|
||||
nullable=False,
|
||||
description="The number of password reset requests in the current rate-limit window.",
|
||||
)
|
||||
request_window_started_at: datetime | None = Field(
|
||||
default=None,
|
||||
index=True,
|
||||
description="The start timestamp of the current password reset request window.",
|
||||
)
|
||||
|
||||
|
||||
class BaseTokenData(BaseModel):
|
||||
@@ -151,6 +223,17 @@ class IdTokenMetadata(BaseTokenData):
|
||||
|
||||
|
||||
class AccessTokenMetadata(BaseTokenData):
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def _effective_role_to_roles(cls, values):
|
||||
if (
|
||||
isinstance(values, dict)
|
||||
and "effective_roles" not in values
|
||||
and "effective_role" in values
|
||||
):
|
||||
values = {**values, "effective_roles": [values["effective_role"]]}
|
||||
return values
|
||||
|
||||
token_type: TokenType = Field(
|
||||
default=TokenType.ACCESS_TOKEN,
|
||||
const=True,
|
||||
@@ -166,6 +249,10 @@ class AccessTokenMetadata(BaseTokenData):
|
||||
default=UserRole.USER,
|
||||
description="The specific role this access token grants within its organization.",
|
||||
)
|
||||
effective_roles: List[UserRole] = Field(
|
||||
default_factory=lambda: [UserRole.USER],
|
||||
description="The roles this access token grants within its organization.",
|
||||
)
|
||||
effective_organization_id: uuid.UUID = Field(
|
||||
description="The unique identifier of the organization associated with this access token.",
|
||||
)
|
||||
@@ -186,6 +273,17 @@ class AccessToken(AccessTokenMetadata):
|
||||
|
||||
|
||||
class RefreshTokenMetadata(BaseTokenData):
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def _effective_role_to_roles(cls, values):
|
||||
if (
|
||||
isinstance(values, dict)
|
||||
and "effective_roles" not in values
|
||||
and "effective_role" in values
|
||||
):
|
||||
values = {**values, "effective_roles": [values["effective_role"]]}
|
||||
return values
|
||||
|
||||
token_type: TokenType = Field(
|
||||
default=TokenType.REFRESH_TOKEN,
|
||||
const=True,
|
||||
@@ -198,6 +296,10 @@ class RefreshTokenMetadata(BaseTokenData):
|
||||
default=UserRole.USER,
|
||||
description="The specific role this access token grants within its organization.",
|
||||
)
|
||||
effective_roles: List[UserRole] = Field(
|
||||
default_factory=lambda: [UserRole.USER],
|
||||
description="The roles this access token grants within its organization.",
|
||||
)
|
||||
effective_organization_id: uuid.UUID = Field(
|
||||
description="The unique identifier of the organization associated with this access token.",
|
||||
)
|
||||
|
||||
@@ -46,6 +46,46 @@ async def request_otk(
|
||||
return auth_service.request_otk(session=session, email=email, password=password)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/request-password-reset",
|
||||
summary="Request Password Reset",
|
||||
description="Request a one-time password reset link for the given email address.",
|
||||
operation_id="requestPasswordReset",
|
||||
responses={
|
||||
status.HTTP_200_OK: {"description": "Password reset requested successfully."}
|
||||
},
|
||||
)
|
||||
async def request_password_reset(
|
||||
session: SessionDep,
|
||||
email: Annotated[str, Body(embed=True, description="User's email address")],
|
||||
):
|
||||
return auth_service.request_password_reset(session=session, email=email)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/reset-password",
|
||||
summary="Reset Password",
|
||||
description="Reset the user's password using a one-time password reset token.",
|
||||
operation_id="resetPassword",
|
||||
responses={status.HTTP_200_OK: {"description": "Password reset successfully."}},
|
||||
)
|
||||
async def reset_password(
|
||||
session: SessionDep,
|
||||
reset_token: Annotated[
|
||||
str, Body(description="Password reset token from the reset link")
|
||||
],
|
||||
new_password: Annotated[
|
||||
str,
|
||||
Body(description="New password", min_length=8, example="NewPassword123"),
|
||||
],
|
||||
):
|
||||
return auth_service.reset_password(
|
||||
session=session,
|
||||
reset_token=reset_token,
|
||||
new_password=new_password,
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/login",
|
||||
summary="Login with One-Time Key",
|
||||
|
||||
@@ -11,6 +11,9 @@ from argon2 import PasswordHasher
|
||||
from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError
|
||||
from fastapi import Cookie, Depends, HTTPException, Response, status
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
from sqlmodel import Session, func, select
|
||||
|
||||
from inse.auth.email_service import send_email
|
||||
from inse.auth.model import (
|
||||
AccessResponse,
|
||||
AccessToken,
|
||||
@@ -22,23 +25,28 @@ from inse.auth.model import (
|
||||
OtkResponse,
|
||||
RefreshTokenMetadata,
|
||||
Secret,
|
||||
SecretPurpose,
|
||||
TokenType,
|
||||
UserRole,
|
||||
effective_role_for_roles,
|
||||
normalize_roles,
|
||||
)
|
||||
from inse.config import get_settings
|
||||
from inse.database import get_session
|
||||
from sqlmodel import Session, select, func
|
||||
from inse.auth.email_service import send_email
|
||||
|
||||
ID_TOKEN_EXPIRATION_MINUTES = 30 * 24 * 60 # 30 days
|
||||
REFRESH_TOKEN_EXPIRATION_MINUTES = 1 * 24 * 60 # 1 day
|
||||
ACCESS_TOKEN_EXPIRATION_MINUTES = 30 # 30 minutes
|
||||
|
||||
OTK_EXPIRATION_MINUTES = 15 # 15 minutes
|
||||
PASSWORD_RESET_EXPIRATION_MINUTES = 5 # 5 minutes
|
||||
PASSWORD_RESET_RATE_LIMIT_WINDOW_MINUTES = 5 # 5 minutes
|
||||
PASSWORD_RESET_MAX_REQUESTS_PER_WINDOW = 3 # 3 minutes
|
||||
|
||||
REAL_ACCOUNT_ID_KEY = "real_account_id"
|
||||
EFFECTIVE_ACCOUNT_ID_KEY = "effective_account_id"
|
||||
EFFECTIVE_ROLE_KEY = "effective_role"
|
||||
EFFECTIVE_ROLES_KEY = "effective_roles"
|
||||
EFFECTIVE_ORGANIZATION_ID_KEY = "effective_organization_id"
|
||||
EPOCH_KEY = "epoch"
|
||||
USER_FINGERPRINT_HASH_KEY = "user_fingerprint_hash"
|
||||
@@ -105,14 +113,16 @@ def create_predefined_accounts(session: Session, file_path: str):
|
||||
session.add(organization)
|
||||
for account_data in data.get("accounts", []):
|
||||
organization_id = uuid.UUID(account_data["organization_id"])
|
||||
role = UserRole(account_data["role"])
|
||||
roles = normalize_roles(
|
||||
account_data.get("roles", account_data.get("role"))
|
||||
)
|
||||
email = account_data["email"]
|
||||
password_hash = _hash_password(account_data["password"])
|
||||
account = Account(
|
||||
email=email,
|
||||
name=account_data["name"],
|
||||
organization_id=organization_id,
|
||||
role=role,
|
||||
roles=roles,
|
||||
password_hash=password_hash,
|
||||
epoch=0,
|
||||
)
|
||||
@@ -160,7 +170,32 @@ def _verify_password(password: str, password_hash: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def request_otk(session: Session, email: str, password: str) -> OtkResponse:
|
||||
def _hash_reset_token(reset_token: str) -> str:
|
||||
"""Hashes a high-entropy password reset token for storage.
|
||||
|
||||
Args:
|
||||
reset_token (str): The raw reset token sent to the user.
|
||||
|
||||
Returns:
|
||||
str: SHA-256 hash of the reset token.
|
||||
"""
|
||||
return hashlib.sha256(reset_token.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def _build_password_reset_link(reset_token: str) -> str:
|
||||
"""Builds the password reset link that will be sent to the user.
|
||||
|
||||
Args:
|
||||
reset_token (str): The raw reset token to include in the link.
|
||||
|
||||
Returns:
|
||||
str: The full password reset link.
|
||||
"""
|
||||
separator = "&" if "?" in settings.password_reset_url else "?"
|
||||
return f"{settings.password_reset_url}{separator}token={reset_token}"
|
||||
|
||||
|
||||
def request_otk(session: Session, email: str, password: str):
|
||||
"""Requests a one-time key (OTK) for authentication using email and password. Validates the provided credentials and generates a one-time key if valid.
|
||||
|
||||
Args:
|
||||
@@ -211,7 +246,12 @@ def request_otk(session: Session, email: str, password: str) -> OtkResponse:
|
||||
otk_code = f"{secrets.randbelow(1_000_000):06d}"
|
||||
print(otk_code)
|
||||
|
||||
secret = session.exec(select(Secret).where(Secret.account_id == account.id)).first()
|
||||
secret = session.exec(
|
||||
select(Secret).where(
|
||||
Secret.account_id == account.id,
|
||||
Secret.purpose == SecretPurpose.LOGIN_OTK,
|
||||
)
|
||||
).first()
|
||||
|
||||
expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
|
||||
minutes=OTK_EXPIRATION_MINUTES
|
||||
@@ -220,6 +260,7 @@ def request_otk(session: Session, email: str, password: str) -> OtkResponse:
|
||||
if secret is None:
|
||||
secret = Secret(
|
||||
account_id=account.id,
|
||||
purpose=SecretPurpose.LOGIN_OTK,
|
||||
secret_value=otk_code,
|
||||
expires_at=expires_at,
|
||||
)
|
||||
@@ -251,6 +292,210 @@ def request_otk(session: Session, email: str, password: str) -> OtkResponse:
|
||||
return OtkResponse(status="success", account_id=account.id)
|
||||
|
||||
|
||||
def request_password_reset(session: Session, email: str) -> Dict[str, Any]:
|
||||
"""Requests a one-time password reset link for the given email address.
|
||||
|
||||
For security reasons, this function always returns a successful response and
|
||||
does not reveal whether the email address belongs to an active account.
|
||||
"""
|
||||
email = email.lower().strip()
|
||||
now = datetime.datetime.now(datetime.timezone.utc)
|
||||
|
||||
account = session.exec(
|
||||
select(Account).where(
|
||||
Account.email == email,
|
||||
Account.deleted == False, # noqa: E712
|
||||
)
|
||||
).first()
|
||||
|
||||
if account is None or account.deleted or account.id is None:
|
||||
logger.info("Password reset requested for unknown email %s", email)
|
||||
return {
|
||||
"status": "ok",
|
||||
"reset_link_created": False,
|
||||
"rate_limited": False,
|
||||
}
|
||||
|
||||
secret = session.exec(
|
||||
select(Secret).where(
|
||||
Secret.account_id == account.id,
|
||||
Secret.purpose == SecretPurpose.PASSWORD_RESET,
|
||||
)
|
||||
).first()
|
||||
|
||||
if secret is not None:
|
||||
if secret.request_window_started_at is not None:
|
||||
window_started_at = secret.request_window_started_at
|
||||
if getattr(window_started_at, "tzinfo", None) is None:
|
||||
window_started_at = window_started_at.replace(
|
||||
tzinfo=datetime.timezone.utc
|
||||
)
|
||||
|
||||
window_ends_at = window_started_at + datetime.timedelta(
|
||||
minutes=PASSWORD_RESET_RATE_LIMIT_WINDOW_MINUTES
|
||||
)
|
||||
|
||||
if window_ends_at > now:
|
||||
if secret.request_count >= PASSWORD_RESET_MAX_REQUESTS_PER_WINDOW:
|
||||
retry_after_seconds = max(
|
||||
0,
|
||||
int((window_ends_at - now).total_seconds()),
|
||||
)
|
||||
|
||||
logger.info(
|
||||
"Password reset request rate-limited for account %s.",
|
||||
account.id,
|
||||
)
|
||||
return {
|
||||
"status": "ok",
|
||||
"reset_link_created": False,
|
||||
"rate_limited": True,
|
||||
"retry_after_seconds": retry_after_seconds,
|
||||
}
|
||||
else:
|
||||
secret.request_count = 0
|
||||
secret.request_window_started_at = now
|
||||
else:
|
||||
secret.request_count = 0
|
||||
secret.request_window_started_at = now
|
||||
|
||||
reset_token = secrets.token_urlsafe(32)
|
||||
reset_token_hash = _hash_reset_token(reset_token)
|
||||
|
||||
expires_at = now + datetime.timedelta(minutes=PASSWORD_RESET_EXPIRATION_MINUTES)
|
||||
|
||||
if secret is None:
|
||||
secret = Secret(
|
||||
account_id=account.id,
|
||||
purpose=SecretPurpose.PASSWORD_RESET,
|
||||
secret_value=reset_token_hash,
|
||||
expires_at=expires_at,
|
||||
request_count=1,
|
||||
request_window_started_at=now,
|
||||
)
|
||||
session.add(secret)
|
||||
else:
|
||||
secret.secret_value = reset_token_hash
|
||||
secret.expires_at = expires_at
|
||||
secret.request_count += 1
|
||||
|
||||
if secret.request_window_started_at is None:
|
||||
secret.request_window_started_at = now
|
||||
|
||||
session.commit()
|
||||
|
||||
reset_link = _build_password_reset_link(reset_token)
|
||||
|
||||
if settings.send_password_reset_email:
|
||||
try:
|
||||
send_email(
|
||||
recipient=account.email,
|
||||
subject="Reset your SmartGUIDE password",
|
||||
body=(
|
||||
"Use the following link to reset your SmartGUIDE password:\n"
|
||||
f"{reset_link}\n\n"
|
||||
f"This link expires in {PASSWORD_RESET_EXPIRATION_MINUTES} minutes."
|
||||
),
|
||||
smtp_server=settings.smtp_server,
|
||||
smtp_port=settings.smtp_port,
|
||||
sender=settings.smtp_sender,
|
||||
username=settings.smtp_username,
|
||||
password=settings.smtp_password,
|
||||
use_tls=settings.smtp_use_tls,
|
||||
)
|
||||
logger.info("Sent password reset email for account %s", account.id)
|
||||
except Exception:
|
||||
if settings.environment == "dev":
|
||||
logger.exception(
|
||||
"Failed to send password reset email for account %s. "
|
||||
"Falling back to console reset link.",
|
||||
account.id,
|
||||
)
|
||||
logger.info(
|
||||
"Password reset link for account %s: %s",
|
||||
account.id,
|
||||
reset_link,
|
||||
)
|
||||
else:
|
||||
raise
|
||||
elif settings.environment == "dev":
|
||||
logger.info("Password reset link for account %s: %s", account.id, reset_link)
|
||||
else:
|
||||
logger.info("Password reset token generated for account %s", account.id)
|
||||
|
||||
return {
|
||||
"status": "ok",
|
||||
"reset_link_created": True,
|
||||
"rate_limited": False,
|
||||
}
|
||||
|
||||
|
||||
def reset_password(
|
||||
session: Session,
|
||||
reset_token: str,
|
||||
new_password: str,
|
||||
) -> Dict[str, str]:
|
||||
"""Resets an account password using a one-time password reset token.
|
||||
|
||||
Args:
|
||||
session (Session): The database session used to query the account and secret.
|
||||
reset_token (str): The raw reset token from the password reset link.
|
||||
new_password (str): The new password to store for the account.
|
||||
|
||||
Raises:
|
||||
HTTPException: If the reset token is invalid or expired.
|
||||
|
||||
Returns:
|
||||
Dict[str, str]: A status response.
|
||||
"""
|
||||
now = datetime.datetime.now(datetime.timezone.utc)
|
||||
reset_token_hash = _hash_reset_token(reset_token.strip())
|
||||
|
||||
secret = session.exec(
|
||||
select(Secret).where(
|
||||
Secret.purpose == SecretPurpose.PASSWORD_RESET,
|
||||
Secret.secret_value == reset_token_hash,
|
||||
)
|
||||
).first()
|
||||
|
||||
if secret is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid or expired password reset token",
|
||||
)
|
||||
|
||||
secret_expires = secret.expires_at
|
||||
if getattr(secret_expires, "tzinfo", None) is None:
|
||||
secret_expires = secret_expires.replace(tzinfo=datetime.timezone.utc)
|
||||
|
||||
if secret_expires <= now:
|
||||
session.delete(secret)
|
||||
session.commit()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid or expired password reset token",
|
||||
)
|
||||
|
||||
account = session.get(Account, secret.account_id)
|
||||
|
||||
if account is None or account.deleted or account.id is None:
|
||||
session.delete(secret)
|
||||
session.commit()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid or expired password reset token",
|
||||
)
|
||||
|
||||
account.password_hash = _hash_password(new_password)
|
||||
account.epoch += 1
|
||||
|
||||
session.add(account)
|
||||
session.delete(secret)
|
||||
session.commit()
|
||||
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
def login(
|
||||
session: Session, response: Response, account_id: uuid.UUID, email_code: str
|
||||
) -> LoginResponse:
|
||||
@@ -274,6 +519,7 @@ def login(
|
||||
secret = session.exec(
|
||||
select(Secret).where(
|
||||
Secret.account_id == account_id,
|
||||
Secret.purpose == SecretPurpose.LOGIN_OTK,
|
||||
Secret.secret_value == email_code,
|
||||
# Validating the code and ensuring it matches the account ID
|
||||
)
|
||||
@@ -368,6 +614,11 @@ def _get_current_user_access_token_payload(
|
||||
),
|
||||
epoch=access_token_payload[EPOCH_KEY],
|
||||
effective_role=UserRole(access_token_payload[EFFECTIVE_ROLE_KEY]),
|
||||
effective_roles=normalize_roles(
|
||||
access_token_payload.get(
|
||||
EFFECTIVE_ROLES_KEY, access_token_payload[EFFECTIVE_ROLE_KEY]
|
||||
)
|
||||
),
|
||||
effective_organization_id=uuid.UUID(
|
||||
access_token_payload[EFFECTIVE_ORGANIZATION_ID_KEY]
|
||||
),
|
||||
@@ -408,6 +659,11 @@ def _get_current_user_refresh_token_payload(
|
||||
),
|
||||
epoch=refresh_token_payload[EPOCH_KEY],
|
||||
effective_role=UserRole(refresh_token_payload[EFFECTIVE_ROLE_KEY]),
|
||||
effective_roles=normalize_roles(
|
||||
refresh_token_payload.get(
|
||||
EFFECTIVE_ROLES_KEY, refresh_token_payload[EFFECTIVE_ROLE_KEY]
|
||||
)
|
||||
),
|
||||
effective_organization_id=uuid.UUID(
|
||||
refresh_token_payload[EFFECTIVE_ORGANIZATION_ID_KEY]
|
||||
),
|
||||
@@ -487,7 +743,7 @@ def _get_account_epoch(
|
||||
return account.epoch
|
||||
|
||||
|
||||
def _get_account_role(session: Session, account_id: uuid.UUID) -> UserRole:
|
||||
def _get_account_roles(session: Session, account_id: uuid.UUID) -> list[UserRole]:
|
||||
"""Retrieves the role for the given account ID.
|
||||
|
||||
Args:
|
||||
@@ -495,14 +751,14 @@ def _get_account_role(session: Session, account_id: uuid.UUID) -> UserRole:
|
||||
account_id (uuid.UUID): The unique identifier of the account for which to retrieve the role.
|
||||
|
||||
Returns:
|
||||
UserRole: The role associated with the given account ID.
|
||||
list[UserRole]: The roles associated with the given account ID.
|
||||
"""
|
||||
account = session.get(Account, account_id)
|
||||
|
||||
if not account or account.deleted or not account.activated or account.id is None:
|
||||
raise AccountNotFoundException
|
||||
|
||||
return account.role
|
||||
return normalize_roles(account.roles)
|
||||
|
||||
|
||||
def _get_account_organization(session: Session, account_id: uuid.UUID) -> uuid.UUID:
|
||||
@@ -553,13 +809,16 @@ def _is_valid_impersonation(
|
||||
):
|
||||
raise AccountNotFoundException
|
||||
|
||||
if real_account.role == UserRole.SUPER_ADMIN:
|
||||
real_account_role = effective_role_for_roles(real_account.roles)
|
||||
effective_account_role = effective_role_for_roles(effective_account.roles)
|
||||
|
||||
if real_account_role == UserRole.SUPER_ADMIN:
|
||||
return True # Super admins can impersonate any account
|
||||
|
||||
if real_account.organization_id != effective_account.organization_id:
|
||||
return False # Cannot impersonate accounts from different organizations
|
||||
|
||||
if real_account.role == UserRole.ADMIN and effective_account.role in [
|
||||
if real_account_role == UserRole.ADMIN and effective_account_role in [
|
||||
UserRole.MANAGER,
|
||||
UserRole.USER,
|
||||
]:
|
||||
@@ -606,7 +865,8 @@ def get_access_token(
|
||||
detail="Impersonation not allowed",
|
||||
)
|
||||
|
||||
role = _get_account_role(session=session, account_id=effective_account_id)
|
||||
roles = _get_account_roles(session=session, account_id=effective_account_id)
|
||||
role = effective_role_for_roles(roles)
|
||||
epoch = _get_account_epoch(account_id=effective_account_id, session=session)
|
||||
organization_id = _get_account_organization(
|
||||
session=session, account_id=effective_account_id
|
||||
@@ -621,6 +881,7 @@ def get_access_token(
|
||||
effective_organization_id=organization_id,
|
||||
epoch=epoch,
|
||||
user_fingerprint_hash=user_fingerprint_hash,
|
||||
effective_roles=roles,
|
||||
)
|
||||
_set_refresh_token(
|
||||
response=response,
|
||||
@@ -629,6 +890,7 @@ def get_access_token(
|
||||
effective_role=role,
|
||||
effective_organization_id=organization_id,
|
||||
epoch=epoch,
|
||||
effective_roles=roles,
|
||||
)
|
||||
return AccessResponse(
|
||||
access_token=access_token,
|
||||
@@ -733,6 +995,7 @@ def refresh_access_token(
|
||||
effective_organization_id=refresh_token.effective_organization_id,
|
||||
epoch=refresh_token.epoch,
|
||||
user_fingerprint_hash=user_fingerprint_hash,
|
||||
effective_roles=refresh_token.effective_roles,
|
||||
)
|
||||
|
||||
|
||||
@@ -779,6 +1042,7 @@ def _set_refresh_token(
|
||||
effective_role: UserRole,
|
||||
effective_organization_id: uuid.UUID,
|
||||
epoch: int,
|
||||
effective_roles: list[UserRole] | None = None,
|
||||
) -> RefreshTokenMetadata:
|
||||
"""Builds a refresh token for the specified account IDs, role, organization ID, epoch, and fingerprint hash.
|
||||
|
||||
@@ -797,10 +1061,12 @@ def _set_refresh_token(
|
||||
expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
|
||||
minutes=REFRESH_TOKEN_EXPIRATION_MINUTES
|
||||
)
|
||||
effective_roles = normalize_roles(effective_roles or effective_role)
|
||||
payload = {
|
||||
REAL_ACCOUNT_ID_KEY: str(real_account_id),
|
||||
EFFECTIVE_ACCOUNT_ID_KEY: str(effective_account_id),
|
||||
EFFECTIVE_ROLE_KEY: effective_role.value,
|
||||
EFFECTIVE_ROLES_KEY: [role.value for role in effective_roles],
|
||||
EFFECTIVE_ORGANIZATION_ID_KEY: str(effective_organization_id),
|
||||
EPOCH_KEY: epoch,
|
||||
}
|
||||
@@ -817,6 +1083,7 @@ def _set_refresh_token(
|
||||
expires_at=expires_at,
|
||||
epoch=epoch,
|
||||
effective_role=effective_role,
|
||||
effective_roles=effective_roles,
|
||||
effective_organization_id=effective_organization_id,
|
||||
)
|
||||
|
||||
@@ -828,6 +1095,7 @@ def _build_access_token(
|
||||
effective_organization_id: uuid.UUID,
|
||||
epoch: int,
|
||||
user_fingerprint_hash: str,
|
||||
effective_roles: list[UserRole] | None = None,
|
||||
) -> AccessToken:
|
||||
"""Builds an access token for the specified account IDs, role, organization ID, epoch, and fingerprint hash.
|
||||
|
||||
@@ -846,10 +1114,12 @@ def _build_access_token(
|
||||
expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
|
||||
minutes=ACCESS_TOKEN_EXPIRATION_MINUTES
|
||||
)
|
||||
effective_roles = normalize_roles(effective_roles or effective_role)
|
||||
payload = {
|
||||
REAL_ACCOUNT_ID_KEY: str(real_account_id),
|
||||
EFFECTIVE_ACCOUNT_ID_KEY: str(effective_account_id),
|
||||
EFFECTIVE_ROLE_KEY: effective_role.value,
|
||||
EFFECTIVE_ROLES_KEY: [role.value for role in effective_roles],
|
||||
EFFECTIVE_ORGANIZATION_ID_KEY: str(effective_organization_id),
|
||||
EPOCH_KEY: epoch,
|
||||
USER_FINGERPRINT_HASH_KEY: user_fingerprint_hash,
|
||||
@@ -867,6 +1137,7 @@ def _build_access_token(
|
||||
expires_at=expires_at,
|
||||
epoch=epoch,
|
||||
effective_role=effective_role,
|
||||
effective_roles=effective_roles,
|
||||
effective_organization_id=effective_organization_id,
|
||||
user_fingerprint_hash=user_fingerprint_hash,
|
||||
raw_token=raw_token,
|
||||
|
||||
@@ -14,6 +14,7 @@ from inse.auth.model import (
|
||||
Account,
|
||||
Organization,
|
||||
Secret,
|
||||
SecretPurpose,
|
||||
AccessToken,
|
||||
IdTokenMetadata,
|
||||
AccessTokenMetadata,
|
||||
@@ -98,7 +99,10 @@ def test_request_otk_and_login_flow(in_memory_session, settings_backup):
|
||||
assert resp.account_id == acc.id
|
||||
|
||||
secret = in_memory_session.exec(
|
||||
select(Secret).where(Secret.account_id == acc.id)
|
||||
select(Secret).where(
|
||||
Secret.account_id == acc.id,
|
||||
Secret.purpose == SecretPurpose.LOGIN_OTK,
|
||||
)
|
||||
).first()
|
||||
assert secret is not None
|
||||
|
||||
@@ -281,7 +285,12 @@ def test_login_with_expired_secret(in_memory_session, settings_backup):
|
||||
assert acc.id is not None
|
||||
|
||||
expired_at = _dt.datetime.now(_dt.timezone.utc) - timedelta(minutes=10)
|
||||
secret = Secret(account_id=acc.id, secret_value="000000", expires_at=expired_at)
|
||||
secret = Secret(
|
||||
account_id=acc.id,
|
||||
purpose=SecretPurpose.LOGIN_OTK,
|
||||
secret_value="000000",
|
||||
expires_at=expired_at,
|
||||
)
|
||||
in_memory_session.add(secret)
|
||||
in_memory_session.commit()
|
||||
|
||||
@@ -426,14 +435,20 @@ def test_otk_regeneration_and_reuse(in_memory_session, settings_backup):
|
||||
|
||||
auth_service.request_otk(in_memory_session, email, password)
|
||||
secret1 = in_memory_session.exec(
|
||||
select(Secret).where(Secret.account_id == acc.id)
|
||||
select(Secret).where(
|
||||
Secret.account_id == acc.id,
|
||||
Secret.purpose == SecretPurpose.LOGIN_OTK,
|
||||
)
|
||||
).first()
|
||||
assert secret1 is not None
|
||||
first_value = secret1.secret_value
|
||||
|
||||
auth_service.request_otk(in_memory_session, email, password)
|
||||
secret2 = in_memory_session.exec(
|
||||
select(Secret).where(Secret.account_id == acc.id)
|
||||
select(Secret).where(
|
||||
Secret.account_id == acc.id,
|
||||
Secret.purpose == SecretPurpose.LOGIN_OTK,
|
||||
)
|
||||
).first()
|
||||
|
||||
assert secret2 is not None
|
||||
@@ -460,13 +475,19 @@ def test_otk_deleted_after_login(in_memory_session, settings_backup):
|
||||
|
||||
auth_service.request_otk(in_memory_session, email, password)
|
||||
secret = in_memory_session.exec(
|
||||
select(Secret).where(Secret.account_id == acc.id)
|
||||
select(Secret).where(
|
||||
Secret.account_id == acc.id,
|
||||
Secret.purpose == SecretPurpose.LOGIN_OTK,
|
||||
)
|
||||
).first()
|
||||
assert secret is not None
|
||||
|
||||
auth_service.login(in_memory_session, Response(), acc.id, secret.secret_value)
|
||||
post = in_memory_session.exec(
|
||||
select(Secret).where(Secret.account_id == acc.id)
|
||||
select(Secret).where(
|
||||
Secret.account_id == acc.id,
|
||||
Secret.purpose == SecretPurpose.LOGIN_OTK,
|
||||
)
|
||||
).first()
|
||||
assert post is None
|
||||
|
||||
@@ -551,3 +572,180 @@ def test_get_account_epoch_not_found(in_memory_session):
|
||||
random_id = uuid.uuid4()
|
||||
with pytest.raises(Exception):
|
||||
auth_service._get_account_epoch(in_memory_session, random_id)
|
||||
|
||||
|
||||
|
||||
def test_request_password_reset_creates_secret(in_memory_session, settings_backup):
|
||||
email = "reset@example.com"
|
||||
password = "oldpw123"
|
||||
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||
assert acc.id is not None
|
||||
|
||||
result = auth_service.request_password_reset(in_memory_session, email)
|
||||
assert result["status"] == "ok"
|
||||
|
||||
secret = in_memory_session.exec(
|
||||
select(Secret).where(
|
||||
Secret.account_id == acc.id,
|
||||
Secret.purpose == SecretPurpose.PASSWORD_RESET,
|
||||
)
|
||||
).first()
|
||||
|
||||
assert secret is not None
|
||||
assert secret.secret_value is not None
|
||||
assert secret.secret_value != ""
|
||||
assert secret.secret_value != password
|
||||
|
||||
|
||||
def test_request_password_reset_unknown_email_is_safe(
|
||||
in_memory_session, settings_backup, monkeypatch
|
||||
):
|
||||
sent_emails = []
|
||||
|
||||
def fake_send_email(**kwargs):
|
||||
sent_emails.append(kwargs)
|
||||
|
||||
monkeypatch.setattr(auth_service, "send_email", fake_send_email)
|
||||
config_module.settings.send_password_reset_email = True
|
||||
|
||||
result = auth_service.request_password_reset(
|
||||
in_memory_session, "missing@example.com"
|
||||
)
|
||||
|
||||
assert result["status"] == "ok"
|
||||
assert sent_emails == []
|
||||
|
||||
|
||||
def test_request_password_reset_sends_email(
|
||||
in_memory_session, settings_backup, monkeypatch
|
||||
):
|
||||
email = "mail-reset@example.com"
|
||||
password = "oldpw123"
|
||||
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||
assert acc.id is not None
|
||||
|
||||
sent_emails = []
|
||||
|
||||
def fake_send_email(**kwargs):
|
||||
sent_emails.append(kwargs)
|
||||
|
||||
monkeypatch.setattr(auth_service, "send_email", fake_send_email)
|
||||
config_module.settings.send_password_reset_email = True
|
||||
config_module.settings.password_reset_url = "http://localhost/reset-password"
|
||||
|
||||
result = auth_service.request_password_reset(in_memory_session, email)
|
||||
|
||||
assert result["status"] == "ok"
|
||||
assert len(sent_emails) == 1
|
||||
assert sent_emails[0]["recipient"] == email
|
||||
assert "token=" in sent_emails[0]["body"]
|
||||
|
||||
|
||||
def test_reset_password_changes_password_and_increments_epoch(in_memory_session):
|
||||
email = "do-reset@example.com"
|
||||
password = "oldpw123"
|
||||
new_password = "NewPassword123"
|
||||
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||
assert acc.id is not None
|
||||
|
||||
reset_token = "valid-reset-token"
|
||||
secret = Secret(
|
||||
account_id=acc.id,
|
||||
purpose=SecretPurpose.PASSWORD_RESET,
|
||||
secret_value=auth_service._hash_reset_token(reset_token),
|
||||
expires_at=_dt.datetime.now(_dt.timezone.utc) + timedelta(minutes=5),
|
||||
)
|
||||
in_memory_session.add(secret)
|
||||
in_memory_session.commit()
|
||||
|
||||
old_epoch = acc.epoch
|
||||
|
||||
result = auth_service.reset_password(
|
||||
in_memory_session,
|
||||
reset_token=reset_token,
|
||||
new_password=new_password,
|
||||
)
|
||||
|
||||
assert result["status"] == "ok"
|
||||
in_memory_session.refresh(acc)
|
||||
assert auth_service._verify_password(new_password, acc.password_hash)
|
||||
assert acc.epoch == old_epoch + 1
|
||||
|
||||
deleted_secret = in_memory_session.exec(
|
||||
select(Secret).where(
|
||||
Secret.account_id == acc.id,
|
||||
Secret.purpose == SecretPurpose.PASSWORD_RESET,
|
||||
)
|
||||
).first()
|
||||
assert deleted_secret is None
|
||||
|
||||
|
||||
def test_reset_password_rejects_reused_token(in_memory_session):
|
||||
email = "reuse-reset@example.com"
|
||||
password = "oldpw123"
|
||||
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||
assert acc.id is not None
|
||||
|
||||
reset_token = "single-use-token"
|
||||
secret = Secret(
|
||||
account_id=acc.id,
|
||||
purpose=SecretPurpose.PASSWORD_RESET,
|
||||
secret_value=auth_service._hash_reset_token(reset_token),
|
||||
expires_at=_dt.datetime.now(_dt.timezone.utc) + timedelta(minutes=5),
|
||||
)
|
||||
in_memory_session.add(secret)
|
||||
in_memory_session.commit()
|
||||
|
||||
auth_service.reset_password(
|
||||
in_memory_session,
|
||||
reset_token=reset_token,
|
||||
new_password="NewPassword123",
|
||||
)
|
||||
|
||||
with pytest.raises(HTTPException):
|
||||
auth_service.reset_password(
|
||||
in_memory_session,
|
||||
reset_token=reset_token,
|
||||
new_password="AnotherPassword123",
|
||||
)
|
||||
|
||||
|
||||
def test_reset_password_rejects_invalid_token(in_memory_session):
|
||||
with pytest.raises(HTTPException):
|
||||
auth_service.reset_password(
|
||||
in_memory_session,
|
||||
reset_token="invalid-token",
|
||||
new_password="NewPassword123",
|
||||
)
|
||||
|
||||
|
||||
def test_reset_password_rejects_expired_token(in_memory_session):
|
||||
email = "expired-reset@example.com"
|
||||
password = "oldpw123"
|
||||
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||
assert acc.id is not None
|
||||
|
||||
reset_token = "expired-token"
|
||||
secret = Secret(
|
||||
account_id=acc.id,
|
||||
purpose=SecretPurpose.PASSWORD_RESET,
|
||||
secret_value=auth_service._hash_reset_token(reset_token),
|
||||
expires_at=_dt.datetime.now(_dt.timezone.utc) - timedelta(minutes=1),
|
||||
)
|
||||
in_memory_session.add(secret)
|
||||
in_memory_session.commit()
|
||||
|
||||
with pytest.raises(HTTPException):
|
||||
auth_service.reset_password(
|
||||
in_memory_session,
|
||||
reset_token=reset_token,
|
||||
new_password="NewPassword123",
|
||||
)
|
||||
|
||||
deleted_secret = in_memory_session.exec(
|
||||
select(Secret).where(
|
||||
Secret.account_id == acc.id,
|
||||
Secret.purpose == SecretPurpose.PASSWORD_RESET,
|
||||
)
|
||||
).first()
|
||||
assert deleted_secret is None
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""User bookmark feature."""
|
||||
@@ -0,0 +1,36 @@
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from pydantic import BaseModel, Field as PydanticField
|
||||
from sqlalchemy import UniqueConstraint
|
||||
from sqlmodel import Field, SQLModel
|
||||
|
||||
|
||||
class PersonBookmark(SQLModel, table=True):
|
||||
__tablename__ = "person_bookmark"
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
"account_id", "person_id", name="uq_person_bookmark_account_person"
|
||||
),
|
||||
)
|
||||
|
||||
id: uuid.UUID = Field(default_factory=uuid.uuid4, primary_key=True)
|
||||
account_id: uuid.UUID = Field(
|
||||
foreign_key="account.id", nullable=False, index=True
|
||||
)
|
||||
person_id: str = Field(nullable=False, index=True)
|
||||
person_name: str | None = Field(default=None)
|
||||
created_at: datetime = Field(
|
||||
default_factory=lambda: datetime.now(timezone.utc), nullable=False, index=True
|
||||
)
|
||||
|
||||
|
||||
class CreatePersonBookmark(BaseModel):
|
||||
person_name: str | None = PydanticField(default=None, max_length=500)
|
||||
|
||||
|
||||
class PersonBookmarkResponse(BaseModel):
|
||||
person_id: str
|
||||
person_name: str | None
|
||||
created_at: datetime
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
from fastapi import APIRouter, Response, status
|
||||
|
||||
from inse.auth import service as auth_service
|
||||
from inse.auth.model import AccessTokenMetadata
|
||||
from inse.database import SessionDep
|
||||
|
||||
from . import service
|
||||
from .model import CreatePersonBookmark, PersonBookmarkResponse
|
||||
|
||||
|
||||
router = APIRouter(prefix="/api/bookmarks", tags=["Bookmarks"])
|
||||
|
||||
|
||||
@router.get("/persons", operation_id="listPersonBookmarks")
|
||||
def list_person_bookmarks(
|
||||
session: SessionDep,
|
||||
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> list[PersonBookmarkResponse]:
|
||||
return service.list_person_bookmarks(session, access_token.effective_account_id)
|
||||
|
||||
|
||||
@router.put("/persons/{person_id}", operation_id="bookmarkPerson")
|
||||
def bookmark_person(
|
||||
person_id: str,
|
||||
payload: CreatePersonBookmark,
|
||||
session: SessionDep,
|
||||
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> PersonBookmarkResponse:
|
||||
return service.create_person_bookmark(
|
||||
session, access_token.effective_account_id, person_id, payload
|
||||
)
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/persons/{person_id}",
|
||||
operation_id="removePersonBookmark",
|
||||
status_code=status.HTTP_204_NO_CONTENT,
|
||||
)
|
||||
def remove_person_bookmark(
|
||||
person_id: str,
|
||||
session: SessionDep,
|
||||
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> Response:
|
||||
service.delete_person_bookmark(
|
||||
session, access_token.effective_account_id, person_id
|
||||
)
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
@@ -0,0 +1,81 @@
|
||||
import uuid
|
||||
|
||||
from fastapi import HTTPException, status
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from .model import CreatePersonBookmark, PersonBookmark, PersonBookmarkResponse
|
||||
|
||||
|
||||
def normalize_person_id(person_id: str) -> str:
|
||||
normalized = person_id.strip().rstrip("/").split("/")[-1]
|
||||
if not normalized:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="A person ID is required.",
|
||||
)
|
||||
return normalized
|
||||
|
||||
|
||||
def list_person_bookmarks(
|
||||
session: Session, account_id: uuid.UUID
|
||||
) -> list[PersonBookmarkResponse]:
|
||||
bookmarks = session.exec(
|
||||
select(PersonBookmark)
|
||||
.where(PersonBookmark.account_id == account_id)
|
||||
.order_by(PersonBookmark.created_at.desc())
|
||||
).all()
|
||||
return [
|
||||
PersonBookmarkResponse(
|
||||
person_id=bookmark.person_id,
|
||||
person_name=bookmark.person_name,
|
||||
created_at=bookmark.created_at,
|
||||
)
|
||||
for bookmark in bookmarks
|
||||
]
|
||||
|
||||
|
||||
def create_person_bookmark(
|
||||
session: Session,
|
||||
account_id: uuid.UUID,
|
||||
person_id: str,
|
||||
payload: CreatePersonBookmark,
|
||||
) -> PersonBookmarkResponse:
|
||||
normalized_id = normalize_person_id(person_id)
|
||||
bookmark = session.exec(
|
||||
select(PersonBookmark).where(
|
||||
PersonBookmark.account_id == account_id,
|
||||
PersonBookmark.person_id == normalized_id,
|
||||
)
|
||||
).first()
|
||||
if bookmark is None:
|
||||
bookmark = PersonBookmark(
|
||||
account_id=account_id,
|
||||
person_id=normalized_id,
|
||||
person_name=payload.person_name,
|
||||
)
|
||||
session.add(bookmark)
|
||||
elif payload.person_name:
|
||||
bookmark.person_name = payload.person_name
|
||||
|
||||
session.commit()
|
||||
session.refresh(bookmark)
|
||||
return PersonBookmarkResponse(
|
||||
person_id=bookmark.person_id,
|
||||
person_name=bookmark.person_name,
|
||||
created_at=bookmark.created_at,
|
||||
)
|
||||
|
||||
|
||||
def delete_person_bookmark(
|
||||
session: Session, account_id: uuid.UUID, person_id: str
|
||||
) -> None:
|
||||
normalized_id = normalize_person_id(person_id)
|
||||
bookmark = session.exec(
|
||||
select(PersonBookmark).where(
|
||||
PersonBookmark.account_id == account_id,
|
||||
PersonBookmark.person_id == normalized_id,
|
||||
)
|
||||
).first()
|
||||
if bookmark is not None:
|
||||
session.delete(bookmark)
|
||||
session.commit()
|
||||
@@ -0,0 +1,71 @@
|
||||
import uuid
|
||||
|
||||
from sqlmodel import Session, SQLModel, create_engine
|
||||
|
||||
from inse.auth.model import Account, Organization
|
||||
|
||||
from .model import CreatePersonBookmark
|
||||
from .service import (
|
||||
create_person_bookmark,
|
||||
delete_person_bookmark,
|
||||
list_person_bookmarks,
|
||||
)
|
||||
|
||||
|
||||
def _session_with_account():
|
||||
engine = create_engine(
|
||||
"sqlite:///:memory:", connect_args={"check_same_thread": False}
|
||||
)
|
||||
SQLModel.metadata.create_all(engine)
|
||||
session = Session(engine)
|
||||
organization = Organization(name="Bookmark Test Org")
|
||||
session.add(organization)
|
||||
session.flush()
|
||||
account = Account(
|
||||
email="bookmarks@example.org",
|
||||
name="Bookmark Tester",
|
||||
password_hash="not-used",
|
||||
organization_id=organization.id,
|
||||
)
|
||||
session.add(account)
|
||||
session.commit()
|
||||
return session, account.id
|
||||
|
||||
|
||||
def test_person_bookmarks_are_idempotent_and_normalize_openalex_ids():
|
||||
session, account_id = _session_with_account()
|
||||
assert isinstance(account_id, uuid.UUID)
|
||||
|
||||
create_person_bookmark(
|
||||
session,
|
||||
account_id,
|
||||
"https://openalex.org/A123",
|
||||
CreatePersonBookmark(person_name="Ada Example"),
|
||||
)
|
||||
create_person_bookmark(
|
||||
session,
|
||||
account_id,
|
||||
"A123",
|
||||
CreatePersonBookmark(person_name="Ada Updated"),
|
||||
)
|
||||
|
||||
bookmarks = list_person_bookmarks(session, account_id)
|
||||
assert len(bookmarks) == 1
|
||||
assert bookmarks[0].person_id == "A123"
|
||||
assert bookmarks[0].person_name == "Ada Updated"
|
||||
|
||||
|
||||
def test_deleting_a_person_bookmark_is_idempotent():
|
||||
session, account_id = _session_with_account()
|
||||
assert isinstance(account_id, uuid.UUID)
|
||||
create_person_bookmark(
|
||||
session,
|
||||
account_id,
|
||||
"A123",
|
||||
CreatePersonBookmark(person_name="Ada Example"),
|
||||
)
|
||||
|
||||
delete_person_bookmark(session, account_id, "A123")
|
||||
delete_person_bookmark(session, account_id, "A123")
|
||||
|
||||
assert list_person_bookmarks(session, account_id) == []
|
||||
@@ -70,6 +70,8 @@ class Settings(BaseSettings):
|
||||
skip_otk_validation: bool = True
|
||||
# SMTP / email config
|
||||
send_otk_email: bool = False
|
||||
send_password_reset_email: bool = True
|
||||
password_reset_url: str = "http://localhost:4200/inse-webapp/reset-password"
|
||||
smtp_server: str = "localhost"
|
||||
smtp_port: int = 25
|
||||
smtp_sender: str = "no-reply@smartguide.local"
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""Dashboard statistics package."""
|
||||
@@ -0,0 +1,52 @@
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class DashboardStatistics(BaseModel):
|
||||
institution_id: str
|
||||
organization_name: str
|
||||
publications: int
|
||||
persons: int
|
||||
projects: int
|
||||
dfg_projects: int
|
||||
eu_projects: int
|
||||
bmbf_projects: int
|
||||
|
||||
|
||||
class DashboardStatisticValue(BaseModel):
|
||||
institution_id: str
|
||||
organization_name: str
|
||||
value: int
|
||||
|
||||
|
||||
class TopAuthor(BaseModel):
|
||||
id: str | None = None
|
||||
name: str
|
||||
count: int
|
||||
|
||||
|
||||
class TopAuthorStatistics(BaseModel):
|
||||
institution_id: str
|
||||
works: list[TopAuthor]
|
||||
projects: list[TopAuthor]
|
||||
patents: list[TopAuthor]
|
||||
news: list[TopAuthor]
|
||||
|
||||
|
||||
class TopicHeatmapValue(BaseModel):
|
||||
year: int
|
||||
count: int
|
||||
share: float
|
||||
|
||||
|
||||
class TopicHeatmapField(BaseModel):
|
||||
id: str
|
||||
name: str
|
||||
total: int
|
||||
values: list[TopicHeatmapValue]
|
||||
|
||||
|
||||
class TopicHeatmap(BaseModel):
|
||||
institution_id: str
|
||||
organization_name: str
|
||||
years: list[int]
|
||||
fields: list[TopicHeatmapField]
|
||||
@@ -0,0 +1,168 @@
|
||||
from typing import Literal
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from sqlmodel import Session
|
||||
|
||||
from inse.auth import service as auth_service
|
||||
from inse.auth.model import AccessToken
|
||||
from inse.database import get_session
|
||||
from inse.tags import Tags
|
||||
|
||||
from .model import (
|
||||
DashboardStatisticValue,
|
||||
DashboardStatistics,
|
||||
TopAuthorStatistics,
|
||||
TopicHeatmap,
|
||||
)
|
||||
from .service import (
|
||||
get_dashboard_bmbf_projects,
|
||||
get_dashboard_dfg_projects,
|
||||
get_dashboard_eu_projects,
|
||||
get_dashboard_organization,
|
||||
get_dashboard_persons,
|
||||
get_dashboard_publications,
|
||||
get_dashboard_statistics,
|
||||
get_top_authors,
|
||||
get_topic_heatmap,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/api/dashboard", tags=[Tags.DASHBOARD])
|
||||
|
||||
|
||||
@router.get(
|
||||
"/statistics",
|
||||
operation_id="getDashboardStatistics",
|
||||
response_model=DashboardStatistics,
|
||||
)
|
||||
async def dashboard_statistics(
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> DashboardStatistics:
|
||||
organization = get_dashboard_organization(session, access_token)
|
||||
return await get_dashboard_statistics(
|
||||
organization.openalex_institution_id,
|
||||
organization.name,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/statistics/publications",
|
||||
operation_id="getDashboardPublications",
|
||||
response_model=DashboardStatisticValue,
|
||||
)
|
||||
async def dashboard_publications(
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> DashboardStatisticValue:
|
||||
organization = get_dashboard_organization(session, access_token)
|
||||
return await get_dashboard_publications(
|
||||
organization.openalex_institution_id,
|
||||
organization.name,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/statistics/persons",
|
||||
operation_id="getDashboardPersons",
|
||||
response_model=DashboardStatisticValue,
|
||||
)
|
||||
async def dashboard_persons(
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> DashboardStatisticValue:
|
||||
organization = get_dashboard_organization(session, access_token)
|
||||
return await get_dashboard_persons(
|
||||
organization.openalex_institution_id,
|
||||
organization.name,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/statistics/projects/eu",
|
||||
operation_id="getDashboardEuProjects",
|
||||
response_model=DashboardStatisticValue,
|
||||
)
|
||||
async def dashboard_eu_projects(
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> DashboardStatisticValue:
|
||||
organization = get_dashboard_organization(session, access_token)
|
||||
return await get_dashboard_eu_projects(
|
||||
organization.openalex_institution_id,
|
||||
organization.name,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/statistics/projects/bmbf",
|
||||
operation_id="getDashboardBmbfProjects",
|
||||
response_model=DashboardStatisticValue,
|
||||
)
|
||||
async def dashboard_bmbf_projects(
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> DashboardStatisticValue:
|
||||
organization = get_dashboard_organization(session, access_token)
|
||||
return await get_dashboard_bmbf_projects(
|
||||
organization.openalex_institution_id,
|
||||
organization.name,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/statistics/projects/dfg",
|
||||
operation_id="getDashboardDfgProjects",
|
||||
response_model=DashboardStatisticValue,
|
||||
)
|
||||
async def dashboard_dfg_projects(
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> DashboardStatisticValue:
|
||||
organization = get_dashboard_organization(session, access_token)
|
||||
return await get_dashboard_dfg_projects(
|
||||
organization.openalex_institution_id,
|
||||
organization.name,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/top-authors",
|
||||
operation_id="getDashboardTopAuthors",
|
||||
response_model=TopAuthorStatistics,
|
||||
)
|
||||
async def dashboard_top_authors(
|
||||
works_period: Literal["all_time", "last_5_years"] = Query(
|
||||
default="all_time",
|
||||
pattern="^(all_time|last_5_years)$",
|
||||
),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> TopAuthorStatistics:
|
||||
organization = get_dashboard_organization(session, access_token)
|
||||
return await get_top_authors(
|
||||
organization.openalex_institution_id,
|
||||
organization.name,
|
||||
works_period=works_period,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/topic-heatmap",
|
||||
operation_id="getDashboardTopicHeatmap",
|
||||
response_model=TopicHeatmap,
|
||||
)
|
||||
async def dashboard_topic_heatmap(
|
||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
to_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
limit: int = Query(default=25, ge=1, le=50),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> TopicHeatmap:
|
||||
organization = get_dashboard_organization(session, access_token)
|
||||
return await get_topic_heatmap(
|
||||
institution_id=organization.openalex_institution_id,
|
||||
organization_name=organization.name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
limit=limit,
|
||||
)
|
||||
@@ -0,0 +1,732 @@
|
||||
import asyncio
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from typing import Any, Literal
|
||||
|
||||
from fastapi import HTTPException, status
|
||||
from sqlmodel import Session
|
||||
|
||||
from inse import config
|
||||
from inse.auth.model import AccessToken, Organization
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.institutions.institutions_search_client import InstitutionsSearchClient
|
||||
from inse.model import ESCluster, ESIndex
|
||||
from inse.patents.org.elastic_search_client import OrgPatentsSearchClient
|
||||
|
||||
from .model import (
|
||||
DashboardStatisticValue,
|
||||
DashboardStatistics,
|
||||
TopAuthor,
|
||||
TopAuthorStatistics,
|
||||
TopicHeatmap,
|
||||
TopicHeatmapField,
|
||||
TopicHeatmapValue,
|
||||
)
|
||||
|
||||
TOP_AUTHOR_LIMIT = 10
|
||||
TOPIC_HEATMAP_LIMIT = 25
|
||||
TOPIC_HEATMAP_YEARS = 5
|
||||
WorksPeriod = Literal["all_time", "last_5_years"]
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
DFG_INSTITUTION_FIELDS = [
|
||||
"Antragstellende Institution",
|
||||
"Mitantragstellende Institution",
|
||||
"Beteiligte Einrichtung",
|
||||
"Beteiligte Hochschule",
|
||||
"Beteiligte Institution",
|
||||
"IGK-Partnerinstitution",
|
||||
"Partnerorganisation",
|
||||
"Unternehmen",
|
||||
]
|
||||
|
||||
|
||||
def _total(response: dict[str, Any]) -> int:
|
||||
total = response.get("hits", {}).get("total", 0)
|
||||
if isinstance(total, dict):
|
||||
return int(total.get("value", 0))
|
||||
return int(total or 0)
|
||||
|
||||
|
||||
def get_dashboard_organization(
|
||||
session: Session,
|
||||
access_token: AccessToken,
|
||||
) -> Organization:
|
||||
organization = session.get(Organization, access_token.effective_organization_id)
|
||||
if organization is None or organization.deleted:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Organization not found.",
|
||||
)
|
||||
if not organization.openalex_institution_id:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="Organization has no OpenAlex institution ID configured.",
|
||||
)
|
||||
return organization
|
||||
|
||||
|
||||
async def get_dashboard_statistics(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
) -> DashboardStatistics:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
publications, persons, eu_projects, bmbf_projects, dfg_projects = (
|
||||
await asyncio.gather(
|
||||
get_dashboard_publications(institution_id, organization_name),
|
||||
get_dashboard_persons(institution_id, organization_name),
|
||||
get_dashboard_eu_projects(institution_id, organization_name),
|
||||
get_dashboard_bmbf_projects(institution_id, organization_name),
|
||||
get_dashboard_dfg_projects(institution_id, organization_name),
|
||||
)
|
||||
)
|
||||
return DashboardStatistics(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
publications=publications.value,
|
||||
persons=persons.value,
|
||||
projects=eu_projects.value + bmbf_projects.value + dfg_projects.value,
|
||||
dfg_projects=dfg_projects.value,
|
||||
eu_projects=eu_projects.value,
|
||||
bmbf_projects=bmbf_projects.value,
|
||||
)
|
||||
|
||||
|
||||
async def get_dashboard_publications(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
) -> DashboardStatisticValue:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
response = await elasticsearch.search(
|
||||
index=config.settings.openalex_works_search_index,
|
||||
query=_institution_works_query(normalized_id),
|
||||
size=0,
|
||||
track_total_hits=True,
|
||||
cluster=ESCluster.NES,
|
||||
)
|
||||
return _dashboard_statistic_value(normalized_id, organization_name, response)
|
||||
|
||||
|
||||
async def get_dashboard_persons(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
) -> DashboardStatisticValue:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.OPENALEX_AUTHORS,
|
||||
query={
|
||||
"nested": {
|
||||
"path": "affiliations",
|
||||
"query": {"term": {"affiliations.institution.id": normalized_id}},
|
||||
}
|
||||
},
|
||||
size=0,
|
||||
track_total_hits=True,
|
||||
cluster=ESCluster.NES,
|
||||
)
|
||||
return _dashboard_statistic_value(normalized_id, organization_name, response)
|
||||
|
||||
|
||||
async def get_dashboard_eu_projects(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
) -> DashboardStatisticValue:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
aliases = await _institution_aliases(normalized_id, organization_name)
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD,
|
||||
body={
|
||||
"size": 0,
|
||||
"query": _eu_organization_query(aliases),
|
||||
"aggs": {
|
||||
"projects": {
|
||||
"cardinality": {
|
||||
"field": "projectID",
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
return DashboardStatisticValue(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
value=int(
|
||||
response.get("aggregations", {})
|
||||
.get("projects", {})
|
||||
.get("value", 0)
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
async def get_dashboard_bmbf_projects(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
) -> DashboardStatisticValue:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
aliases = await _institution_aliases(normalized_id, organization_name)
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.PROJECTS_BUND_V1,
|
||||
query=_alias_match_query("Zuwendungsempfänger", aliases),
|
||||
size=0,
|
||||
track_total_hits=True,
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
return _dashboard_statistic_value(normalized_id, organization_name, response)
|
||||
|
||||
|
||||
async def get_dashboard_dfg_projects(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
) -> DashboardStatisticValue:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
aliases = await _institution_aliases(normalized_id, organization_name)
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.PROJECTS_DFG_ALL,
|
||||
query=_dfg_institution_query(aliases),
|
||||
size=0,
|
||||
track_total_hits=True,
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
return _dashboard_statistic_value(normalized_id, organization_name, response)
|
||||
|
||||
|
||||
def _dashboard_statistic_value(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
response: dict[str, Any],
|
||||
) -> DashboardStatisticValue:
|
||||
return DashboardStatisticValue(
|
||||
institution_id=institution_id,
|
||||
organization_name=organization_name,
|
||||
value=_total(response),
|
||||
)
|
||||
|
||||
|
||||
async def _institution_aliases(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
) -> list[str]:
|
||||
aliases = await InstitutionsSearchClient().get_institution_aliases_by_oa_institution_id(
|
||||
_raw_institution_id(institution_id)
|
||||
)
|
||||
return sorted(
|
||||
{
|
||||
alias.strip()
|
||||
for alias in [organization_name, *aliases]
|
||||
if alias and alias.strip()
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _eu_organization_query(aliases: list[str]) -> dict[str, Any]:
|
||||
return {
|
||||
"terms": {
|
||||
"name.keyword": [alias.upper() for alias in aliases],
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def _alias_match_query(field: str, aliases: list[str]) -> dict[str, Any]:
|
||||
return {
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"match": {
|
||||
field: {
|
||||
"query": alias,
|
||||
"operator": "and",
|
||||
}
|
||||
}
|
||||
}
|
||||
for alias in aliases
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def _dfg_institution_query(aliases: list[str]) -> dict[str, Any]:
|
||||
return {
|
||||
"bool": {
|
||||
"should": [
|
||||
_alias_match_query(field, aliases)
|
||||
for field in DFG_INSTITUTION_FIELDS
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
async def get_top_authors(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
works_period: WorksPeriod = "all_time",
|
||||
) -> TopAuthorStatistics:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
authors = await _safe_institution_authors(normalized_id)
|
||||
works = _top_work_authors(authors, works_period)
|
||||
aliases = await _safe_institution_aliases(normalized_id, organization_name)
|
||||
projects = await _safe_top_authors(
|
||||
"projects",
|
||||
_top_project_authors(authors, aliases),
|
||||
)
|
||||
patents = await _safe_top_authors(
|
||||
"patents",
|
||||
_top_patent_authors(normalized_id),
|
||||
)
|
||||
news = await _safe_top_authors(
|
||||
"news",
|
||||
_top_news_authors(authors),
|
||||
)
|
||||
return TopAuthorStatistics(
|
||||
institution_id=normalized_id,
|
||||
works=works,
|
||||
projects=projects,
|
||||
patents=patents,
|
||||
news=news,
|
||||
)
|
||||
|
||||
|
||||
async def get_topic_heatmap(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
limit: int = TOPIC_HEATMAP_LIMIT,
|
||||
) -> TopicHeatmap:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
current_year = datetime.now().year
|
||||
effective_to_year = to_year or current_year
|
||||
effective_from_year = from_year or (effective_to_year - TOPIC_HEATMAP_YEARS + 1)
|
||||
if effective_from_year > effective_to_year:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="from_year must be less than or equal to to_year.",
|
||||
)
|
||||
years = list(range(effective_from_year, effective_to_year + 1))
|
||||
|
||||
response = await elasticsearch.search(
|
||||
index=config.settings.openalex_works_search_index,
|
||||
body={
|
||||
"size": 0,
|
||||
"query": {
|
||||
"bool": {
|
||||
"must": [_institution_works_query(normalized_id)],
|
||||
"filter": [
|
||||
{
|
||||
"range": {
|
||||
"publication_year": {
|
||||
"gte": effective_from_year,
|
||||
"lte": effective_to_year,
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
}
|
||||
},
|
||||
"aggs": {
|
||||
"publication_years": {
|
||||
"terms": {
|
||||
"field": "publication_year",
|
||||
"size": len(years),
|
||||
"order": {"_key": "asc"},
|
||||
}
|
||||
},
|
||||
"topics_nested": {
|
||||
"nested": {"path": "topics"},
|
||||
"aggs": {
|
||||
"fields": {
|
||||
"terms": {
|
||||
"field": "topics.field.id",
|
||||
"size": limit,
|
||||
"order": [
|
||||
{"works": "desc"},
|
||||
{"_key": "asc"},
|
||||
],
|
||||
},
|
||||
"aggs": {
|
||||
"field_name": {
|
||||
"terms": {
|
||||
"field": "topics.field.display_name.keyword",
|
||||
"size": 1,
|
||||
}
|
||||
},
|
||||
"works": {
|
||||
"reverse_nested": {},
|
||||
"aggs": {
|
||||
"by_year": {
|
||||
"terms": {
|
||||
"field": "publication_year",
|
||||
"size": len(years),
|
||||
"order": {"_key": "asc"},
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
cluster=ESCluster.NES,
|
||||
)
|
||||
year_totals = _year_totals(response)
|
||||
buckets = (
|
||||
response.get("aggregations", {})
|
||||
.get("topics_nested", {})
|
||||
.get("fields", {})
|
||||
.get("buckets", [])
|
||||
)
|
||||
field_names = await _field_names([bucket.get("key") for bucket in buckets])
|
||||
|
||||
return TopicHeatmap(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
years=years,
|
||||
fields=[
|
||||
_topic_heatmap_field(bucket, years, year_totals, field_names)
|
||||
for bucket in buckets
|
||||
if bucket.get("key")
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
async def _safe_top_authors(
|
||||
source: str, operation: Any
|
||||
) -> list[TopAuthor]:
|
||||
try:
|
||||
return await operation
|
||||
except Exception:
|
||||
logger.exception("Dashboard top-author aggregation failed for %s.", source)
|
||||
return []
|
||||
|
||||
|
||||
def _normalize_institution_id(value: str) -> str:
|
||||
short_id = value.replace("https://openalex.org/", "").strip().upper()
|
||||
return f"https://openalex.org/{short_id}"
|
||||
|
||||
|
||||
def _raw_institution_id(value: str) -> str:
|
||||
return value.replace("https://openalex.org/", "").strip().upper()
|
||||
|
||||
|
||||
def _institution_works_query(institution_id: str) -> dict[str, Any]:
|
||||
return {
|
||||
"nested": {
|
||||
"path": "authorships.institutions",
|
||||
"query": {"term": {"authorships.institutions.id": institution_id}},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def _year_totals(response: dict[str, Any]) -> dict[int, int]:
|
||||
buckets = (
|
||||
response.get("aggregations", {})
|
||||
.get("publication_years", {})
|
||||
.get("buckets", [])
|
||||
)
|
||||
return {
|
||||
int(bucket["key"]): int(bucket.get("doc_count", 0))
|
||||
for bucket in buckets
|
||||
if bucket.get("key") is not None
|
||||
}
|
||||
|
||||
|
||||
async def _field_names(field_ids: list[str | None]) -> dict[str, str]:
|
||||
ids = [field_id for field_id in field_ids if field_id]
|
||||
if not ids:
|
||||
return {}
|
||||
try:
|
||||
response = await elasticsearch.search(
|
||||
index="openalex-fields",
|
||||
query={"terms": {"id": ids}},
|
||||
source=["id", "display_name"],
|
||||
size=len(ids),
|
||||
cluster=ESCluster.NES,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Could not load dashboard field names.")
|
||||
return {}
|
||||
|
||||
return {
|
||||
source["id"]: source["display_name"]
|
||||
for hit in response.get("hits", {}).get("hits", [])
|
||||
if (source := hit.get("_source", {})).get("id")
|
||||
and source.get("display_name")
|
||||
}
|
||||
|
||||
|
||||
def _topic_heatmap_field(
|
||||
bucket: dict[str, Any],
|
||||
years: list[int],
|
||||
year_totals: dict[int, int],
|
||||
field_names: dict[str, str],
|
||||
) -> TopicHeatmapField:
|
||||
field_id = str(bucket["key"])
|
||||
by_year = {
|
||||
int(year_bucket["key"]): int(year_bucket.get("doc_count", 0))
|
||||
for year_bucket in (
|
||||
bucket.get("works", {}).get("by_year", {}).get("buckets", [])
|
||||
)
|
||||
if year_bucket.get("key") is not None
|
||||
}
|
||||
values = []
|
||||
for year in years:
|
||||
count = by_year.get(year, 0)
|
||||
total = year_totals.get(year, 0)
|
||||
values.append(
|
||||
TopicHeatmapValue(
|
||||
year=year,
|
||||
count=count,
|
||||
share=(count / total) if total else 0,
|
||||
)
|
||||
)
|
||||
|
||||
return TopicHeatmapField(
|
||||
id=field_id,
|
||||
name=_field_name(bucket, field_names.get(field_id, field_id)),
|
||||
total=int(bucket.get("works", {}).get("doc_count", 0)),
|
||||
values=values,
|
||||
)
|
||||
|
||||
|
||||
def _field_name(bucket: dict[str, Any], fallback: str) -> str:
|
||||
name_buckets = bucket.get("field_name", {}).get("buckets", [])
|
||||
if name_buckets and name_buckets[0].get("key"):
|
||||
return str(name_buckets[0]["key"])
|
||||
return fallback
|
||||
|
||||
|
||||
def _short_author_id(value: str) -> str:
|
||||
return value.replace("https://openalex.org/", "").strip().upper()
|
||||
|
||||
|
||||
def _top_work_authors(
|
||||
authors: list[dict[str, Any]],
|
||||
works_period: WorksPeriod,
|
||||
) -> list[TopAuthor]:
|
||||
if works_period == "last_5_years":
|
||||
from_year = datetime.now().year - 4
|
||||
ranked_authors = sorted(
|
||||
(
|
||||
{
|
||||
**author,
|
||||
"selected_works_count": _works_count_since(author, from_year),
|
||||
}
|
||||
for author in authors
|
||||
),
|
||||
key=lambda author: author["selected_works_count"],
|
||||
reverse=True,
|
||||
)
|
||||
else:
|
||||
ranked_authors = [
|
||||
{**author, "selected_works_count": author["works_count"]}
|
||||
for author in authors
|
||||
]
|
||||
|
||||
return [
|
||||
TopAuthor(
|
||||
id=_short_author_id(author["id"]),
|
||||
name=author["name"],
|
||||
count=author["selected_works_count"],
|
||||
)
|
||||
for author in ranked_authors[:TOP_AUTHOR_LIMIT]
|
||||
if author["selected_works_count"] > 0
|
||||
]
|
||||
|
||||
|
||||
def _works_count_since(author: dict[str, Any], from_year: int) -> int:
|
||||
return sum(
|
||||
int(item.get("works_count", 0) or 0)
|
||||
for item in author.get("counts_by_year", [])
|
||||
if int(item.get("year", 0) or 0) >= from_year
|
||||
)
|
||||
|
||||
|
||||
async def _safe_institution_authors(institution_id: str) -> list[dict[str, Any]]:
|
||||
try:
|
||||
return await _institution_authors(institution_id)
|
||||
except Exception:
|
||||
logger.exception("Could not load authors for institution %s.", institution_id)
|
||||
return []
|
||||
|
||||
|
||||
async def _safe_institution_aliases(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
) -> list[str]:
|
||||
try:
|
||||
return await _institution_aliases(institution_id, organization_name)
|
||||
except Exception:
|
||||
logger.exception("Could not load aliases for institution %s.", institution_id)
|
||||
return [organization_name]
|
||||
|
||||
|
||||
async def _institution_authors(institution_id: str) -> list[dict[str, Any]]:
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.OPENALEX_AUTHORS,
|
||||
query={
|
||||
"nested": {
|
||||
"path": "last_known_institutions",
|
||||
"query": {"term": {"last_known_institutions.id": institution_id}},
|
||||
}
|
||||
},
|
||||
source=["id", "display_name", "works_count", "counts_by_year"],
|
||||
size=10000,
|
||||
sort=[{"works_count": {"order": "desc", "missing": "_last"}}],
|
||||
cluster=ESCluster.NES,
|
||||
)
|
||||
return [
|
||||
{
|
||||
"id": str(source["id"]),
|
||||
"name": str(source["display_name"]),
|
||||
"works_count": int(source.get("works_count", 0)),
|
||||
"counts_by_year": source.get("counts_by_year", []) or [],
|
||||
}
|
||||
for hit in response.get("hits", {}).get("hits", [])
|
||||
if (source := hit.get("_source", {})).get("id")
|
||||
and source.get("display_name")
|
||||
]
|
||||
|
||||
|
||||
async def _top_project_authors(
|
||||
authors: list[dict[str, Any]],
|
||||
aliases: list[str],
|
||||
) -> list[TopAuthor]:
|
||||
if not aliases:
|
||||
return []
|
||||
counts: dict[str, int] = {}
|
||||
names: dict[str, str] = {}
|
||||
for bucket in await _top_dfg_project_author_buckets(aliases):
|
||||
key = str(bucket.get("key", "")).strip()
|
||||
if key:
|
||||
normalized_key = key.casefold()
|
||||
names[normalized_key] = key
|
||||
counts[normalized_key] = counts.get(normalized_key, 0) + int(
|
||||
bucket.get("doc_count", 0)
|
||||
)
|
||||
|
||||
institution_authors = {author["name"].casefold(): author for author in authors}
|
||||
ranked = sorted(
|
||||
(
|
||||
(name, count)
|
||||
for name, count in counts.items()
|
||||
if count > 0
|
||||
),
|
||||
key=lambda item: (-item[1], names[item[0]].casefold()),
|
||||
)
|
||||
return [
|
||||
TopAuthor(
|
||||
id=(
|
||||
_short_author_id(institution_authors[name]["id"])
|
||||
if name in institution_authors
|
||||
else None
|
||||
),
|
||||
name=(
|
||||
institution_authors[name]["name"]
|
||||
if name in institution_authors
|
||||
else names[name]
|
||||
),
|
||||
count=count,
|
||||
)
|
||||
for name, count in ranked[:TOP_AUTHOR_LIMIT]
|
||||
]
|
||||
|
||||
|
||||
async def _top_dfg_project_author_buckets(
|
||||
aliases: list[str],
|
||||
) -> list[dict[str, Any]]:
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.PROJECTS_DFG_ALL,
|
||||
body={
|
||||
"size": 0,
|
||||
"query": _dfg_institution_query(aliases),
|
||||
"aggs": {
|
||||
"people": {
|
||||
"terms": {
|
||||
"script": {
|
||||
"lang": "painless",
|
||||
"source": _dfg_involved_persons_script(),
|
||||
},
|
||||
"size": 10000,
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
return (
|
||||
response.get("aggregations", {}).get("people", {}).get("buckets", [])
|
||||
)
|
||||
|
||||
|
||||
def _dfg_involved_persons_script() -> str:
|
||||
return (
|
||||
"def names = new HashSet(); "
|
||||
"def value = params['_source'].containsKey('Beteiligte Personen') "
|
||||
" ? params['_source']['Beteiligte Personen'] : null; "
|
||||
"if (value instanceof String && value.length() > 0) { "
|
||||
" for (name in value.splitOnToken(';')) { "
|
||||
" def trimmed = name.trim(); "
|
||||
" if (trimmed.length() > 0) { names.add(trimmed); } "
|
||||
" } "
|
||||
"} "
|
||||
"return new ArrayList(names);"
|
||||
)
|
||||
|
||||
|
||||
async def _top_patent_authors(institution_id: str) -> list[TopAuthor]:
|
||||
client = OrgPatentsSearchClient()
|
||||
authors = await client.top_authors_by_institution(
|
||||
institution_id=institution_id,
|
||||
size=TOP_AUTHOR_LIMIT,
|
||||
)
|
||||
return [
|
||||
TopAuthor(
|
||||
id=_short_author_id(author["id"]),
|
||||
name=author["name"],
|
||||
count=author["count"],
|
||||
)
|
||||
for author in authors
|
||||
]
|
||||
|
||||
|
||||
async def _top_news_authors(authors: list[dict[str, Any]]) -> list[TopAuthor]:
|
||||
if not authors:
|
||||
return []
|
||||
|
||||
author_names = [author["name"] for author in authors]
|
||||
response = await elasticsearch.search(
|
||||
index="aktuell_postproc",
|
||||
body={
|
||||
"size": 0,
|
||||
"query": {"terms": {"authors.keyword": author_names}},
|
||||
"aggs": {
|
||||
"authors": {
|
||||
"terms": {
|
||||
"field": "authors.keyword",
|
||||
"size": 10000,
|
||||
"order": [
|
||||
{"_count": "desc"},
|
||||
{"_key": "asc"},
|
||||
],
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
buckets = response.get("aggregations", {}).get("authors", {}).get("buckets", [])
|
||||
institution_authors = {author["name"].casefold(): author for author in authors}
|
||||
|
||||
return [
|
||||
TopAuthor(
|
||||
id=_short_author_id(institution_authors[str(bucket["key"]).casefold()]["id"]),
|
||||
name=institution_authors[str(bucket["key"]).casefold()]["name"],
|
||||
count=int(bucket.get("doc_count", 0)),
|
||||
)
|
||||
for bucket in buckets
|
||||
if str(bucket.get("key", "")).casefold() in institution_authors
|
||||
][:TOP_AUTHOR_LIMIT]
|
||||
@@ -0,0 +1,581 @@
|
||||
from unittest.mock import AsyncMock, patch
|
||||
from datetime import datetime
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
from sqlmodel import Session, SQLModel, create_engine
|
||||
|
||||
from inse import config
|
||||
from inse.auth.model import AccessToken, Organization, UserRole
|
||||
from inse.dashboard.service import (
|
||||
get_dashboard_organization,
|
||||
get_dashboard_statistics,
|
||||
get_top_authors,
|
||||
get_topic_heatmap,
|
||||
)
|
||||
from inse.model import ESCluster, ESIndex
|
||||
|
||||
ORG_INSTITUTION_ID = "https://openalex.org/I123"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def anyio_backend():
|
||||
return "asyncio"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_dashboard_statistics_counts_organization_data_and_all_projects():
|
||||
async def search(**kwargs):
|
||||
index = kwargs["index"]
|
||||
if index == config.settings.openalex_works_search_index:
|
||||
return {"hits": {"total": {"value": 120}}}
|
||||
if index == ESIndex.OPENALEX_AUTHORS:
|
||||
return {"hits": {"total": {"value": 35}}}
|
||||
if index == ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD:
|
||||
return {"aggregations": {"projects": {"value": 10}}}
|
||||
if index == ESIndex.PROJECTS_BUND_V1:
|
||||
return {"hits": {"total": {"value": 5}}}
|
||||
return {"hits": {"total": {"value": 3}}}
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.elasticsearch.search",
|
||||
new=AsyncMock(side_effect=search),
|
||||
) as mocked_search, patch(
|
||||
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
|
||||
new=AsyncMock(return_value=["Example University", "Example Uni"]),
|
||||
):
|
||||
result = await get_dashboard_statistics(ORG_INSTITUTION_ID, "Example Org")
|
||||
|
||||
assert result.model_dump() == {
|
||||
"institution_id": ORG_INSTITUTION_ID,
|
||||
"organization_name": "Example Org",
|
||||
"publications": 120,
|
||||
"persons": 35,
|
||||
"projects": 18,
|
||||
"dfg_projects": 3,
|
||||
"eu_projects": 10,
|
||||
"bmbf_projects": 5,
|
||||
}
|
||||
calls = mocked_search.await_args_list
|
||||
assert calls[0].kwargs["index"] == config.settings.openalex_works_search_index
|
||||
assert calls[0].kwargs["query"]["nested"]["query"]["term"] == {
|
||||
"authorships.institutions.id": ORG_INSTITUTION_ID
|
||||
}
|
||||
assert calls[1].kwargs["query"]["nested"]["query"]["term"] == {
|
||||
"affiliations.institution.id": ORG_INSTITUTION_ID
|
||||
}
|
||||
assert all(call.kwargs["cluster"] == ESCluster.INSE for call in calls[2:])
|
||||
assert [call.kwargs["index"] for call in calls[2:]] == [
|
||||
ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD,
|
||||
ESIndex.PROJECTS_BUND_V1,
|
||||
ESIndex.PROJECTS_DFG_ALL,
|
||||
]
|
||||
assert calls[2].kwargs["body"]["query"] == {
|
||||
"terms": {
|
||||
"name.keyword": [
|
||||
"EXAMPLE ORG",
|
||||
"EXAMPLE UNI",
|
||||
"EXAMPLE UNIVERSITY",
|
||||
]
|
||||
}
|
||||
}
|
||||
assert calls[3].kwargs["query"]["bool"]["minimum_should_match"] == 1
|
||||
assert calls[3].kwargs["query"]["bool"]["should"][0]["match"] == {
|
||||
"Zuwendungsempfänger": {
|
||||
"query": "Example Org",
|
||||
"operator": "and",
|
||||
}
|
||||
}
|
||||
assert calls[4].kwargs["query"]["bool"]["minimum_should_match"] == 1
|
||||
assert calls[4].kwargs["query"]["bool"]["should"][0]["bool"]["should"][0][
|
||||
"match"
|
||||
] == {
|
||||
"Antragstellende Institution": {
|
||||
"query": "Example Org",
|
||||
"operator": "and",
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_top_authors_maps_works_and_dfg_project_aggregations():
|
||||
async def search(**kwargs):
|
||||
if kwargs["index"] == ESIndex.OPENALEX_AUTHORS:
|
||||
return {
|
||||
"hits": {
|
||||
"hits": [
|
||||
{
|
||||
"_source": {
|
||||
"id": "https://openalex.org/A1",
|
||||
"display_name": "Ada Example",
|
||||
"works_count": 42,
|
||||
"counts_by_year": [],
|
||||
}
|
||||
},
|
||||
{
|
||||
"_source": {
|
||||
"id": "https://openalex.org/A2",
|
||||
"display_name": "Grace Example",
|
||||
"works_count": 12,
|
||||
"counts_by_year": [],
|
||||
}
|
||||
},
|
||||
]
|
||||
}
|
||||
}
|
||||
if kwargs["index"] == "aktuell_postproc":
|
||||
return {
|
||||
"aggregations": {
|
||||
"authors": {
|
||||
"buckets": [{"key": "Ada Example", "doc_count": 6}]
|
||||
}
|
||||
}
|
||||
}
|
||||
if kwargs["index"] == ESIndex.PROJECTS_DFG_ALL:
|
||||
return {
|
||||
"aggregations": {
|
||||
"people": {
|
||||
"buckets": [{"key": "Grace Example", "doc_count": 3}]
|
||||
}
|
||||
}
|
||||
}
|
||||
return {"aggregations": {"people": {"buckets": []}}}
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.elasticsearch.search",
|
||||
new=AsyncMock(side_effect=search),
|
||||
) as mocked_search, patch(
|
||||
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
|
||||
new=AsyncMock(return_value=["Example University"]),
|
||||
), patch(
|
||||
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
|
||||
new=AsyncMock(
|
||||
return_value=[
|
||||
{"id": "A1", "name": "Ada Example", "count": 4},
|
||||
]
|
||||
),
|
||||
):
|
||||
result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org")
|
||||
|
||||
assert result.works[0].model_dump() == {
|
||||
"id": "A1",
|
||||
"name": "Ada Example",
|
||||
"count": 42,
|
||||
}
|
||||
assert result.projects[0].model_dump() == {
|
||||
"id": "A2",
|
||||
"name": "Grace Example",
|
||||
"count": 3,
|
||||
}
|
||||
assert result.patents[0].model_dump() == {
|
||||
"id": "A1",
|
||||
"name": "Ada Example",
|
||||
"count": 4,
|
||||
}
|
||||
assert result.news[0].model_dump() == {
|
||||
"id": "A1",
|
||||
"name": "Ada Example",
|
||||
"count": 6,
|
||||
}
|
||||
project_calls = [
|
||||
call
|
||||
for call in mocked_search.await_args_list
|
||||
if call.kwargs["index"]
|
||||
in {ESIndex.PROJECTS_DFG_ALL, ESIndex.PROJECTS_BUND_V1}
|
||||
]
|
||||
assert len(project_calls) == 1
|
||||
assert project_calls[0].kwargs["index"] == ESIndex.PROJECTS_DFG_ALL
|
||||
assert project_calls[0].kwargs["body"]["query"]["bool"][
|
||||
"minimum_should_match"
|
||||
] == 1
|
||||
assert "Beteiligte Personen" in project_calls[0].kwargs["body"]["aggs"][
|
||||
"people"
|
||||
]["terms"]["script"]["source"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_top_authors_keeps_dfg_project_authors_without_openalex_match():
|
||||
async def search(**kwargs):
|
||||
if kwargs["index"] == ESIndex.OPENALEX_AUTHORS:
|
||||
return {"hits": {"hits": []}}
|
||||
if kwargs["index"] == ESIndex.PROJECTS_DFG_ALL:
|
||||
return {
|
||||
"aggregations": {
|
||||
"people": {
|
||||
"buckets": [{"key": "Project Person", "doc_count": 9}]
|
||||
}
|
||||
}
|
||||
}
|
||||
return {"aggregations": {"people": {"buckets": []}}}
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.elasticsearch.search",
|
||||
new=AsyncMock(side_effect=search),
|
||||
), patch(
|
||||
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
|
||||
new=AsyncMock(return_value=["Example University"]),
|
||||
), patch(
|
||||
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
|
||||
new=AsyncMock(return_value=[]),
|
||||
):
|
||||
result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org")
|
||||
|
||||
assert result.projects[0].model_dump() == {
|
||||
"id": None,
|
||||
"name": "Project Person",
|
||||
"count": 9,
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_top_authors_returns_top_ten_dfg_project_people_by_project_count():
|
||||
async def search(**kwargs):
|
||||
if kwargs["index"] == ESIndex.OPENALEX_AUTHORS:
|
||||
return {"hits": {"hits": []}}
|
||||
if kwargs["index"] == ESIndex.PROJECTS_DFG_ALL:
|
||||
return {
|
||||
"aggregations": {
|
||||
"people": {
|
||||
"buckets": [
|
||||
{"key": f"Project Person {count}", "doc_count": count}
|
||||
for count in range(1, 12)
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
return {"aggregations": {"people": {"buckets": []}}}
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.elasticsearch.search",
|
||||
new=AsyncMock(side_effect=search),
|
||||
), patch(
|
||||
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
|
||||
new=AsyncMock(return_value=["Example University"]),
|
||||
), patch(
|
||||
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
|
||||
new=AsyncMock(return_value=[]),
|
||||
):
|
||||
result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org")
|
||||
|
||||
assert [author.count for author in result.projects] == list(range(11, 1, -1))
|
||||
assert result.projects[0].name == "Project Person 11"
|
||||
assert len(result.projects) == 10
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_top_authors_combines_dfg_involved_people_case_insensitively():
|
||||
async def search(**kwargs):
|
||||
if kwargs["index"] == ESIndex.OPENALEX_AUTHORS:
|
||||
return {
|
||||
"hits": {
|
||||
"hits": [
|
||||
{
|
||||
"_source": {
|
||||
"id": "https://openalex.org/A1",
|
||||
"display_name": "Ada Example",
|
||||
"works_count": 1,
|
||||
"counts_by_year": [],
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
if kwargs["index"] == ESIndex.PROJECTS_DFG_ALL:
|
||||
return {
|
||||
"aggregations": {
|
||||
"people": {
|
||||
"buckets": [
|
||||
{"key": "Ada Example", "doc_count": 2},
|
||||
{"key": "ada example", "doc_count": 3},
|
||||
{"key": "DFG Person", "doc_count": 4},
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
return {"aggregations": {"authors": {"buckets": []}}}
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.elasticsearch.search",
|
||||
new=AsyncMock(side_effect=search),
|
||||
), patch(
|
||||
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
|
||||
new=AsyncMock(return_value=["Example University"]),
|
||||
), patch(
|
||||
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
|
||||
new=AsyncMock(return_value=[]),
|
||||
):
|
||||
result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org")
|
||||
|
||||
assert [author.model_dump() for author in result.projects] == [
|
||||
{"id": "A1", "name": "Ada Example", "count": 5},
|
||||
{"id": None, "name": "DFG Person", "count": 4},
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_top_authors_returns_partial_response_when_one_source_fails():
|
||||
async def search(**kwargs):
|
||||
if kwargs["index"] == ESIndex.OPENALEX_AUTHORS:
|
||||
return {
|
||||
"hits": {
|
||||
"hits": [
|
||||
{
|
||||
"_source": {
|
||||
"id": "https://openalex.org/A1",
|
||||
"display_name": "Ada Example",
|
||||
"works_count": 42,
|
||||
"counts_by_year": [],
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
raise RuntimeError("projects unavailable")
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.elasticsearch.search",
|
||||
new=AsyncMock(side_effect=search),
|
||||
), patch(
|
||||
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
|
||||
new=AsyncMock(return_value=["Example University"]),
|
||||
), patch(
|
||||
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
|
||||
new=AsyncMock(return_value=[]),
|
||||
):
|
||||
result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org")
|
||||
|
||||
assert result.works[0].name == "Ada Example"
|
||||
assert result.projects == []
|
||||
assert result.patents == []
|
||||
assert result.news == []
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_top_authors_can_rank_works_by_last_five_years():
|
||||
current_year = datetime.now().year
|
||||
|
||||
async def search(**kwargs):
|
||||
if kwargs["index"] == ESIndex.OPENALEX_AUTHORS:
|
||||
return {
|
||||
"hits": {
|
||||
"hits": [
|
||||
{
|
||||
"_source": {
|
||||
"id": "https://openalex.org/A1",
|
||||
"display_name": "Ada Example",
|
||||
"works_count": 100,
|
||||
"counts_by_year": [
|
||||
{"year": current_year - 6, "works_count": 90},
|
||||
{"year": current_year - 1, "works_count": 2},
|
||||
],
|
||||
}
|
||||
},
|
||||
{
|
||||
"_source": {
|
||||
"id": "https://openalex.org/A2",
|
||||
"display_name": "Grace Example",
|
||||
"works_count": 50,
|
||||
"counts_by_year": [
|
||||
{"year": current_year - 1, "works_count": 12},
|
||||
{"year": current_year, "works_count": 4},
|
||||
],
|
||||
}
|
||||
},
|
||||
]
|
||||
}
|
||||
}
|
||||
return {"aggregations": {"people": {"buckets": []}}}
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.elasticsearch.search",
|
||||
new=AsyncMock(side_effect=search),
|
||||
), patch(
|
||||
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
|
||||
new=AsyncMock(return_value=["Example University"]),
|
||||
), patch(
|
||||
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
|
||||
new=AsyncMock(return_value=[]),
|
||||
):
|
||||
result = await get_top_authors(
|
||||
ORG_INSTITUTION_ID,
|
||||
"Example Org",
|
||||
works_period="last_5_years",
|
||||
)
|
||||
|
||||
assert result.works[0].model_dump() == {
|
||||
"id": "A2",
|
||||
"name": "Grace Example",
|
||||
"count": 16,
|
||||
}
|
||||
assert result.works[1].model_dump() == {
|
||||
"id": "A1",
|
||||
"name": "Ada Example",
|
||||
"count": 2,
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_topic_heatmap_maps_field_year_counts_and_shares():
|
||||
async def search(**kwargs):
|
||||
if kwargs["index"] == config.settings.openalex_works_search_index:
|
||||
return {
|
||||
"aggregations": {
|
||||
"publication_years": {
|
||||
"buckets": [
|
||||
{"key": 2023, "doc_count": 10},
|
||||
{"key": 2024, "doc_count": 20},
|
||||
]
|
||||
},
|
||||
"topics_nested": {
|
||||
"fields": {
|
||||
"buckets": [
|
||||
{
|
||||
"key": "https://openalex.org/fields/17",
|
||||
"field_name": {
|
||||
"buckets": [
|
||||
{
|
||||
"key": "Computer Science",
|
||||
"doc_count": 12,
|
||||
}
|
||||
]
|
||||
},
|
||||
"works": {
|
||||
"doc_count": 12,
|
||||
"by_year": {
|
||||
"buckets": [
|
||||
{"key": 2023, "doc_count": 4},
|
||||
{"key": 2024, "doc_count": 8},
|
||||
]
|
||||
},
|
||||
},
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
return {
|
||||
"hits": {
|
||||
"hits": [
|
||||
{
|
||||
"_source": {
|
||||
"id": "https://openalex.org/fields/17",
|
||||
"display_name": "Computer Science",
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.elasticsearch.search",
|
||||
new=AsyncMock(side_effect=search),
|
||||
) as mocked_search:
|
||||
result = await get_topic_heatmap(
|
||||
institution_id=ORG_INSTITUTION_ID,
|
||||
organization_name="Example Org",
|
||||
from_year=2023,
|
||||
to_year=2024,
|
||||
limit=10,
|
||||
)
|
||||
|
||||
assert result.institution_id == ORG_INSTITUTION_ID
|
||||
assert result.organization_name == "Example Org"
|
||||
assert result.years == [2023, 2024]
|
||||
assert result.fields[0].model_dump() == {
|
||||
"id": "https://openalex.org/fields/17",
|
||||
"name": "Computer Science",
|
||||
"total": 12,
|
||||
"values": [
|
||||
{"year": 2023, "count": 4, "share": 0.4},
|
||||
{"year": 2024, "count": 8, "share": 0.4},
|
||||
],
|
||||
}
|
||||
body = mocked_search.await_args_list[0].kwargs["body"]
|
||||
assert body["query"]["bool"]["must"][0]["nested"]["query"]["term"] == {
|
||||
"authorships.institutions.id": ORG_INSTITUTION_ID
|
||||
}
|
||||
assert (
|
||||
body["aggs"]["topics_nested"]["aggs"]["fields"]["terms"]["field"]
|
||||
== "topics.field.id"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_topic_heatmap_defaults_to_last_five_years():
|
||||
async def search(**kwargs):
|
||||
if kwargs["index"] == config.settings.openalex_works_search_index:
|
||||
return {
|
||||
"aggregations": {
|
||||
"publication_years": {"buckets": []},
|
||||
"topics_nested": {"fields": {"buckets": []}},
|
||||
}
|
||||
}
|
||||
return {"hits": {"hits": []}}
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.elasticsearch.search",
|
||||
new=AsyncMock(side_effect=search),
|
||||
) as mocked_search:
|
||||
result = await get_topic_heatmap(
|
||||
institution_id=ORG_INSTITUTION_ID,
|
||||
organization_name="Example Org",
|
||||
)
|
||||
|
||||
current_year = datetime.now().year
|
||||
assert result.years == list(range(current_year - 4, current_year + 1))
|
||||
body = mocked_search.await_args_list[0].kwargs["body"]
|
||||
assert body["query"]["bool"]["filter"][0]["range"]["publication_year"] == {
|
||||
"gte": current_year - 4,
|
||||
"lte": current_year,
|
||||
}
|
||||
|
||||
|
||||
def test_get_dashboard_organization_uses_effective_organization():
|
||||
engine = create_engine("sqlite://", connect_args={"check_same_thread": False})
|
||||
SQLModel.metadata.create_all(engine)
|
||||
|
||||
with Session(engine) as session:
|
||||
organization = Organization(
|
||||
name="Example University",
|
||||
openalex_institution_id="I456",
|
||||
)
|
||||
session.add(organization)
|
||||
session.commit()
|
||||
session.refresh(organization)
|
||||
|
||||
token = _access_token(organization.id)
|
||||
|
||||
result = get_dashboard_organization(session, token)
|
||||
|
||||
assert result.id == organization.id
|
||||
assert result.openalex_institution_id == "I456"
|
||||
|
||||
|
||||
def test_get_dashboard_organization_rejects_missing_openalex_id():
|
||||
engine = create_engine("sqlite://", connect_args={"check_same_thread": False})
|
||||
SQLModel.metadata.create_all(engine)
|
||||
|
||||
with Session(engine) as session:
|
||||
organization = Organization(name="Example University")
|
||||
session.add(organization)
|
||||
session.commit()
|
||||
session.refresh(organization)
|
||||
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
get_dashboard_organization(session, _access_token(organization.id))
|
||||
|
||||
assert exc_info.value.status_code == 422
|
||||
|
||||
|
||||
def _access_token(organization_id):
|
||||
return AccessToken(
|
||||
real_account_id=organization_id,
|
||||
effective_account_id=organization_id,
|
||||
effective_role=UserRole.USER,
|
||||
effective_organization_id=organization_id,
|
||||
expires_at="2099-01-01T00:00:00Z",
|
||||
epoch=0,
|
||||
user_fingerprint_hash="hash",
|
||||
raw_token="token",
|
||||
)
|
||||
@@ -16,9 +16,72 @@ engine = create_engine(
|
||||
)
|
||||
|
||||
|
||||
def _migrate_secret_table():
|
||||
"""Upgrade the legacy login-only secret table without losing its data."""
|
||||
columns = {column["name"] for column in inspect(engine).get_columns("secret")}
|
||||
required_columns = {
|
||||
"purpose",
|
||||
"request_count",
|
||||
"request_window_started_at",
|
||||
}
|
||||
if required_columns.issubset(columns):
|
||||
return
|
||||
|
||||
# SQLite cannot alter a UNIQUE constraint in place. Rebuild the table so an
|
||||
# account can hold both a login OTK and a password-reset secret.
|
||||
with engine.begin() as connection:
|
||||
connection.execute(text("ALTER TABLE secret RENAME TO secret_legacy"))
|
||||
connection.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE secret (
|
||||
id CHAR(32) NOT NULL PRIMARY KEY,
|
||||
account_id CHAR(32) NOT NULL,
|
||||
purpose VARCHAR NOT NULL,
|
||||
secret_value VARCHAR NOT NULL,
|
||||
expires_at DATETIME NOT NULL,
|
||||
request_count INTEGER NOT NULL DEFAULT 0,
|
||||
request_window_started_at DATETIME,
|
||||
CONSTRAINT uq_secret_account_purpose
|
||||
UNIQUE (account_id, purpose),
|
||||
FOREIGN KEY(account_id) REFERENCES account (id)
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
connection.execute(
|
||||
text(
|
||||
"""
|
||||
INSERT INTO secret (
|
||||
id, account_id, purpose, secret_value, expires_at,
|
||||
request_count, request_window_started_at
|
||||
)
|
||||
SELECT id, account_id, 'LOGIN_OTK', secret_value, expires_at,
|
||||
0, NULL
|
||||
FROM secret_legacy
|
||||
"""
|
||||
)
|
||||
)
|
||||
connection.execute(text("DROP TABLE secret_legacy"))
|
||||
connection.execute(
|
||||
text("CREATE INDEX ix_secret_account_id ON secret (account_id)")
|
||||
)
|
||||
connection.execute(text("CREATE INDEX ix_secret_purpose ON secret (purpose)"))
|
||||
connection.execute(
|
||||
text("CREATE INDEX ix_secret_expires_at ON secret (expires_at)")
|
||||
)
|
||||
connection.execute(
|
||||
text(
|
||||
"CREATE INDEX ix_secret_request_window_started_at "
|
||||
"ON secret (request_window_started_at)"
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def create_db_and_tables():
|
||||
"""Creates the database and tables based on the SQLModel metadata."""
|
||||
SQLModel.metadata.create_all(engine)
|
||||
_migrate_secret_table()
|
||||
columns = {column["name"] for column in inspect(engine).get_columns("account")}
|
||||
if "activated" not in columns:
|
||||
with engine.begin() as connection:
|
||||
@@ -28,6 +91,21 @@ def create_db_and_tables():
|
||||
"BOOLEAN NOT NULL DEFAULT TRUE"
|
||||
)
|
||||
)
|
||||
if "roles" not in columns:
|
||||
with engine.begin() as connection:
|
||||
connection.execute(
|
||||
text(
|
||||
"ALTER TABLE account ADD COLUMN roles "
|
||||
"JSON NOT NULL DEFAULT '[\"USER\"]'"
|
||||
)
|
||||
)
|
||||
if "role" in columns:
|
||||
connection.execute(
|
||||
text(
|
||||
"UPDATE account SET roles = '[\"' || role || '\"]' "
|
||||
"WHERE role IS NOT NULL"
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def get_session():
|
||||
|
||||
@@ -224,6 +224,7 @@ class InstitutionsSearchClient:
|
||||
"wildcard": {
|
||||
"display_name.keyword": {
|
||||
"value": f"*{stripped}*",
|
||||
"case_insensitive": True,
|
||||
"boost": 2,
|
||||
}
|
||||
}
|
||||
@@ -232,6 +233,7 @@ class InstitutionsSearchClient:
|
||||
"wildcard": {
|
||||
"display_name_alternatives.keyword": {
|
||||
"value": f"*{stripped}*",
|
||||
"case_insensitive": True,
|
||||
"boost": 2,
|
||||
}
|
||||
}
|
||||
@@ -240,6 +242,7 @@ class InstitutionsSearchClient:
|
||||
"wildcard": {
|
||||
"display_name_acronyms.keyword": {
|
||||
"value": f"*{stripped.upper()}*",
|
||||
"case_insensitive": True,
|
||||
"boost": 10,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ def get_client() -> httpx.AsyncClient:
|
||||
global _client, _loop
|
||||
try:
|
||||
import asyncio
|
||||
|
||||
current_loop = asyncio.get_running_loop()
|
||||
except RuntimeError:
|
||||
current_loop = None
|
||||
@@ -45,7 +46,7 @@ def _cluster_credentials(cluster: ESCluster) -> Tuple[str, str]:
|
||||
Returns:
|
||||
Tuple[str, str]: The Elasticsearch URL and API key for the specified cluster.
|
||||
"""
|
||||
|
||||
|
||||
if cluster == ESCluster.NES:
|
||||
if (
|
||||
not config.settings.elasticsearch_url
|
||||
@@ -54,7 +55,7 @@ def _cluster_credentials(cluster: ESCluster) -> Tuple[str, str]:
|
||||
raise MissingApiKeyError(
|
||||
"Elasticsearch URL and API key must be set in the configuration for cluster 'nes'"
|
||||
)
|
||||
|
||||
|
||||
return config.settings.elasticsearch_url, config.settings.elasticsearch_api_key
|
||||
elif cluster == ESCluster.INSE:
|
||||
if (
|
||||
@@ -91,6 +92,7 @@ def _index_to_cluster(index: ESIndex) -> Optional[ESCluster]:
|
||||
ESIndex.OPENALEX_AUTHORS,
|
||||
ESIndex.OPENALEX_INSTITUTIONS,
|
||||
ESIndex.OPENALEX_PUBLICATIONS,
|
||||
ESIndex.WORK_CLASSIFICATIONS,
|
||||
}:
|
||||
return ESCluster.NES
|
||||
elif index in {
|
||||
@@ -106,10 +108,15 @@ def _index_to_cluster(index: ESIndex) -> Optional[ESCluster]:
|
||||
|
||||
|
||||
def _wrap_exception(e: Exception) -> Exception:
|
||||
logger.exception(f"Elasticsearch raised an exception: {e}")
|
||||
if isinstance(e, httpx.HTTPStatusError):
|
||||
if e.response.status_code == 404:
|
||||
return ElasticsearchNotFoundException(f"Elasticsearch resource not found: {e}")
|
||||
return ElasticsearchException(f"Elasticsearch returned status {e.response.status_code}: {e}")
|
||||
return ElasticsearchNotFoundException(
|
||||
f"Elasticsearch resource not found: {e}"
|
||||
)
|
||||
return ElasticsearchException(
|
||||
f"Elasticsearch returned status {e.response.status_code}: {e}"
|
||||
)
|
||||
elif isinstance(e, httpx.RequestError):
|
||||
return ElasticsearchConnectionException(f"Elasticsearch connection error: {e}")
|
||||
return ElasticsearchException(f"Unexpected Elasticsearch error: {e}")
|
||||
@@ -211,7 +218,9 @@ async def search(
|
||||
raise _wrap_exception(exc) from exc
|
||||
|
||||
|
||||
async def open_point_in_time(index: str, keep_alive: str = "1m", cluster: str = "nes") -> str:
|
||||
async def open_point_in_time(
|
||||
index: str, keep_alive: str = "1m", cluster: str = "nes"
|
||||
) -> str:
|
||||
"""Opens a point-in-time on the given index and returns its id."""
|
||||
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
||||
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
|
||||
@@ -256,7 +265,7 @@ async def scan(
|
||||
cluster: str = "nes",
|
||||
) -> AsyncIterator[Dict[str, Any]]:
|
||||
"""Yields every hit matching ``query`` using a point-in-time + ``search_after``.
|
||||
|
||||
|
||||
Unlike ``from``/``size`` pagination, this is not bounded by
|
||||
``index.max_result_window``, so it can stream result sets larger than 10k.
|
||||
"""
|
||||
@@ -316,6 +325,9 @@ async def get(
|
||||
cluster: ESCluster = ESCluster.NES,
|
||||
) -> dict[str, Any]:
|
||||
|
||||
if isinstance(index, ESIndex):
|
||||
cluster = _index_to_cluster(index) or cluster
|
||||
|
||||
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
||||
|
||||
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
|
||||
|
||||
@@ -2,7 +2,7 @@ from openai import OpenAI, APIConnectionError
|
||||
from openai import AsyncOpenAI
|
||||
from .. import config
|
||||
from typing import Optional, Dict, Any
|
||||
|
||||
import asyncio
|
||||
def call(
|
||||
system_prompt: str,
|
||||
user_prompt: str,
|
||||
@@ -62,7 +62,7 @@ def _get_response_format(schema, schema_name: Optional[str] = None) -> Dict[str,
|
||||
async def call_stream(
|
||||
system_prompt: str,
|
||||
user_prompt: str,
|
||||
emit, # EventCallback
|
||||
emit,
|
||||
model: str = None,
|
||||
json_schema=None,
|
||||
schema_name=None,
|
||||
@@ -98,15 +98,26 @@ async def call_stream(
|
||||
stream=True,
|
||||
)
|
||||
|
||||
async for chunk in stream:
|
||||
delta = chunk.choices[0].delta.content
|
||||
if delta:
|
||||
full_content += delta
|
||||
await emit({"type": "llm_chunk", "content": delta})
|
||||
try:
|
||||
async for chunk in stream:
|
||||
delta = chunk.choices[0].delta.content
|
||||
if delta:
|
||||
full_content += delta
|
||||
await emit({"type": "llm_chunk", "content": delta})
|
||||
finally:
|
||||
# Always release the underlying HTTP connection, whether we
|
||||
# finished normally, timed out, were cancelled, or emit()
|
||||
# failed because the client disconnected. This is what
|
||||
# actually tells the backend to stop generating.
|
||||
await stream.close()
|
||||
|
||||
except APIConnectionError as e:
|
||||
print(f"Connection error: {e}")
|
||||
return ""
|
||||
except asyncio.CancelledError:
|
||||
# Real cancellation (e.g. asyncio.wait_for timeout, or task.cancel()
|
||||
# from the router)
|
||||
raise
|
||||
except Exception as e:
|
||||
import traceback
|
||||
print(f"LLM streaming failed: {type(e).__name__}: {e}")
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
# inse/keywords/file_extraction.py
|
||||
import base64
|
||||
import logging
|
||||
import httpx
|
||||
from bs4 import BeautifulSoup
|
||||
# import fitz
|
||||
import io
|
||||
from pypdf import PdfReader
|
||||
from pypdf.errors import PdfReadError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def extract_text_from_upload(filename: str, content_base64: str, mime_type: str) -> str:
|
||||
try:
|
||||
raw = base64.b64decode(content_base64)
|
||||
except Exception:
|
||||
logger.warning("Failed to decode base64 for %s", filename)
|
||||
return f"[{filename}: could not decode upload]"
|
||||
|
||||
if mime_type == "application/pdf" or filename.lower().endswith(".pdf"):
|
||||
return _extract_pdf_text(filename, raw)
|
||||
|
||||
try:
|
||||
return raw.decode("utf-8", errors="replace")
|
||||
except Exception:
|
||||
logger.warning("Failed to decode %s as text", filename)
|
||||
return f"[{filename}: unsupported or undecodable content]"
|
||||
|
||||
|
||||
def _extract_pdf_text(filename: str, raw: bytes) -> str:
|
||||
try:
|
||||
reader = PdfReader(io.BytesIO(raw), strict=False) # non-strict: tolerate minor spec violations
|
||||
except Exception as e:
|
||||
logger.warning("Failed to open PDF %s: %s", filename, e)
|
||||
return f"[{filename}: PDF could not be opened (corrupted or invalid)]"
|
||||
|
||||
if reader.is_encrypted:
|
||||
try:
|
||||
# Attempt to decrypt with an empty password (common for "owner-locked"
|
||||
# PDFs that don't require one to read content)
|
||||
reader.decrypt("")
|
||||
except Exception as e:
|
||||
logger.warning("Encrypted PDF %s could not be decrypted: %s", filename, e)
|
||||
return f"[{filename}: PDF is encrypted and could not be read]"
|
||||
|
||||
parts = []
|
||||
for page_num, page in enumerate(reader.pages):
|
||||
try:
|
||||
parts.append(page.extract_text() or "")
|
||||
except PdfReadError as e:
|
||||
logger.warning("Failed to extract page %d of %s: %s", page_num, filename, e)
|
||||
parts.append(f"[Page {page_num + 1} could not be extracted]")
|
||||
except Exception as e:
|
||||
logger.warning("Unexpected error extracting page %d of %s: %s", page_num, filename, e)
|
||||
parts.append(f"[Page {page_num + 1} could not be extracted]")
|
||||
|
||||
return "\n".join(parts)
|
||||
@@ -23,7 +23,9 @@ from inse.keywords.model import (
|
||||
KeywordEntry,
|
||||
KeywordEntryWithTopic,
|
||||
KeywordsWsEvent,
|
||||
FileUpload,
|
||||
)
|
||||
from inse.keywords.extract_text import extract_text_from_upload
|
||||
from inse.topics.logic import vector_search_topics_batch
|
||||
logger = logging.getLogger(__name__)
|
||||
EventCallback = Callable[[dict], Awaitable[None]]
|
||||
@@ -64,7 +66,7 @@ async def extract_keywords(query: str, mode: str, limit: int) -> ExtractedKeywor
|
||||
"""
|
||||
start_time = time.time()
|
||||
if mode == "url":
|
||||
text = await _get_text_content(query)
|
||||
text = await get_text_from_url(query)
|
||||
system_prompt = KeywordsPrompt.EXTRACT_WEBSITE_KEYWORDS_PROMPT
|
||||
|
||||
else:
|
||||
@@ -97,7 +99,294 @@ async def extract_keywords(query: str, mode: str, limit: int) -> ExtractedKeywor
|
||||
return ExtractedKeywordsResponse(results=enriched, source=mode, source_url=query if mode == "url" else None, source_content=text, duration=elapsed_time)
|
||||
|
||||
|
||||
async def _get_text_content(url: str) -> str:
|
||||
|
||||
async def extract_keywords_stream_enriched(
|
||||
query: str,
|
||||
mode: str,
|
||||
limit: int,
|
||||
emit: EventCallback,
|
||||
files: List[FileUpload] | None = None,
|
||||
) -> ExtractedKeywordsResponse:
|
||||
start_time = time.time()
|
||||
timeout_seconds = 120
|
||||
await emit(KeywordsWsEvent(type="status", step="started", message="Starte Keyword-Extraktion").model_dump())
|
||||
|
||||
LEVELS = ("broad_keywords", "coarse_grained", "fine_grained")
|
||||
confirmed: Dict[str, List[KeywordEntryWithTopic]] = {level: [] for level in LEVELS}
|
||||
enrichment_tasks: List[asyncio.Task] = []
|
||||
|
||||
async def emit_full_results() -> None:
|
||||
try:
|
||||
validated = _build_enriched_snapshot(confirmed)
|
||||
except ValidationError:
|
||||
return
|
||||
await emit(KeywordsWsEvent(type="keywords", keywords=validated.model_dump()).model_dump())
|
||||
|
||||
async def get_openalex_topic(level: str, idx: int, item: KeywordEntry) -> None:
|
||||
try:
|
||||
topic = await vector_search_topics_batch(
|
||||
keywords=[item.keyword],
|
||||
search_type="hybrid",
|
||||
)
|
||||
confirmed[level][idx].topic_mapping = topic.results[0] if topic.results else None
|
||||
await emit_full_results()
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error fetching OpenAlex topic for keyword '{item.keyword}': {e}")
|
||||
await emit_full_results()
|
||||
|
||||
def make_on_chunk(base_offset: Dict[str, int]):
|
||||
"""
|
||||
Builds an on_chunk callback for a single streaming LLM call.
|
||||
|
||||
`base_offset` records how many items each level already had in the
|
||||
shared `confirmed` list *before* this call started, so growth from
|
||||
this call's own (independent) partial JSON can be tracked correctly
|
||||
even though `confirmed` keeps accumulating across multiple calls
|
||||
(one per file).
|
||||
"""
|
||||
|
||||
async def on_chunk(event: Dict[str, Any]) -> None:
|
||||
if event["type"] != "llm_chunk":
|
||||
await emit(event)
|
||||
return
|
||||
|
||||
try:
|
||||
partial = partial_json_parser.loads(event.get("_full_content", ""))
|
||||
except Exception:
|
||||
return
|
||||
if not isinstance(partial, dict):
|
||||
return
|
||||
|
||||
grew = False
|
||||
|
||||
for level in LEVELS:
|
||||
current = partial.get(level) or []
|
||||
# How many items belonging to *this* call have already been
|
||||
# appended to the shared `confirmed` list.
|
||||
local_have = len(confirmed[level]) - base_offset[level]
|
||||
start_idx = len(confirmed[level])
|
||||
|
||||
while local_have < len(current):
|
||||
raw_item = current[local_have]
|
||||
try:
|
||||
validated_item = KeywordEntry.model_validate(raw_item)
|
||||
except ValidationError:
|
||||
break
|
||||
|
||||
confirmed[level].append(KeywordEntryWithTopic(llm_keyword=validated_item))
|
||||
local_have += 1
|
||||
grew = True
|
||||
|
||||
for idx in range(start_idx, len(confirmed[level])):
|
||||
keyword_text = confirmed[level][idx].llm_keyword.keyword
|
||||
await emit(
|
||||
KeywordsWsEvent(
|
||||
type="status",
|
||||
step="enriching",
|
||||
message=f"Extracting topic for keyword '{keyword_text}'",
|
||||
).model_dump()
|
||||
)
|
||||
task = asyncio.create_task(get_openalex_topic(level, idx, confirmed[level][idx].llm_keyword))
|
||||
enrichment_tasks.append(task)
|
||||
|
||||
if grew:
|
||||
await emit_full_results()
|
||||
|
||||
return on_chunk
|
||||
|
||||
async def run_llm_extraction(text: str, system_prompt: str, label: str | None = None) -> None:
|
||||
"""
|
||||
Runs a single independent streaming LLM extraction call over `text`
|
||||
and folds its results into the shared `confirmed` structure. Used
|
||||
once for url/text mode, and once *per file* for file mode.
|
||||
"""
|
||||
base_offset = {level: len(confirmed[level]) for level in LEVELS}
|
||||
on_chunk = make_on_chunk(base_offset)
|
||||
full_content_holder = {"value": ""}
|
||||
|
||||
async def emit_wrapper(event: Dict[str, Any]) -> None:
|
||||
if event["type"] == "llm_chunk":
|
||||
full_content_holder["value"] += event["content"]
|
||||
event = {**event, "_full_content": full_content_holder["value"]}
|
||||
await on_chunk(event)
|
||||
|
||||
user_prompt = "\nNow analyze the following text.\n"
|
||||
if limit:
|
||||
user_prompt += f"\nExtract exactly {limit} keywords for each level.\n"
|
||||
user_prompt += f"\nInput:\n{text}"
|
||||
|
||||
suffix = f" for {label}" if label else ""
|
||||
|
||||
try:
|
||||
keywords_raw = await asyncio.wait_for(
|
||||
llm.call_stream(
|
||||
system_prompt=system_prompt,
|
||||
user_prompt=user_prompt,
|
||||
json_schema=ExtractedKeywordsLLM.model_json_schema(),
|
||||
schema_name="extracted_keywords",
|
||||
temperature=0.0,
|
||||
top_p=0.95,
|
||||
emit=emit_wrapper,
|
||||
),
|
||||
timeout=timeout_seconds,
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
await emit(KeywordsWsEvent(type="error", message=f"LLM call timed out after {timeout_seconds}s{suffix}").model_dump())
|
||||
raise RuntimeError(f"LLM streaming call timed out{suffix}")
|
||||
except asyncio.CancelledError:
|
||||
await emit(KeywordsWsEvent(type="error", message="Request cancelled").model_dump())
|
||||
raise
|
||||
|
||||
if not keywords_raw:
|
||||
# Empty string covers: real empty completion, APIConnectionError,
|
||||
# and disconnect-during-emit (call_stream currently swallows all
|
||||
# three the same way). Treat as a failed extraction.
|
||||
await emit(KeywordsWsEvent(type="error", message=f"LLM call failed or returned no content{suffix}").model_dump())
|
||||
raise RuntimeError(f"LLM streaming call returned empty content{suffix}")
|
||||
|
||||
try:
|
||||
json.loads(keywords_raw)
|
||||
except json.JSONDecodeError as e:
|
||||
await emit(KeywordsWsEvent(type="error", message=f"Invalid JSON in LLM response{suffix}: {e}").model_dump())
|
||||
raise RuntimeError(f"LLM response is not valid JSON{suffix}")
|
||||
|
||||
# ---------- Gather input text & run extraction(s) ----------
|
||||
source_content = ""
|
||||
try:
|
||||
if mode == "url":
|
||||
await emit(KeywordsWsEvent(type="status", step="fetching_url", message=f"Extrahiere Inhalt von {query}").model_dump())
|
||||
text = await get_text_from_url(query)
|
||||
if text:
|
||||
await emit(KeywordsWsEvent(type="status", step="content_extracted", message=f"Extrahiert {len(text)} Zeichen").model_dump())
|
||||
else:
|
||||
await emit(KeywordsWsEvent(type="error", message=f"Fehler beim Abrufen des Inhalts von {query}").model_dump())
|
||||
raise RuntimeError(f"Failed to fetch content from {query}")
|
||||
|
||||
source_content = text
|
||||
await run_llm_extraction(text, KeywordsPrompt.EXTRACT_WEBSITE_KEYWORDS_PROMPT)
|
||||
|
||||
elif mode == "files":
|
||||
provided_files = files or []
|
||||
total_files = len(provided_files)
|
||||
await emit(
|
||||
KeywordsWsEvent(
|
||||
type="status",
|
||||
step="extracting_files",
|
||||
message=f"Extrahiere Inhalt aus {total_files} Datei(en)",
|
||||
).model_dump()
|
||||
)
|
||||
|
||||
file_texts: List[str] = []
|
||||
failed_files: List[str] = []
|
||||
|
||||
for i, f in enumerate(provided_files, start=1):
|
||||
text = await asyncio.to_thread(
|
||||
extract_text_from_upload, f.filename, f.content_base64, f.mime_type
|
||||
)
|
||||
|
||||
if not text or not text.strip():
|
||||
await emit(
|
||||
KeywordsWsEvent(
|
||||
type="status",
|
||||
step="content_extracted",
|
||||
message=f"Kein Text in '{f.filename}' gefunden, überspringe",
|
||||
).model_dump()
|
||||
)
|
||||
failed_files.append(f.filename)
|
||||
continue
|
||||
|
||||
await emit(
|
||||
KeywordsWsEvent(
|
||||
type="status",
|
||||
step="content_extracted",
|
||||
message=f"'{f.filename}': {len(text)} Zeichen extrahiert ({i}/{total_files})",
|
||||
).model_dump()
|
||||
)
|
||||
await emit(
|
||||
KeywordsWsEvent(
|
||||
type="status",
|
||||
step="calling_llm",
|
||||
message=f"Extrahiere Keywords aus '{f.filename}' ({i}/{total_files})",
|
||||
).model_dump()
|
||||
)
|
||||
|
||||
try:
|
||||
# Each file gets its own, independent LLM call so
|
||||
# keywords from one file can't dilute or get mixed up
|
||||
# with the content of another. Results from every call
|
||||
# still accumulate into the same shared `confirmed`
|
||||
# structure, so they keep streaming to the client
|
||||
# progressively as before.
|
||||
await run_llm_extraction(
|
||||
text,
|
||||
KeywordsPrompt.EXTRACT_KEYWORDS_TEXT_PROMPT,
|
||||
label=f"file '{f.filename}'",
|
||||
)
|
||||
file_texts.append(f"# {f.filename}\n\n{text}")
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as e:
|
||||
# Isolate failures: one broken/unparseable file shouldn't
|
||||
# abort keyword extraction for the rest of the batch.
|
||||
logger.error(f"Keyword extraction failed for file '{f.filename}': {e}")
|
||||
failed_files.append(f.filename)
|
||||
continue
|
||||
|
||||
if not file_texts:
|
||||
await emit(KeywordsWsEvent(type="error", message="Kein Text konnte aus den Dateien extrahiert werden").model_dump())
|
||||
raise RuntimeError("Failed to extract text from uploaded files")
|
||||
|
||||
if failed_files:
|
||||
await emit(
|
||||
KeywordsWsEvent(
|
||||
type="status",
|
||||
step="content_extracted",
|
||||
message=f"{len(failed_files)} Datei(en) konnten nicht verarbeitet werden: {', '.join(failed_files)}",
|
||||
).model_dump()
|
||||
)
|
||||
|
||||
source_content = "\n\n---\n\n".join(file_texts)
|
||||
|
||||
else:
|
||||
text = query
|
||||
await emit(KeywordsWsEvent(type="status", step="text_received", message=f"Empfangen {len(text)} Zeichen").model_dump())
|
||||
source_content = text
|
||||
await run_llm_extraction(text, KeywordsPrompt.EXTRACT_KEYWORDS_TEXT_PROMPT)
|
||||
|
||||
finally:
|
||||
if enrichment_tasks:
|
||||
done, pending = await asyncio.wait(enrichment_tasks, timeout=10)
|
||||
for task in pending:
|
||||
task.cancel()
|
||||
if pending:
|
||||
await asyncio.gather(*pending, return_exceptions=True)
|
||||
|
||||
# ---------- Finalize ----------
|
||||
await emit(KeywordsWsEvent(type="status", step="parsing_response", message="Bearbeite Ergebnisse").model_dump())
|
||||
await emit_full_results()
|
||||
|
||||
try:
|
||||
final_validated = _build_enriched_snapshot(confirmed)
|
||||
except ValidationError:
|
||||
final_validated = ExtractedKeywords.model_validate(
|
||||
{level: [item.model_dump() for item in confirmed.get(level, [])] for level in LEVELS}
|
||||
)
|
||||
|
||||
elapsed_time = time.time() - start_time
|
||||
result = ExtractedKeywordsResponse(
|
||||
results=final_validated,
|
||||
source=mode,
|
||||
source_url=query if mode == "url" else None,
|
||||
source_content=source_content,
|
||||
duration=elapsed_time,
|
||||
)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
async def get_text_from_url(url: str) -> str:
|
||||
"""
|
||||
Fetches the HTML content from the given URL using httpx and extracts visible text.
|
||||
"""
|
||||
@@ -112,7 +401,7 @@ async def _get_text_content(url: str) -> str:
|
||||
async with httpx.AsyncClient(timeout=30.0) as client:
|
||||
response = await client.get(url, headers=headers)
|
||||
response.raise_for_status()
|
||||
|
||||
|
||||
soup = BeautifulSoup(response.text, "html.parser")
|
||||
for element in soup(["script", "style"]):
|
||||
element.decompose()
|
||||
@@ -125,320 +414,3 @@ async def _get_text_content(url: str) -> str:
|
||||
except Exception as e:
|
||||
logger.error(f"Error processing {url}: {e}")
|
||||
|
||||
|
||||
async def extract_keywords_stream(
|
||||
query: str,
|
||||
mode: str,
|
||||
limit: int,
|
||||
emit: EventCallback,
|
||||
) -> ExtractedKeywordsResponse:
|
||||
start_time = time.time()
|
||||
timeout_seconds = 60 # configurable
|
||||
await emit(KeywordsWsEvent(type="status", step="started", message="Starte Keyword-Extraktion").model_dump())
|
||||
|
||||
if mode == "url":
|
||||
await emit(KeywordsWsEvent(type="status", step="fetching_url", message=f"Extrahiere Inhalt von {query}").model_dump())
|
||||
text = await _get_text_content(query)
|
||||
await emit(KeywordsWsEvent(type="status", step="content_extracted", message=f"Extrahiert {len(text)} Zeichen").model_dump())
|
||||
system_prompt = KeywordsPrompt.EXTRACT_WEBSITE_KEYWORDS_PROMPT
|
||||
else:
|
||||
text = query
|
||||
await emit(KeywordsWsEvent(type="status", step="text_received", message=f"Empfangen {len(text)} Zeichen").model_dump())
|
||||
system_prompt = KeywordsPrompt.EXTRACT_KEYWORDS_TEXT_PROMPT
|
||||
user_prompt = "\nNow analyze the following text and return ONLY the JSON object.\n"
|
||||
if limit:
|
||||
user_prompt += f"\nExtract exactly {limit} keywords for each level (broad, coarse, fine).\n"
|
||||
user_prompt += f"\nInput:\n{text}"
|
||||
|
||||
await emit(KeywordsWsEvent(type="status", step="calling_llm", message="Extrahiere Keywords...").model_dump())
|
||||
|
||||
LEVELS = ("broad_keywords", "coarse_grained", "fine_grained")
|
||||
|
||||
# Holds only fully validated KeywordEntry dicts for each level
|
||||
confirmed: Dict[str, List[Dict[str, Any]]] = {level: [] for level in LEVELS}
|
||||
|
||||
async def emit_full_results() -> None:
|
||||
"""Attempt to build and validate the full ExtractedKeywordsLLM model and emit it."""
|
||||
# Build a dict with all three fields, using empty lists for missing ones
|
||||
data = {level: confirmed.get(level, []) for level in LEVELS}
|
||||
try:
|
||||
validated = ExtractedKeywordsLLM.model_validate(data)
|
||||
except ValidationError:
|
||||
# Should not happen if all items are valid, but guard against it
|
||||
return
|
||||
await emit(KeywordsWsEvent(type="keywords", keywords=validated.model_dump()).model_dump())
|
||||
|
||||
# adds completed keyword chunks to the confirmed dict and emits the full results when new valid items are found
|
||||
async def on_chunk(event: Dict[str, Any]) -> None:
|
||||
if event["type"] != "llm_chunk":
|
||||
await emit(event)
|
||||
return
|
||||
|
||||
try:
|
||||
partial = partial_json_parser.loads(event.get("_full_content", ""))
|
||||
except Exception:
|
||||
return
|
||||
|
||||
if not isinstance(partial, dict):
|
||||
return
|
||||
|
||||
grew = False
|
||||
|
||||
for level in LEVELS:
|
||||
current = partial.get(level) or []
|
||||
idx = len(confirmed[level])
|
||||
|
||||
while idx < len(current):
|
||||
raw_item = current[idx]
|
||||
try:
|
||||
validated_item = KeywordEntry.model_validate(raw_item)
|
||||
except ValidationError:
|
||||
break # item not complete yet
|
||||
confirmed[level].append(validated_item.model_dump())
|
||||
idx += 1
|
||||
grew = True
|
||||
|
||||
if grew:
|
||||
await emit_full_results()
|
||||
|
||||
# Accumulate full_content for incremental parsing
|
||||
full_content_holder = {"value": ""}
|
||||
|
||||
async def emit_wrapper(event: Dict[str, Any]) -> None:
|
||||
if event["type"] == "llm_chunk":
|
||||
full_content_holder["value"] += event["content"]
|
||||
event = {**event, "_full_content": full_content_holder["value"]}
|
||||
await on_chunk(event)
|
||||
|
||||
try:
|
||||
keywords = await asyncio.wait_for(
|
||||
llm.call_stream(
|
||||
system_prompt=system_prompt,
|
||||
user_prompt=user_prompt,
|
||||
json_schema=ExtractedKeywordsLLM.model_json_schema(),
|
||||
schema_name="extracted_keywords",
|
||||
temperature=0.8,
|
||||
top_p=0.95,
|
||||
emit=emit_wrapper,
|
||||
),
|
||||
timeout=timeout_seconds,
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
await emit(KeywordsWsEvent(type="error", message=f"LLM call timed out after {timeout_seconds}s").model_dump())
|
||||
raise RuntimeError("LLM streaming call timed out")
|
||||
except asyncio.CancelledError:
|
||||
await emit(KeywordsWsEvent(type="error", message="Request cancelled").model_dump())
|
||||
raise
|
||||
|
||||
if not keywords:
|
||||
await emit(KeywordsWsEvent(type="error", message="LLM call failed or returned no content").model_dump())
|
||||
raise RuntimeError("LLM streaming call returned empty content")
|
||||
|
||||
await emit(KeywordsWsEvent(type="status", step="parsing_response", message="Bearbeite Ergebnisse").model_dump())
|
||||
|
||||
try:
|
||||
keywords_json = json.loads(keywords)
|
||||
except json.JSONDecodeError as e:
|
||||
await emit(KeywordsWsEvent(type="error", message=f"Invalid JSON in LLM response: {e}").model_dump())
|
||||
raise RuntimeError("LLM response is not valid JSON")
|
||||
|
||||
# Final emission of the full results (in case the last chunk didn't trigger it)
|
||||
final_data = {level: confirmed.get(level, []) for level in LEVELS}
|
||||
try:
|
||||
final_validated = ExtractedKeywordsLLM.model_validate(keywords_json)
|
||||
except ValidationError:
|
||||
# Fallback: use our confirmed data
|
||||
final_validated = ExtractedKeywordsLLM.model_validate(final_data)
|
||||
|
||||
elapsed_time = time.time() - start_time
|
||||
result = ExtractedKeywordsResponse(
|
||||
results=final_validated,
|
||||
source=mode,
|
||||
source_url=query if mode == "url" else None,
|
||||
source_content=text,
|
||||
duration=elapsed_time,
|
||||
)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
async def extract_keywords_stream_enriched(
|
||||
query: str,
|
||||
mode: str,
|
||||
limit: int,
|
||||
emit: EventCallback,
|
||||
) -> ExtractedKeywordsResponse:
|
||||
start_time = time.time()
|
||||
timeout_seconds = 120
|
||||
await emit(KeywordsWsEvent(type="status", step="started", message="Starte Keyword-Extraktion").model_dump())
|
||||
|
||||
if mode == "url":
|
||||
await emit(KeywordsWsEvent(type="status", step="fetching_url", message=f"Extrahiere Inhalt von {query}").model_dump())
|
||||
text = await _get_text_content(query)
|
||||
await emit(KeywordsWsEvent(type="status", step="content_extracted", message=f"Extrahiert {len(text)} Zeichen").model_dump())
|
||||
system_prompt = KeywordsPrompt.EXTRACT_WEBSITE_KEYWORDS_PROMPT
|
||||
else:
|
||||
text = query
|
||||
await emit(KeywordsWsEvent(type="status", step="text_received", message=f"Empfangen {len(text)} Zeichen").model_dump())
|
||||
system_prompt = KeywordsPrompt.EXTRACT_KEYWORDS_TEXT_PROMPT
|
||||
|
||||
user_prompt = "\nNow analyze the following text.\n"
|
||||
if limit:
|
||||
user_prompt += f"\nExtract exactly {limit} keywords for each level.\n"
|
||||
user_prompt += f"\nInput:\n{text}"
|
||||
|
||||
await emit(KeywordsWsEvent(type="status", step="calling_llm", message="Extrahiere Keywords...").model_dump())
|
||||
|
||||
LEVELS = ("broad_keywords", "coarse_grained", "fine_grained")
|
||||
|
||||
# Holds enriched keyword wrappers for each level
|
||||
confirmed: Dict[str, List[KeywordEntryWithTopic]] = {level: [] for level in LEVELS}
|
||||
|
||||
# Track background enrichment tasks
|
||||
enrichment_tasks: List[asyncio.Task] = []
|
||||
|
||||
async def emit_full_results() -> None:
|
||||
"""Attempt to build and emit the full enriched keyword model."""
|
||||
try:
|
||||
validated = _build_enriched_snapshot(confirmed)
|
||||
except ValidationError:
|
||||
return
|
||||
await emit(KeywordsWsEvent(type="keywords", keywords=validated.model_dump()).model_dump())
|
||||
|
||||
async def get_openalex_topic(level: str, idx: int, item: KeywordEntry) -> None:
|
||||
"""
|
||||
Fetch/enrich metadata for a single keyword.
|
||||
Runs concurrently without blocking the LLM stream.
|
||||
"""
|
||||
try:
|
||||
topic = await vector_search_topics_batch(
|
||||
keywords=[item.keyword],
|
||||
search_type="hybrid",
|
||||
)
|
||||
# Update the shared confirmed list in-place (safe in asyncio)
|
||||
confirmed[level][idx].topic_mapping = topic.results[0] if topic.results else None
|
||||
|
||||
# Emit the full updated set after each enrichment so the frontend sees progress.
|
||||
await emit_full_results()
|
||||
|
||||
except asyncio.CancelledError:
|
||||
# If the whole request is cancelled, we can just re-raise
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error fetching OpenAlex topic for keyword '{item.keyword}': {e}")
|
||||
await emit_full_results()
|
||||
|
||||
# ---------- on_chunk: parses LLM stream and appends new keywords ----------
|
||||
async def on_chunk(event: Dict[str, Any]) -> None:
|
||||
if event["type"] != "llm_chunk":
|
||||
await emit(event)
|
||||
return
|
||||
|
||||
try:
|
||||
partial = partial_json_parser.loads(event.get("_full_content", ""))
|
||||
except Exception:
|
||||
return
|
||||
|
||||
if not isinstance(partial, dict):
|
||||
return
|
||||
|
||||
grew = False
|
||||
|
||||
for level in LEVELS:
|
||||
current = partial.get(level) or []
|
||||
start_idx = len(confirmed[level]) # Where we start appending
|
||||
|
||||
while len(confirmed[level]) < len(current):
|
||||
raw_item = current[len(confirmed[level])]
|
||||
try:
|
||||
validated_item = KeywordEntry.model_validate(raw_item)
|
||||
except ValidationError:
|
||||
break # item not complete yet
|
||||
|
||||
confirmed[level].append(KeywordEntryWithTopic(llm_keyword=validated_item))
|
||||
grew = True
|
||||
|
||||
# Launch openalex topic mapping
|
||||
for idx in range(start_idx, len(confirmed[level])):
|
||||
keyword_text = confirmed[level][idx].llm_keyword.keyword
|
||||
await emit(
|
||||
KeywordsWsEvent(
|
||||
type="status",
|
||||
step="enriching",
|
||||
message=f"Extracting topic for keyword '{keyword_text}'",
|
||||
).model_dump()
|
||||
)
|
||||
task = asyncio.create_task(get_openalex_topic(level, idx, confirmed[level][idx].llm_keyword))
|
||||
enrichment_tasks.append(task)
|
||||
|
||||
if grew:
|
||||
await emit_full_results()
|
||||
|
||||
# ---------- Accumulate full_content for incremental parsing ----------
|
||||
full_content_holder = {"value": ""}
|
||||
|
||||
async def emit_wrapper(event: Dict[str, Any]) -> None:
|
||||
if event["type"] == "llm_chunk":
|
||||
full_content_holder["value"] += event["content"]
|
||||
event = {**event, "_full_content": full_content_holder["value"]}
|
||||
await on_chunk(event)
|
||||
|
||||
# ---------- Call the LLM ----------
|
||||
try:
|
||||
keywords = await asyncio.wait_for(
|
||||
llm.call_stream(
|
||||
system_prompt=system_prompt,
|
||||
user_prompt=user_prompt,
|
||||
json_schema=ExtractedKeywordsLLM.model_json_schema(),
|
||||
schema_name="extracted_keywords",
|
||||
temperature=0.0,
|
||||
top_p=0.95,
|
||||
emit=emit_wrapper,
|
||||
),
|
||||
timeout=timeout_seconds,
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
await emit(KeywordsWsEvent(type="error", message=f"LLM call timed out after {timeout_seconds}s").model_dump())
|
||||
raise RuntimeError("LLM streaming call timed out")
|
||||
except asyncio.CancelledError:
|
||||
# Cancel all pending enrichment tasks to avoid dangling background work
|
||||
for task in enrichment_tasks:
|
||||
task.cancel()
|
||||
if enrichment_tasks:
|
||||
await asyncio.gather(*enrichment_tasks, return_exceptions=True)
|
||||
await emit(KeywordsWsEvent(type="error", message="Request cancelled").model_dump())
|
||||
raise
|
||||
|
||||
# ---------- Finalize ----------
|
||||
await emit(KeywordsWsEvent(type="status", step="parsing_response", message="Bearbeite Ergebnisse").model_dump())
|
||||
|
||||
try:
|
||||
keywords_json = json.loads(keywords)
|
||||
except json.JSONDecodeError as e:
|
||||
await emit(KeywordsWsEvent(type="error", message=f"Invalid JSON in LLM response: {e}").model_dump())
|
||||
raise RuntimeError("LLM response is not valid JSON")
|
||||
|
||||
# ---------- Wait for ALL pending enrichments to complete ----------
|
||||
if enrichment_tasks:
|
||||
await asyncio.gather(*enrichment_tasks, return_exceptions=True)
|
||||
|
||||
await emit_full_results()
|
||||
|
||||
# Build final response
|
||||
try:
|
||||
final_validated = _build_enriched_snapshot(confirmed)
|
||||
except ValidationError:
|
||||
final_validated = ExtractedKeywords.model_validate(
|
||||
{level: [item.model_dump() for item in confirmed.get(level, [])] for level in LEVELS}
|
||||
)
|
||||
|
||||
elapsed_time = time.time() - start_time
|
||||
result = ExtractedKeywordsResponse(
|
||||
results=final_validated,
|
||||
source=mode,
|
||||
source_url=query if mode == "url" else None,
|
||||
source_content=text,
|
||||
duration=elapsed_time,
|
||||
)
|
||||
|
||||
return result
|
||||
@@ -8,10 +8,21 @@ from typing import List, Literal
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from inse.topics.model import KeywordTopicMatch
|
||||
|
||||
class FileUpload(BaseModel):
|
||||
filename: str = Field(description="The name of the uploaded file.")
|
||||
content_base64: str = Field(description="The base64-encoded content of the uploaded file.")
|
||||
mime_type: str = Field(description="The MIME type of the uploaded file, e.g., 'application/pdf', 'image/png', etc.")
|
||||
|
||||
class KeywordsRequest(BaseModel):
|
||||
query: str = Field(description="The input text from which to extract keywords.")
|
||||
files: list[FileUpload] | None = None
|
||||
mode: str = Field(description="The mode of keyword extraction, e.g., 'url', 'text', or 'keywords'.")
|
||||
limit: int = Field(default=None, description="The maximum number of keywords to extract.")
|
||||
# class KeywordsRequest(BaseModel):
|
||||
# query: str = Field(description="The input text from which to extract keywords.")
|
||||
# mode: str = Field(description="The mode of keyword extraction, e.g., 'url', 'text', or 'keywords'.")
|
||||
# limit: int = Field(default=None, description="The maximum number of keywords to extract.")
|
||||
|
||||
class KeywordEntry(BaseModel):
|
||||
keyword: str = Field(description="The extracted keyword.")
|
||||
|
||||
@@ -35,13 +35,118 @@ class KeywordsPrompt(StrEnum):
|
||||
|
||||
---
|
||||
|
||||
# STRICT GROUNDING GUARDRAIL (HIGHEST PRIORITY)
|
||||
|
||||
The output must be strictly extractive and grounded in the input text.
|
||||
|
||||
## Mandatory Rules
|
||||
|
||||
1. Extract ONLY keywords, terms, entities, concepts, technologies, methods, materials, standards, diseases, applications, sectors, or noun phrases that explicitly appear in the input text.
|
||||
|
||||
2. Do NOT introduce, infer, generalize, expand, normalize, summarize, classify, enrich, or extrapolate concepts beyond what is directly present in the text.
|
||||
|
||||
3. Do NOT generate parent categories, broader domains, scientific disciplines, industries, or technology areas unless those exact terms appear in the input text.
|
||||
|
||||
Example:
|
||||
|
||||
Input contains:
|
||||
|
||||
"transformer-based machine learning framework"
|
||||
|
||||
Allowed:
|
||||
|
||||
* transformer-based machine learning framework
|
||||
* machine learning
|
||||
* transformer
|
||||
|
||||
Not allowed:
|
||||
|
||||
* Artificial Intelligence
|
||||
* Deep Learning
|
||||
* Neural Networks
|
||||
|
||||
unless those exact terms appear in the text.
|
||||
|
||||
4. Do NOT generate synonyms, abbreviations, alternate phrasings, normalized forms, or related concepts that do not explicitly appear in the source text.
|
||||
|
||||
Example:
|
||||
|
||||
Input:
|
||||
|
||||
"large language models"
|
||||
|
||||
Allowed:
|
||||
|
||||
* large language models
|
||||
|
||||
Not allowed:
|
||||
|
||||
* LLMs
|
||||
* Generative AI
|
||||
* Artificial Intelligence
|
||||
|
||||
unless explicitly present.
|
||||
|
||||
5. Do NOT generate implied concepts.
|
||||
|
||||
Example:
|
||||
|
||||
Input:
|
||||
|
||||
"patient records"
|
||||
|
||||
Not allowed:
|
||||
|
||||
* Healthcare
|
||||
* Medical Informatics
|
||||
* Clinical Documentation
|
||||
|
||||
unless explicitly mentioned.
|
||||
|
||||
6. Every keyword must have direct textual evidence in the input.
|
||||
|
||||
7. If a keyword cannot be highlighted verbatim or as a contiguous phrase in the source text, it must NOT appear in the output.
|
||||
|
||||
8. Prefer exact surface forms from the text.
|
||||
|
||||
9. Preserve original capitalization when possible.
|
||||
|
||||
10. Do not invent keywords to satisfy target counts.
|
||||
|
||||
11. When insufficient keywords exist for a level, return fewer keywords.
|
||||
|
||||
12. Grounding accuracy is more important than completeness.
|
||||
|
||||
13. Any keyword not directly supported by the text is considered an extraction error.
|
||||
|
||||
## Hierarchy Assignment Rules
|
||||
|
||||
The hierarchy is only an organizational grouping.
|
||||
|
||||
Do NOT create broader concepts to populate broad_keywords.
|
||||
|
||||
If the source text contains only specific concepts, place those concepts into the most appropriate level while remaining faithful to the text.
|
||||
|
||||
Do not create abstraction layers that are not explicitly present in the document.
|
||||
|
||||
## Self-Validation Before Output
|
||||
|
||||
Before returning the final JSON, verify every keyword:
|
||||
|
||||
* Can this exact phrase be found in the input text?
|
||||
* Can a user highlight the phrase directly in the source text?
|
||||
|
||||
If the answer is NO, remove the keyword.
|
||||
|
||||
---
|
||||
|
||||
# Keyword Hierarchy
|
||||
|
||||
## 1. broad_keywords
|
||||
|
||||
High-level domains, disciplines, industries, or technology areas.
|
||||
High-level domains, disciplines, industries, technology areas, or major themes explicitly present in the text.
|
||||
|
||||
Examples:
|
||||
Examples (only if explicitly mentioned):
|
||||
|
||||
* Artificial Intelligence
|
||||
* Healthcare
|
||||
@@ -50,15 +155,15 @@ class KeywordsPrompt(StrEnum):
|
||||
* Materials Science
|
||||
* Robotics
|
||||
|
||||
These should represent the major themes of the document.
|
||||
These should represent the major themes of the document when those themes are explicitly stated.
|
||||
|
||||
---
|
||||
|
||||
## 2. coarse_grained
|
||||
|
||||
Mid-level concepts, technologies, research areas, methods, or applications.
|
||||
Mid-level concepts, technologies, research areas, methods, applications, or technical topics explicitly present in the text.
|
||||
|
||||
Examples:
|
||||
Examples (only if explicitly mentioned):
|
||||
|
||||
* Machine Learning
|
||||
* Drug Discovery
|
||||
@@ -73,9 +178,9 @@ class KeywordsPrompt(StrEnum):
|
||||
|
||||
## 3. fine_grained
|
||||
|
||||
Highly specific technical concepts, algorithms, materials, protocols, standards, tools, products, datasets, biomarkers, or specialized terminology.
|
||||
Highly specific technical concepts, algorithms, materials, protocols, standards, tools, products, datasets, biomarkers, or specialized terminology explicitly present in the text.
|
||||
|
||||
Examples:
|
||||
Examples (only if explicitly mentioned):
|
||||
|
||||
* Transformer Architecture
|
||||
* CRISPR-Cas9
|
||||
@@ -114,21 +219,56 @@ class KeywordsPrompt(StrEnum):
|
||||
|
||||
# Extraction Rules
|
||||
|
||||
* Extract only concepts explicitly mentioned or strongly implied.
|
||||
* Extract only concepts explicitly mentioned in the text.
|
||||
* Do not use concepts that are merely implied, inferred, generalized, or derived.
|
||||
* Every keyword must be directly traceable to text spans in the input.
|
||||
* Prefer noun phrases.
|
||||
* Avoid complete sentences.
|
||||
* Avoid duplicates across levels whenever possible.
|
||||
* Do not invent technologies not supported by the text.
|
||||
* Prefer terminology that can be searched in scientific literature databases such as OpenAlex.
|
||||
* Return between 5 and 15 keywords per level when sufficient information exists.
|
||||
* If fewer valid keywords exist, return fewer.
|
||||
|
||||
---
|
||||
|
||||
# Output Schema
|
||||
|
||||
Return ONLY valid JSON.
|
||||
Return ONLY valid JSON using the following structure:
|
||||
|
||||
{
|
||||
"broad_keywords": [
|
||||
{
|
||||
"keyword": "string",
|
||||
"relevance_score": 0.0
|
||||
}
|
||||
],
|
||||
"coarse_grained": [
|
||||
{
|
||||
"keyword": "string",
|
||||
"relevance_score": 0.0
|
||||
}
|
||||
],
|
||||
"fine_grained": [
|
||||
{
|
||||
"keyword": "string",
|
||||
"relevance_score": 0.0
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
Requirements:
|
||||
|
||||
* Return ONLY valid JSON.
|
||||
* Do not include explanations.
|
||||
* Do not include markdown.
|
||||
* Do not include comments.
|
||||
* Do not include reasoning.
|
||||
* Do not include any text outside the JSON object.
|
||||
* Every keyword must be directly supported by the input text.
|
||||
* Any keyword not explicitly present in the source text must be excluded.
|
||||
|
||||
Return ONLY valid JSON matching the schema provided by the API.
|
||||
---
|
||||
|
||||
# Example 1
|
||||
@@ -136,269 +276,277 @@ class KeywordsPrompt(StrEnum):
|
||||
Input:
|
||||
|
||||
Researchers developed a transformer-based machine learning framework for predictive maintenance in industrial manufacturing. The system uses sensor fusion, anomaly detection, and time-series forecasting to reduce downtime in smart factories.
|
||||
|
||||
Output:
|
||||
|
||||
{"broad_keywords":[{"keyword":"ArtificialIntelligence","relevance_score":0.98},{"keyword":"Manufacturing","relevance_score":0.94},{"keyword":"IndustrialAutomation","relevance_score":0.90}],"coarse_grained":[{"keyword":"MachineLearning","relevance_score":0.96},{"keyword":"PredictiveMaintenance","relevance_score":0.95},{"keyword":"SmartFactories","relevance_score":0.88},{"keyword":"SensorFusion","relevance_score":0.86},{"keyword":"AnomalyDetection","relevance_score":0.85},{"keyword":"Time-SeriesForecasting","relevance_score":0.83}],"fine_grained":[{"keyword":"TransformerArchitecture","relevance_score":0.95},{"keyword":"IndustrialSensors","relevance_score":0.84},{"keyword":"MultimodalDataFusion","relevance_score":0.82},{"keyword":"PredictiveAnalytics","relevance_score":0.80}]}
|
||||
|
||||
broad_keywords":[{"keyword":"Industrial manufacturing","relevance_score":0.94}],"coarse_grained":[{"keyword":"Machine learning","relevance_score":0.97},{"keyword":"Predictive maintenance","relevance_score":0.95},{"keyword":"Sensor fusion","relevance_score":0.89},{"keyword":"Anomaly detection","relevance_score":0.88},{"keyword":"Time-series forecasting","relevance_score":0.87},{"keyword":"Smart factories","relevance_score":0.85}],"fine_grained":[{"keyword":"Transformer-based machine learning framework","relevance_score":0.96}]}
|
||||
---
|
||||
|
||||
# Example 2
|
||||
|
||||
Input:
|
||||
|
||||
A healthcare platform uses large language models and retrieval-augmented generation to automatically summarize patient records and support clinical decision-making.
|
||||
|
||||
A healthcare platform uses large language models and retrieval-augmented generation to automatically summarize patient records and support clinical decision-making.
|
||||
Output:
|
||||
|
||||
{"broad_keywords":[{"keyword":"Healthcare","relevance_score":0.97},{"keyword":"ArtificialIntelligence","relevance_score":0.95},{"keyword":"DigitalHealth","relevance_score":0.89}],"coarse_grained":[{"keyword":"LargeLanguageModels","relevance_score":0.96},{"keyword":"ClinicalDecisionSupport","relevance_score":0.92},{"keyword":"MedicalRecordAnalysis","relevance_score":0.90},{"keyword":"NaturalLanguageProcessing","relevance_score":0.88}],"fine_grained":[{"keyword":"Retrieval-AugmentedGeneration","relevance_score":0.95},{"keyword":"PatientRecordSummarization","relevance_score":0.91},{"keyword":"ClinicalDocumentation","relevance_score":0.86},{"keyword":"MedicalTextProcessing","relevance_score":0.84}]}
|
||||
{"broad_keywords":[{"keyword":"Healthcare","relevance_score":0.96}],"coarse_grained":[{"keyword":"Large language models","relevance_score":0.95},{"keyword":"Clinical decision-making","relevance_score":0.91},{"keyword":"Patient records","relevance_score":0.90}],"fine_grained":[{"keyword":"Retrieval-augmented generation","relevance_score":0.94}]}
|
||||
Return ONLY valid JSON matching the schema provided by the API.
|
||||
"""
|
||||
|
||||
|
||||
EXTRACT_WEBSITE_KEYWORDS_PROMPT = """
|
||||
You are an expert technology scout, scientific analyst, and innovation intelligence specialist.
|
||||
You are an expert technology scout, scientific analyst, and innovation intelligence specialist.
|
||||
|
||||
The input text was extracted automatically from a webpage using BeautifulSoup or a similar HTML parser.
|
||||
The input text was extracted automatically from a webpage using BeautifulSoup or a similar HTML parser.
|
||||
|
||||
The extracted text may contain:
|
||||
The extracted text may contain:
|
||||
|
||||
* Navigation menus
|
||||
* Headers and footers
|
||||
* Cookie notices
|
||||
* Marketing language
|
||||
* Contact information
|
||||
* Repeated sections
|
||||
* Calls to action
|
||||
* Legal disclaimers
|
||||
* Product pages
|
||||
* Blog articles
|
||||
* News articles
|
||||
* Landing pages
|
||||
* Navigation menus
|
||||
* Headers and footers
|
||||
* Cookie notices
|
||||
* Marketing language
|
||||
* Contact information
|
||||
* Repeated sections
|
||||
* Calls to action
|
||||
* Legal disclaimers
|
||||
* Product pages
|
||||
* Blog articles
|
||||
* News articles
|
||||
* Landing pages
|
||||
|
||||
Your first task is to identify the actual content and purpose of the webpage.
|
||||
Your first task is to identify the actual content and purpose of the webpage.
|
||||
|
||||
Ignore:
|
||||
Ignore:
|
||||
|
||||
* Navigation elements
|
||||
* Cookie banners
|
||||
* Legal notices
|
||||
* Copyright text
|
||||
* Generic marketing statements
|
||||
* Contact information
|
||||
* Login/signup content
|
||||
* Careers pages unless they contain relevant technical information
|
||||
* Repeated website boilerplate
|
||||
* Navigation elements
|
||||
* Cookie banners
|
||||
* Legal notices
|
||||
* Copyright text
|
||||
* Generic marketing statements
|
||||
* Contact information
|
||||
* Login/signup content
|
||||
* Careers pages unless they contain relevant technical information
|
||||
* Repeated website boilerplate
|
||||
|
||||
Focus only on content that helps identify:
|
||||
Focus only on the primary informational content of the webpage.
|
||||
|
||||
* Technologies
|
||||
* Scientific concepts
|
||||
* Research areas
|
||||
* Technical methods
|
||||
* Products
|
||||
* Applications
|
||||
* Industrial sectors
|
||||
* Materials
|
||||
* Standards
|
||||
* Diseases
|
||||
* Engineering disciplines
|
||||
* Innovation domains
|
||||
---
|
||||
|
||||
---
|
||||
# STRICT GROUNDING GUARDRAIL (HIGHEST PRIORITY)
|
||||
|
||||
# Step 1: Determine Page Type
|
||||
The output must be strictly extractive and grounded in the webpage text.
|
||||
|
||||
Determine which type of page is represented:
|
||||
## Mandatory Rules
|
||||
|
||||
* Technology/Product Page
|
||||
* Company Page
|
||||
* Research Article
|
||||
* Scientific Blog Post
|
||||
* News Article
|
||||
* Technical Documentation
|
||||
* White Paper
|
||||
* Industry Report
|
||||
* Other
|
||||
1. Extract ONLY keywords, entities, concepts, technologies, methods, products, materials, standards, diseases, applications, sectors, or noun phrases that explicitly appear in the webpage text.
|
||||
|
||||
Use this classification internally only.
|
||||
2. Do NOT introduce, infer, generalize, normalize, classify, enrich, expand, summarize, or extrapolate concepts beyond what is directly present in the text.
|
||||
|
||||
Do not include it in the output.
|
||||
3. Do NOT generate broader domains, scientific disciplines, industries, technology areas, research fields, or categories unless those exact terms appear in the webpage text.
|
||||
|
||||
---
|
||||
Example:
|
||||
|
||||
# Step 2: Extract Searchable Concepts
|
||||
Input:
|
||||
|
||||
Prioritize concepts that are useful for:
|
||||
"The platform uses large language models and retrieval-augmented generation."
|
||||
|
||||
* OpenAlex retrieval
|
||||
* Scientific literature discovery
|
||||
* Patent scouting
|
||||
* Technology scouting
|
||||
* Innovation monitoring
|
||||
Allowed:
|
||||
|
||||
Prefer canonical scientific terminology over marketing language.
|
||||
* large language models
|
||||
* retrieval-augmented generation
|
||||
|
||||
Examples:
|
||||
Not allowed:
|
||||
|
||||
Prefer:
|
||||
* Artificial Intelligence
|
||||
* Generative AI
|
||||
* Natural Language Processing
|
||||
|
||||
* Large Language Models
|
||||
unless explicitly present.
|
||||
|
||||
Instead of:
|
||||
4. Do NOT generate synonyms.
|
||||
|
||||
* AI Assistant
|
||||
Example:
|
||||
|
||||
Prefer:
|
||||
Input:
|
||||
|
||||
* Smart Manufacturing
|
||||
"AI assistant"
|
||||
|
||||
Instead of:
|
||||
Allowed:
|
||||
|
||||
* Factory Optimization Solution
|
||||
* AI assistant
|
||||
|
||||
Prefer:
|
||||
Not allowed:
|
||||
|
||||
* Retrieval-Augmented Generation
|
||||
* large language models
|
||||
* conversational AI
|
||||
* generative AI
|
||||
|
||||
Instead of:
|
||||
unless those exact terms appear.
|
||||
|
||||
* Intelligent Knowledge Assistant
|
||||
5. Do NOT generate canonical scientific terminology when it does not appear in the source text.
|
||||
|
||||
Prefer:
|
||||
6. Do NOT rewrite marketing terms into technical terms.
|
||||
|
||||
* Predictive Maintenance
|
||||
7. Every keyword must have direct textual evidence in the webpage content.
|
||||
|
||||
Instead of:
|
||||
8. If a keyword cannot be highlighted directly in the source text, it must NOT appear in the output.
|
||||
|
||||
* Equipment Performance Optimization
|
||||
9. Preserve original wording whenever possible.
|
||||
|
||||
---
|
||||
10. Do not invent keywords to satisfy target counts.
|
||||
|
||||
# Keyword Hierarchy
|
||||
11. When insufficient keywords exist, return fewer keywords.
|
||||
|
||||
## broad_keywords
|
||||
12. Grounding accuracy is more important than completeness.
|
||||
|
||||
High-level domains, industries, disciplines, or technology areas.
|
||||
13. Any keyword not directly supported by the webpage text is considered an extraction error.
|
||||
|
||||
Examples:
|
||||
---
|
||||
|
||||
* Artificial Intelligence
|
||||
* Healthcare
|
||||
* Manufacturing
|
||||
* Energy Storage
|
||||
* Biotechnology
|
||||
* Robotics
|
||||
# Step 1: Determine Page Type
|
||||
|
||||
---
|
||||
Determine internally whether the page is:
|
||||
|
||||
## coarse_grained
|
||||
* Technology/Product Page
|
||||
* Company Page
|
||||
* Research Article
|
||||
* Scientific Blog Post
|
||||
* News Article
|
||||
* Technical Documentation
|
||||
* White Paper
|
||||
* Industry Report
|
||||
* Other
|
||||
|
||||
Technologies, methods, research fields, and applications.
|
||||
Use this classification only to identify the relevant content and remove boilerplate.
|
||||
|
||||
Examples:
|
||||
Do NOT include the classification in the output.
|
||||
|
||||
* Machine Learning
|
||||
* Predictive Maintenance
|
||||
* Drug Discovery
|
||||
* Smart Manufacturing
|
||||
* Computer Vision
|
||||
* Clinical Decision Support
|
||||
---
|
||||
|
||||
---
|
||||
# Step 2: Extract Searchable Concepts
|
||||
|
||||
## fine_grained
|
||||
Extract concepts directly present in the page that are useful for:
|
||||
|
||||
Specific technical concepts, algorithms, materials, standards, tools, products, datasets, biomarkers, or protocols.
|
||||
* OpenAlex retrieval
|
||||
* Scientific literature discovery
|
||||
* Patent scouting
|
||||
* Technology scouting
|
||||
* Innovation monitoring
|
||||
|
||||
Examples:
|
||||
The extracted concepts must remain faithful to the wording used in the webpage.
|
||||
|
||||
* Transformer Architecture
|
||||
* CRISPR-Cas9
|
||||
* OPC UA
|
||||
* Retrieval-Augmented Generation
|
||||
* YOLOv8
|
||||
* Lithium Iron Phosphate
|
||||
Do NOT replace webpage terminology with your own preferred terminology.
|
||||
|
||||
---
|
||||
---
|
||||
|
||||
# Relevance Score
|
||||
# Keyword Hierarchy
|
||||
|
||||
Assign a relevance score between 0.0 and 1.0.
|
||||
## broad_keywords
|
||||
|
||||
Guidelines:
|
||||
High-level domains, industries, disciplines, technology areas, products, services, or major themes that explicitly appear in the webpage.
|
||||
|
||||
* 1.00 = central topic of the webpage
|
||||
* 0.90 = major topic
|
||||
* 0.80 = highly relevant
|
||||
* 0.70 = supporting concept
|
||||
* 0.60 = secondary concept
|
||||
Only use this level when such broad concepts are explicitly present.
|
||||
|
||||
Avoid scores below 0.60 unless necessary.
|
||||
Examples:
|
||||
|
||||
---
|
||||
* Healthcare
|
||||
* Biotechnology
|
||||
* Manufacturing
|
||||
* Robotics
|
||||
* Financial Technology
|
||||
|
||||
# Additional Rules
|
||||
only if those exact concepts appear in the webpage.
|
||||
|
||||
* Extract only concepts supported by the page content.
|
||||
* Do not hallucinate technologies.
|
||||
* Avoid generic company descriptions.
|
||||
* Avoid generic business terminology.
|
||||
* Prefer terminology suitable for scientific literature search.
|
||||
* Prefer concepts that could appear in OpenAlex, patents, technical reports, or academic publications.
|
||||
* Remove duplicates across hierarchy levels whenever possible.
|
||||
* Rank keywords by importance.
|
||||
---
|
||||
|
||||
---
|
||||
# Example 3 — News Article
|
||||
## coarse_grained
|
||||
|
||||
## Input
|
||||
Technologies, methods, research fields, applications, products, services, or technical topics explicitly present in the webpage.
|
||||
|
||||
Apple announced a new generation of custom AI chips designed for on-device inference. The chips will power future iPhone and Mac devices, improving privacy, latency, and energy efficiency for generative AI applications.
|
||||
Examples:
|
||||
|
||||
## Output
|
||||
* Machine Learning
|
||||
* Predictive Maintenance
|
||||
* Drug Discovery
|
||||
* Smart Manufacturing
|
||||
* Clinical Decision Support
|
||||
|
||||
```json{"broad_keywords":[{"keyword":"Technology","relevance_score":0.98},{"keyword":"ArtificialIntelligence","relevance_score":0.97},{"keyword":"ConsumerElectronics","relevance_score":0.92}],"coarse_grained":[{"keyword":"AIHardware","relevance_score":0.96},{"keyword":"SemiconductorDesign","relevance_score":0.93},{"keyword":"EdgeComputing","relevance_score":0.90},{"keyword":"GenerativeAI","relevance_score":0.88}],"fine_grained":[{"keyword":"On-DeviceInference","relevance_score":0.95},{"keyword":"CustomAIChips","relevance_score":0.94},{"keyword":"InferenceAcceleration","relevance_score":0.89},{"keyword":"Low-LatencyProcessing","relevance_score":0.86}]}```
|
||||
only if explicitly present.
|
||||
|
||||
---
|
||||
---
|
||||
|
||||
# Example 4 — Product Page
|
||||
## fine_grained
|
||||
|
||||
## Input
|
||||
Highly specific technical concepts, algorithms, materials, standards, tools, products, datasets, biomarkers, protocols, model names, framework names, software packages, or specialized terminology explicitly present in the webpage.
|
||||
|
||||
The Sony WH-1000XM6 wireless headphones feature adaptive noise cancellation, Bluetooth 5.4 connectivity, 40-hour battery life, multipoint device pairing, and spatial audio support.
|
||||
Examples:
|
||||
|
||||
## Output
|
||||
* FastAPI
|
||||
* OpenAPI
|
||||
* Pydantic
|
||||
* CRISPR-Cas9
|
||||
* Retrieval-Augmented Generation
|
||||
* OPC UA
|
||||
|
||||
```json{"broad_keywords":[{"keyword":"ConsumerElectronics","relevance_score":0.98},{"keyword":"AudioTechnology","relevance_score":0.95}],"coarse_grained":[{"keyword":"WirelessHeadphones","relevance_score":0.97},{"keyword":"NoiseCancellation","relevance_score":0.95},{"keyword":"BluetoothAudio","relevance_score":0.92}],"fine_grained":[{"keyword":"AdaptiveNoiseCancellation","relevance_score":0.96},{"keyword":"Bluetooth5.4","relevance_score":0.94},{"keyword":"MultipointPairing","relevance_score":0.89},{"keyword":"SpatialAudio","relevance_score":0.87}]}```
|
||||
only if explicitly present.
|
||||
|
||||
---
|
||||
---
|
||||
|
||||
# Example 5 — Technical Documentation
|
||||
# Relevance Score
|
||||
|
||||
## Input
|
||||
Assign a relevance score between 0.0 and 1.0.
|
||||
|
||||
FastAPI is a modern Python web framework for building APIs. It provides automatic OpenAPI schema generation, dependency injection, asynchronous request handling, and data validation through Pydantic models.
|
||||
Guidelines:
|
||||
|
||||
## Output
|
||||
* 1.00 = central topic of the webpage
|
||||
* 0.90 = major topic
|
||||
* 0.80 = highly relevant
|
||||
* 0.70 = supporting concept
|
||||
* 0.60 = secondary concept
|
||||
|
||||
```json{"broad_keywords":[{"keyword":"SoftwareDevelopment","relevance_score":0.98},{"keyword":"WebDevelopment","relevance_score":0.95}],"coarse_grained":[{"keyword":"PythonFrameworks","relevance_score":0.97},{"keyword":"APIDevelopment","relevance_score":0.95},{"keyword":"BackendEngineering","relevance_score":0.91}],"fine_grained":[{"keyword":"FastAPI","relevance_score":0.99},{"keyword":"OpenAPI","relevance_score":0.95},{"keyword":"DependencyInjection","relevance_score":0.90},{"keyword":"Pydantic","relevance_score":0.89},{"keyword":"AsynchronousRequestHandling","relevance_score":0.87}]}```
|
||||
Avoid scores below 0.60 unless necessary.
|
||||
|
||||
---
|
||||
Rank keywords by importance.
|
||||
|
||||
# Example 6 — Company Website
|
||||
---
|
||||
|
||||
## Input
|
||||
# Extraction Rules
|
||||
|
||||
Stripe provides online payment infrastructure for businesses. Its platform supports payment processing, subscription billing, fraud prevention, financial reporting, and global commerce operations.
|
||||
* Extract only concepts explicitly mentioned in the webpage text.
|
||||
* Do not use concepts that are merely implied, inferred, generalized, or derived.
|
||||
* Every keyword must be directly traceable to text spans in the webpage.
|
||||
* Prefer noun phrases.
|
||||
* Avoid complete sentences.
|
||||
* Avoid duplicates across hierarchy levels whenever possible.
|
||||
* Preserve original wording.
|
||||
* Rank keywords by importance.
|
||||
* Return between 5 and 15 keywords per level when sufficient information exists.
|
||||
* If fewer valid keywords exist, return fewer.
|
||||
|
||||
## Output
|
||||
---
|
||||
|
||||
```json{"broad_keywords":[{"keyword":"FinancialTechnology","relevance_score":0.98},{"keyword":"BusinessServices","relevance_score":0.91}],"coarse_grained":[{"keyword":"PaymentProcessing","relevance_score":0.97},{"keyword":"DigitalPayments","relevance_score":0.95},{"keyword":"SubscriptionManagement","relevance_score":0.90}],"fine_grained":[{"keyword":"StripePlatform","relevance_score":0.99},{"keyword":"FraudPrevention","relevance_score":0.91},{"keyword":"RecurringBilling","relevance_score":0.89},{"keyword":"GlobalPaymentInfrastructure","relevance_score":0.87}]}```
|
||||
# Self-Validation Before Output
|
||||
|
||||
---
|
||||
For every keyword, verify:
|
||||
|
||||
* Can this exact phrase be found in the webpage text?
|
||||
* Can a user highlight the phrase directly in the extracted content?
|
||||
|
||||
If the answer is NO, remove the keyword.
|
||||
|
||||
---
|
||||
|
||||
# Example — Technical Documentation
|
||||
|
||||
Input:
|
||||
|
||||
FastAPI is a modern Python web framework for building APIs. It provides automatic OpenAPI schema generation, dependency injection, asynchronous request handling, and data validation through Pydantic models.
|
||||
|
||||
Output:
|
||||
|
||||
{"broad_keywords":[{"keyword":"Python web framework","relevance_score":0.95}],"coarse_grained":[{"keyword":"building APIs","relevance_score":0.93},{"keyword":"Data validation","relevance_score":0.90}],"fine_grained":[{"keyword":"FastAPI","relevance_score":0.99},{"keyword":"OpenAPI","relevance_score":0.95},{"keyword":"Dependency Injection","relevance_score":0.91},{"keyword":"Asynchronous Request Handling","relevance_score":0.89},{"keyword":"Pydantic","relevance_score":0.88}]}
|
||||
|
||||
Return ONLY valid JSON matching the schema provided by the API.
|
||||
|
||||
Return ONLY valid JSON matching the schema provided by the API.
|
||||
"""
|
||||
|
||||
SIMPLE_TEXT_PROMPT = """
|
||||
|
||||
@@ -8,10 +8,13 @@ import asyncio
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Body, WebSocket, WebSocketDisconnect
|
||||
from uvicorn.protocols.utils import ClientDisconnected
|
||||
|
||||
from . import logic
|
||||
from inse.keywords.model import ExtractedKeywordsResponse, KeywordsRequest
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(
|
||||
prefix="/api/inse-service",
|
||||
@@ -19,89 +22,79 @@ router = APIRouter(
|
||||
responses={404: {"description": "Not found"}},
|
||||
)
|
||||
|
||||
|
||||
|
||||
|
||||
@router.websocket("/keywords/extract/ws")
|
||||
async def extract_keywords_ws(websocket: WebSocket):
|
||||
print("WebSocket connection established for keyword extraction.")
|
||||
await websocket.accept()
|
||||
|
||||
disconnected = asyncio.Event()
|
||||
extraction_task: asyncio.Task | None = None
|
||||
def _is_socket_open() -> bool:
|
||||
return not disconnected.is_set() and websocket.application_state.name != "DISCONNECTED"
|
||||
|
||||
async def emit(event: dict):
|
||||
if not _is_socket_open():
|
||||
return
|
||||
try:
|
||||
await websocket.send_json(event)
|
||||
except (WebSocketDisconnect, ClientDisconnected):
|
||||
disconnected.set()
|
||||
|
||||
async def safe_send(payload: dict):
|
||||
if not _is_socket_open():
|
||||
return
|
||||
try:
|
||||
await websocket.send_json(payload)
|
||||
except (WebSocketDisconnect, ClientDisconnected):
|
||||
disconnected.set()
|
||||
|
||||
try:
|
||||
raw = await websocket.receive_json()
|
||||
request = KeywordsRequest(**raw)
|
||||
disconnected = asyncio.Event()
|
||||
|
||||
async def emit(event: dict):
|
||||
if disconnected.is_set():
|
||||
return
|
||||
await websocket.send_json(event)
|
||||
|
||||
async def watch_disconnect() -> None:
|
||||
while True:
|
||||
message = await websocket.receive()
|
||||
if message["type"] == "websocket.disconnect":
|
||||
disconnected.set()
|
||||
return
|
||||
|
||||
request = KeywordsRequest(**raw)
|
||||
extraction_task = asyncio.create_task(
|
||||
logic.extract_keywords_stream_enriched(
|
||||
query=request.query,
|
||||
mode=request.mode,
|
||||
limit=request.limit,
|
||||
files=request.files,
|
||||
emit=emit,
|
||||
)
|
||||
)
|
||||
disconnect_task = asyncio.create_task(watch_disconnect())
|
||||
|
||||
done, pending = await asyncio.wait(
|
||||
{extraction_task, disconnect_task},
|
||||
return_when=asyncio.FIRST_COMPLETED,
|
||||
)
|
||||
result = await extraction_task
|
||||
|
||||
if disconnect_task in done:
|
||||
disconnected.set()
|
||||
await safe_send({
|
||||
"type": "completed",
|
||||
"result": result.model_dump(),
|
||||
})
|
||||
|
||||
except (WebSocketDisconnect, ClientDisconnected):
|
||||
disconnected.set()
|
||||
logger.info("Client disconnected from keyword extraction ws")
|
||||
|
||||
except Exception as e:
|
||||
disconnected.set()
|
||||
logger.exception("Error in keyword extraction ws")
|
||||
await safe_send({
|
||||
"type": "error",
|
||||
"message": str(e),
|
||||
})
|
||||
|
||||
finally:
|
||||
if extraction_task is not None and not extraction_task.done():
|
||||
extraction_task.cancel()
|
||||
try:
|
||||
await extraction_task
|
||||
except asyncio.CancelledError:
|
||||
except (asyncio.CancelledError, Exception):
|
||||
pass
|
||||
return
|
||||
|
||||
disconnect_task.cancel()
|
||||
try:
|
||||
await disconnect_task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
result = extraction_task.result()
|
||||
|
||||
await websocket.send_json({"type": "completed", "result": result.model_dump()})
|
||||
|
||||
except WebSocketDisconnect:
|
||||
print("WebSocket disconnected.")
|
||||
pass
|
||||
except Exception as e:
|
||||
await websocket.send_json({"type": "error", "message": str(e)})
|
||||
finally:
|
||||
if websocket.application_state.name != "DISCONNECTED":
|
||||
await websocket.close()
|
||||
|
||||
# @router.post(
|
||||
# "/keywords/extract",
|
||||
# operation_id="extractKeywords",
|
||||
# response_model=ExtractedKeywordsResponse,
|
||||
# )
|
||||
# async def extract_keywords(
|
||||
# request: Annotated[
|
||||
# KeywordsRequest,
|
||||
# Body(description="Input text for keyword extraction"),
|
||||
# ],
|
||||
# ):
|
||||
# async def noop(_: dict):
|
||||
# pass
|
||||
|
||||
# return await logic.extract_keywords_stream(
|
||||
# query=request.query,
|
||||
# mode=request.mode,
|
||||
# limit=request.limit,
|
||||
# emit=noop,
|
||||
# )
|
||||
if _is_socket_open():
|
||||
try:
|
||||
await websocket.close()
|
||||
except RuntimeError:
|
||||
logger.debug("WebSocket already closed, skipping close()")
|
||||
|
||||
@router.post(
|
||||
"/keywords/extract",
|
||||
@@ -118,3 +111,5 @@ async def extract_keywords(
|
||||
|
||||
):
|
||||
return await logic.extract_keywords(query=request.query, mode=request.mode, limit=request.limit)
|
||||
|
||||
|
||||
|
||||
@@ -24,7 +24,9 @@ from inse.exceptions import (
|
||||
)
|
||||
from inse.funders.service import router as funders_service_router
|
||||
from inse.projects.router import router as projects_router
|
||||
from inse.university_ranking.router import router as university_ranking_router
|
||||
from inse.university_ranking.service import router as university_ranking_router
|
||||
from inse.keywords.service import router as keywords_service_router
|
||||
from inse.patents.keywords.service import router as keywords_patents_router
|
||||
|
||||
# caching
|
||||
from inse.middleware.etag_cache import ETagCacheMiddleware
|
||||
@@ -32,13 +34,11 @@ from inse.persons.service import router as persons_service_router
|
||||
from inse.topics.service import router as topics_service_router
|
||||
from inse.works.service import router as works_service_router
|
||||
from inse.news.service import router as news_service_router
|
||||
from inse.patents.service import router as patents_service_router
|
||||
from inse.keywords.service import router as keywords_service_router
|
||||
|
||||
from inse.auth.router import router as auth_router
|
||||
from inse.account_management.router import router as account_management_router
|
||||
from inse.organization_management.router import router as organization_management_router
|
||||
|
||||
from inse.dashboard.router import router as dashboard_router
|
||||
from inse.bookmarks.router import router as bookmarks_router
|
||||
|
||||
from inse.institutions.router import router as institutions_router
|
||||
from inse.database import create_db_and_tables, get_session
|
||||
@@ -53,6 +53,9 @@ from inse.patents.service import (
|
||||
router as patents_service_router,
|
||||
)
|
||||
|
||||
from inse.works.purpose_router import router as works_purpose_router
|
||||
from inse.works.v2.router import router as works_v2_router
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
### startup
|
||||
@@ -83,6 +86,7 @@ app.include_router(institution_patents_router)
|
||||
app.include_router(org_patents_router)
|
||||
app.include_router(institutions_router)
|
||||
app.include_router(topics_service_router)
|
||||
app.include_router(works_purpose_router)
|
||||
app.include_router(works_service_router)
|
||||
app.include_router(persons_service_router)
|
||||
app.include_router(funders_service_router)
|
||||
@@ -93,16 +97,21 @@ app.include_router(university_ranking_router)
|
||||
app.include_router(projects_router)
|
||||
app.include_router(patents_all_router)
|
||||
app.include_router(keywords_service_router)
|
||||
app.include_router(keywords_patents_router)
|
||||
|
||||
app.include_router(service_router)
|
||||
|
||||
app.include_router(auth_router)
|
||||
app.include_router(account_management_router)
|
||||
app.include_router(organization_management_router)
|
||||
app.include_router(works_v2_router)
|
||||
|
||||
app.include_router(dashboard_router)
|
||||
app.include_router(bookmarks_router)
|
||||
|
||||
app.add_middleware(
|
||||
ETagCacheMiddleware,
|
||||
ttl=300, # 5 minutes expiration time
|
||||
ttl=120, # 2 minutes expiration time
|
||||
)
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
@@ -116,6 +125,7 @@ app.add_middleware(
|
||||
|
||||
# exception handlers
|
||||
|
||||
|
||||
@app.exception_handler(NotFoundException)
|
||||
async def handle_not_found(request: Request, exc: NotFoundException):
|
||||
return JSONResponse(status_code=404, content={"message": str(exc)})
|
||||
@@ -124,13 +134,18 @@ async def handle_not_found(request: Request, exc: NotFoundException):
|
||||
@app.exception_handler(ElasticsearchException)
|
||||
async def handle_elasticsearch_error(request: Request, exc: ElasticsearchException):
|
||||
logger.error("Elasticsearch integration error: %s", str(exc))
|
||||
return JSONResponse(status_code=502, content={"message": "Search service temporarily unavailable"})
|
||||
return JSONResponse(
|
||||
status_code=502, content={"message": "Search service temporarily unavailable"}
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(MissingApiKeyError)
|
||||
async def handle_missing_api_key(request: Request, exc: MissingApiKeyError):
|
||||
logger.error("Configuration error: %s", str(exc))
|
||||
return JSONResponse(status_code=503, content={"message": str(exc) or "Search service is not configured"})
|
||||
return JSONResponse(
|
||||
status_code=503,
|
||||
content={"message": str(exc) or "Search service is not configured"},
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(UpstreamAPIException)
|
||||
|
||||
@@ -1,74 +1,161 @@
|
||||
# middleware/etag_cache.py
|
||||
import hashlib
|
||||
import json
|
||||
import time
|
||||
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import Response
|
||||
|
||||
|
||||
class ETagCacheMiddleware(BaseHTTPMiddleware):
|
||||
def __init__(self, app, ttl: int = 60):
|
||||
super().__init__(app)
|
||||
self.ttl = ttl # timeout in seconds
|
||||
self.cache: dict[str, dict] = {} # key → {body, etag, expires}
|
||||
|
||||
def _cache_key(self, request: Request) -> str:
|
||||
# Include query params and relevant headers in the key
|
||||
return f"{request.url.path}?{request.url.query}"
|
||||
|
||||
def _content_type(self, response: Response) -> str | None:
|
||||
return response.headers.get("content-type")
|
||||
|
||||
async def dispatch(self, request: Request, call_next):
|
||||
if request.method != "GET":
|
||||
return await call_next(request)
|
||||
|
||||
if request.url.path.startswith(("/api/auth", "/api/accounts")):
|
||||
return await call_next(request)
|
||||
|
||||
if request.headers.get("authorization"):
|
||||
return await call_next(request)
|
||||
|
||||
key = self._cache_key(request)
|
||||
entry = self.cache.get(key)
|
||||
client_etag = request.headers.get("if-none-match")
|
||||
|
||||
# Cache hit + not expired
|
||||
if entry and time.time() < entry["expires"]:
|
||||
if client_etag == entry["etag"]:
|
||||
headers = {"ETag": entry["etag"]}
|
||||
if entry.get("content_type"):
|
||||
headers["Content-Type"] = entry["content_type"]
|
||||
return Response(status_code=304, headers=headers)
|
||||
|
||||
# Client has stale ETag - return fresh cached body
|
||||
headers = {"ETag": entry["etag"], "Cache-Control": f"max-age={self.ttl}"}
|
||||
if entry.get("content_type"):
|
||||
headers["Content-Type"] = entry["content_type"]
|
||||
return Response(
|
||||
content=entry["body"],
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
# Cache miss or expired → hit the actual route
|
||||
response = await call_next(request)
|
||||
body = b"".join([chunk async for chunk in response.body_iterator])
|
||||
etag = f'"{hashlib.md5(body).hexdigest()}"'
|
||||
content_type = self._content_type(response)
|
||||
|
||||
self.cache[key] = {
|
||||
"body": body,
|
||||
"etag": etag,
|
||||
"expires": time.time() + self.ttl,
|
||||
"content_type": content_type,
|
||||
}
|
||||
headers = {"ETag": etag, "Cache-Control": f"max-age={self.ttl}"}
|
||||
if content_type:
|
||||
headers["Content-Type"] = content_type
|
||||
return Response(
|
||||
content=body,
|
||||
status_code=response.status_code,
|
||||
headers=headers,
|
||||
)
|
||||
# middleware/etag_cache.py
|
||||
|
||||
import hashlib
|
||||
import time
|
||||
from collections import OrderedDict
|
||||
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import Response
|
||||
|
||||
# Paths excluded from caching entirely (everything concerning auth/identity/mutations)
|
||||
EXCLUDED_PATHS = (
|
||||
"/api/auth/v2",
|
||||
"/api/accounts",
|
||||
"/api/bookmarks",
|
||||
"/api/organizations",
|
||||
)
|
||||
|
||||
# POST is opt-out. Add any endpoint here that MUTATES state (create/update/delete/
|
||||
# trigger side effects), even if it "usually" returns 200.
|
||||
EXCLUDED_POST_PATHS = (
|
||||
# "/api/notes/mark-read",
|
||||
)
|
||||
|
||||
# Don't buffer/hash large POST bodies (e.g. uploads) just to compute a cache key.
|
||||
MAX_CACHEABLE_BODY_SIZE = 64 * 1024 # 64 KB
|
||||
|
||||
|
||||
class ETagCacheMiddleware(BaseHTTPMiddleware):
|
||||
def __init__(self, app, ttl: int = 60, maxsize: int = 5000):
|
||||
super().__init__(app)
|
||||
self.ttl = ttl
|
||||
self.maxsize = maxsize
|
||||
# Insertion-ordered so we can evict the oldest entry in O(1) when over capacity.
|
||||
self.cache: "OrderedDict[str, dict]" = OrderedDict()
|
||||
|
||||
def _get(self, key: str) -> dict | None:
|
||||
entry = self.cache.get(key)
|
||||
if entry is None:
|
||||
return None
|
||||
if time.time() >= entry["expires"]:
|
||||
del self.cache[key]
|
||||
return None
|
||||
return entry
|
||||
|
||||
def _set(self, key: str, value: dict) -> None:
|
||||
# Refreshing an existing key should count as "newest" for
|
||||
# eviction purposes, so drop it first if present.
|
||||
if key in self.cache:
|
||||
del self.cache[key]
|
||||
|
||||
# Clear a few expired entries so the cache
|
||||
# doesn't fill up with dead weight between accesses.
|
||||
now = time.time()
|
||||
expired_keys = []
|
||||
for k, v in self.cache.items():
|
||||
if len(expired_keys) >= 50:
|
||||
break
|
||||
if v["expires"] <= now:
|
||||
expired_keys.append(k)
|
||||
for k in expired_keys:
|
||||
del self.cache[k]
|
||||
|
||||
# Hard cap: evict oldest-inserted entries until there's room.
|
||||
while len(self.cache) >= self.maxsize:
|
||||
self.cache.popitem(last=False)
|
||||
|
||||
self.cache[key] = value
|
||||
|
||||
def _user_id(self, request: Request) -> str | None:
|
||||
auth_header = request.headers.get("authorization")
|
||||
if not auth_header:
|
||||
return None
|
||||
return hashlib.sha256(auth_header.encode()).hexdigest()[:16]
|
||||
|
||||
def _cache_key(self, request: Request, body: bytes = b"") -> str:
|
||||
user_id = self._user_id(request)
|
||||
base = f"{request.method}:{request.url.path}?{request.url.query}"
|
||||
if body:
|
||||
base += f":{hashlib.sha256(body).hexdigest()[:16]}"
|
||||
if user_id:
|
||||
return f"{user_id}:{base}"
|
||||
return base
|
||||
|
||||
def _content_type(self, response: Response) -> str | None:
|
||||
return response.headers.get("content-type")
|
||||
|
||||
def _is_cacheable_request(self, request: Request) -> bool:
|
||||
if request.url.path.startswith(EXCLUDED_PATHS):
|
||||
return False
|
||||
if request.method == "GET":
|
||||
return True
|
||||
if request.method == "POST":
|
||||
return not request.url.path.startswith(EXCLUDED_POST_PATHS)
|
||||
return False
|
||||
|
||||
async def dispatch(self, request: Request, call_next):
|
||||
if not self._is_cacheable_request(request):
|
||||
return await call_next(request)
|
||||
|
||||
body_bytes = b""
|
||||
if request.method == "POST":
|
||||
content_length = request.headers.get("content-length")
|
||||
if content_length and int(content_length) > MAX_CACHEABLE_BODY_SIZE:
|
||||
# Too large to safely cache/key on — bypass entirely.
|
||||
return await call_next(request)
|
||||
|
||||
# Starlette caches the body internally after this read, so
|
||||
# downstream handlers (call_next) can still read it normally.
|
||||
body_bytes = await request.body()
|
||||
if len(body_bytes) > MAX_CACHEABLE_BODY_SIZE:
|
||||
return await call_next(request)
|
||||
|
||||
key = self._cache_key(request, body_bytes)
|
||||
entry = self._get(key)
|
||||
client_etag = request.headers.get("if-none-match")
|
||||
|
||||
# Cache hit + not expired
|
||||
if entry:
|
||||
if client_etag == entry["etag"]:
|
||||
headers = {"ETag": entry["etag"]}
|
||||
if entry.get("content_type"):
|
||||
headers["Content-Type"] = entry["content_type"]
|
||||
return Response(status_code=304, headers=headers)
|
||||
|
||||
headers = {"ETag": entry["etag"], "Cache-Control": f"max-age={self.ttl}"}
|
||||
if entry.get("content_type"):
|
||||
headers["Content-Type"] = entry["content_type"]
|
||||
return Response(
|
||||
content=entry["body"],
|
||||
status_code=entry["status_code"],
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
# Cache miss or expired → hit the actual route
|
||||
response = await call_next(request)
|
||||
body = b"".join([chunk async for chunk in response.body_iterator])
|
||||
etag = f'"{hashlib.md5(body).hexdigest()}"'
|
||||
content_type = self._content_type(response)
|
||||
|
||||
# Only cache clean, non-mutating-looking successes. 201/202/204 etc.
|
||||
if response.status_code == 200:
|
||||
self._set(
|
||||
key,
|
||||
{
|
||||
"body": body,
|
||||
"etag": etag,
|
||||
"status_code": response.status_code,
|
||||
"content_type": content_type,
|
||||
"expires": time.time() + self.ttl,
|
||||
},
|
||||
)
|
||||
|
||||
headers = {"ETag": etag, "Cache-Control": f"max-age={self.ttl}"}
|
||||
if content_type:
|
||||
headers["Content-Type"] = content_type
|
||||
return Response(
|
||||
content=body,
|
||||
status_code=response.status_code,
|
||||
headers=headers,
|
||||
)
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user