Compare commits
289
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
15f55af4c4 | ||
|
|
934c49bf49 | ||
|
|
70d6b3d698 | ||
|
|
e6e9628837 | ||
|
|
e1b3318e68 | ||
|
|
4d8a7405ca | ||
|
|
f1a6c32e0c | ||
|
|
cf5a3e7d3d | ||
|
|
89f45082fb | ||
|
|
0ad6ac70ff | ||
|
|
e8e0decc6c | ||
|
|
57aaf77162 | ||
|
|
a3eebedb02 | ||
|
|
f8e5cd90a5 | ||
|
|
07ce24143b | ||
|
|
3d092b02f3 | ||
|
|
bf5e065520 | ||
|
|
08178e74d2 | ||
|
|
c66fcff906 | ||
|
|
b0dd0e509d | ||
|
|
719da6e921 | ||
|
|
e4b3d0a9a9 | ||
|
|
c0e231a32b | ||
|
|
af9f9a25da | ||
|
|
0a465bc7e1 | ||
|
|
aec735e09e | ||
|
|
9ce6d5f26e | ||
|
|
f4b4fb0562 | ||
|
|
aa22fad67d | ||
|
|
548bb4ce70 | ||
|
|
b6871b3618 | ||
|
|
fe5e816551 | ||
|
|
20d2a281b1 | ||
|
|
e2ae0c660a | ||
|
|
9e8ae16597 | ||
|
|
e5284a79c9 | ||
|
|
79dad5dfb0 | ||
|
|
a511c16fb1 | ||
|
|
98a1214a4d | ||
|
|
be459c45cf | ||
|
|
328ef2938c | ||
|
|
21f3f49078 | ||
|
|
882ad3b8cf | ||
|
|
d8b7d8bc2e | ||
|
|
c1692535a5 | ||
|
|
af0e326747 | ||
|
|
6cdaa9738a | ||
|
|
1e5d0c4517 | ||
|
|
127f5ca287 | ||
|
|
f51b775fd9 | ||
|
|
0015b92591 | ||
|
|
37e1f1811f | ||
|
|
deb6448739 | ||
|
|
bfb3224684 | ||
|
|
aed1f33935 | ||
|
|
33192efa33 | ||
|
|
d48435b948 | ||
|
|
daa4f79ea0 | ||
|
|
c70a566514 | ||
|
|
b99d3a7ff1 | ||
|
|
30cbb080b0 | ||
|
|
d8eec59d5d | ||
|
|
be89e2986b | ||
|
|
916af84651 | ||
|
|
567b5ecd4f | ||
|
|
b21d8d3e88 | ||
|
|
4e5ab529de | ||
|
|
3b1ffda3b2 | ||
|
|
cdf58044a8 | ||
|
|
727c3fde67 | ||
|
|
de880fb9f0 | ||
|
|
e9fdf7d538 | ||
|
|
57f221868d | ||
|
|
ae7d1a54cb | ||
|
|
71b075b365 | ||
|
|
c054cf99fe | ||
|
|
98a742f024 | ||
|
|
fb40bc548e | ||
|
|
d06c1954a5 | ||
|
|
545d487fea | ||
|
|
62f0812aae | ||
|
|
e0dda3ea0c | ||
|
|
7628f219e2 | ||
|
|
1d7a54c866 | ||
|
|
6c55493acb | ||
|
|
42bcac251b | ||
|
|
bb791138cd | ||
|
|
1fc509ea13 | ||
|
|
90a1b930a3 | ||
|
|
9011d58355 | ||
|
|
f2c0f203f6 | ||
|
|
3f5746dd7d | ||
|
|
adce95ead4 | ||
|
|
84d7ca0122 | ||
|
|
053af573fc | ||
|
|
06f34bec45 | ||
|
|
c1641fdb38 | ||
|
|
9115af350e | ||
|
|
77cf3612d9 | ||
|
|
07c7343f94 | ||
|
|
530f751f02 | ||
|
|
9a005cabe9 | ||
|
|
f7eb502d9d | ||
|
|
a407cfb514 | ||
|
|
ff43d07b6d | ||
|
|
340b5f22b7 | ||
|
|
b4a90131bb | ||
|
|
90149ddb4e | ||
|
|
1f09f0cf68 | ||
|
|
8035e7aecb | ||
|
|
cea32deba2 | ||
|
|
b02358e3a0 | ||
|
|
79320f27c9 | ||
|
|
52ca2f7339 | ||
|
|
78e54248e3 | ||
|
|
fc82604947 | ||
|
|
40bb0feaf8 | ||
|
|
0afb6a9481 | ||
|
|
57f72a473f | ||
|
|
876fbb9980 | ||
|
|
bee09f7c29 | ||
|
|
c31aef4131 | ||
|
|
53a36e7974 | ||
|
|
60e74c4916 | ||
|
|
1d24f912ae | ||
|
|
f9591c512c | ||
|
|
f74396e97b | ||
|
|
1127eeebb8 | ||
|
|
e9590e8b04 | ||
|
|
fd0bc89771 | ||
|
|
32a38b46fe | ||
|
|
e5f9d8cfdf | ||
|
|
ecd6b30626 | ||
|
|
31da701fe7 | ||
|
|
9d875b3935 | ||
|
|
8cab4ffb42 | ||
|
|
61aeb5bf86 | ||
|
|
0821008d6e | ||
|
|
a4a24b77b9 | ||
|
|
897edab3cf | ||
|
|
a25d70466f | ||
|
|
4270dafd6a | ||
|
|
fc3baef406 | ||
|
|
be20407238 | ||
|
|
26c4dc8fe7 | ||
|
|
4dd124d003 | ||
|
|
ee40f1386a | ||
|
|
4f116d3ca2 | ||
|
|
9ef1ce7ce1 | ||
|
|
641f40ff45 | ||
|
|
6f0d17a991 | ||
|
|
2d1155d46b | ||
|
|
a1cf6e06af | ||
|
|
2e4a861e9c | ||
|
|
70e4ad71a6 | ||
|
|
dc27b49f63 | ||
|
|
b8707c7619 | ||
|
|
b251abb79f | ||
|
|
14be6c1a6c | ||
|
|
7addfe2a71 | ||
|
|
2474700473 | ||
|
|
0150f81a24 | ||
|
|
8a801d0bb5 | ||
|
|
496d2c88f0 | ||
|
|
9d8b287c13 | ||
|
|
94e0cad2d0 | ||
|
|
8be123bf3a | ||
|
|
570da1b47c | ||
|
|
02dd286d55 | ||
|
|
58199760de | ||
|
|
17b59213d3 | ||
|
|
06e2785914 | ||
|
|
0aea390e5e | ||
|
|
c33a900c66 | ||
|
|
f36e9a7d54 | ||
|
|
7259e3a0c0 | ||
|
|
b0581ad452 | ||
|
|
813953f1f5 | ||
|
|
288b21d407 | ||
|
|
01453f73dc | ||
|
|
410f1ade01 | ||
|
|
621a9dd2a1 | ||
|
|
18b9b8bf67 | ||
|
|
3f1ea0a418 | ||
|
|
211f7b82dc | ||
|
|
6675976feb | ||
|
|
034d3ee453 | ||
|
|
faa866f4e1 | ||
|
|
9c3e36930c | ||
|
|
d4daecd921 | ||
|
|
9f10e9e7af | ||
|
|
fa9def349c | ||
|
|
4073214131 | ||
|
|
03fac2a656 | ||
|
|
a204584ddd | ||
|
|
25de01c7be | ||
|
|
176235689f | ||
|
|
f27ee8b295 | ||
|
|
32616fe6aa | ||
|
|
9a5cb9e9b0 | ||
|
|
d11869c70b | ||
|
|
abb8c9dbb5 | ||
|
|
b8442213f8 | ||
|
|
0d19abb293 | ||
|
|
6ea3e79087 | ||
|
|
ba72b146a2 | ||
|
|
0f360c86b2 | ||
|
|
ecf7a6f905 | ||
|
|
345dffaa9b | ||
|
|
7b912196e9 | ||
|
|
6e4742206f | ||
|
|
a28ecc9d02 | ||
|
|
53397f844e | ||
|
|
818398ccda | ||
|
|
a6c7068ca6 | ||
|
|
4785bb4d40 | ||
|
|
1a9f9496fd | ||
|
|
78f35daa58 | ||
|
|
b2e70c2bb3 | ||
|
|
3d8ceeb5b6 | ||
|
|
0b8540d70b | ||
|
|
e9ccfe6796 | ||
|
|
e20f2732b3 | ||
|
|
4da4ea1bff | ||
|
|
93ba39f9b0 | ||
|
|
0642a3704d | ||
|
|
57e1bafa8b | ||
|
|
3d5eb524aa | ||
|
|
c15afed0aa | ||
|
|
b133ce80c9 | ||
|
|
ae8332dc3d | ||
|
|
026a35dd90 | ||
|
|
5fdc1cdce3 | ||
|
|
02bb8b8fb8 | ||
|
|
27f289f4a0 | ||
|
|
6af1747477 | ||
|
|
401b82c226 | ||
|
|
9d128e18b6 | ||
|
|
a6a78bb556 | ||
|
|
bc59c3f563 | ||
|
|
8b7ac08192 | ||
|
|
4fe78c2b88 | ||
|
|
2e8dd00aa6 | ||
|
|
127eed5c49 | ||
|
|
7a84fc2b12 | ||
|
|
96e0925054 | ||
|
|
730ee7f89a | ||
|
|
e62d1ca458 | ||
|
|
6bca5643ee | ||
|
|
db20b23ff3 | ||
|
|
66f34668a9 | ||
|
|
ceadc26741 | ||
|
|
3a74dc9b7b | ||
|
|
4a47d752cb | ||
|
|
1bca6648bd | ||
|
|
af00bc4635 | ||
|
|
def210b4b9 | ||
|
|
89bdab0a26 | ||
|
|
448922d907 | ||
|
|
3ef8c28191 | ||
|
|
46aee46ea3 | ||
|
|
e57875d2a5 | ||
|
|
28726cf4c7 | ||
|
|
b0e4ad639e | ||
|
|
1810918e43 | ||
|
|
a736539851 | ||
|
|
591233e255 | ||
|
|
c2a2a31fb9 | ||
|
|
d4a4bfa2c7 | ||
|
|
3a127450e3 | ||
|
|
3a78519655 | ||
|
|
c6de85d4a0 | ||
|
|
f25c5cd222 | ||
|
|
0b5c6bed37 | ||
|
|
2d485263d1 | ||
|
|
3d78ec900e | ||
|
|
fc134dad8e | ||
|
|
59a1f765d0 | ||
|
|
0dd2023224 | ||
|
|
d4880b417b | ||
|
|
a7ced052dd | ||
|
|
9ac618ebec | ||
|
|
de6339586f | ||
|
|
97c9e2eec3 | ||
|
|
167913aa85 | ||
|
|
18c9785325 | ||
|
|
f4e0888ce2 | ||
|
|
d3266ee50e | ||
|
|
410bcdec4b |
@@ -5,7 +5,6 @@ from typing import Any
|
||||
|
||||
from openalex_client import get_all_author_works
|
||||
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent
|
||||
INPUT_FILE = BASE_DIR / "career_stage_sample.csv"
|
||||
OUTPUT_FILE = BASE_DIR / "career_stage_results.csv"
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
from typing import Callable, Literal
|
||||
from typing import Literal
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
import pandas as pd
|
||||
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent
|
||||
INPUT_FILE = BASE_DIR / "career_stage_results.csv"
|
||||
PLOTS_DIR = BASE_DIR / "plots"
|
||||
|
||||
@@ -4,7 +4,6 @@ from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import urlencode
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
|
||||
OPENALEX_WORKS_URL = "https://api.openalex.org/works"
|
||||
REQUEST_TIMEOUT_SECONDS = 30
|
||||
PER_PAGE = 200
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import os
|
||||
import requests
|
||||
from requests.adapters import HTTPAdapter
|
||||
from urllib.parse import quote
|
||||
|
||||
import requests
|
||||
from dotenv import load_dotenv
|
||||
from requests.adapters import HTTPAdapter
|
||||
|
||||
load_dotenv()
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import os
|
||||
import requests
|
||||
from openai import OpenAI, APIConnectionError
|
||||
|
||||
from dotenv import load_dotenv
|
||||
from openai import APIConnectionError, OpenAI
|
||||
|
||||
load_dotenv()
|
||||
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import elastic.client as es_client
|
||||
import llm.client as llm_client
|
||||
import json
|
||||
import argparse
|
||||
import time
|
||||
import json
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
|
||||
import elastic.client as es_client
|
||||
import llm.client as llm_client
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@ from pathlib import Path
|
||||
|
||||
from llama_parse import LlamaParse
|
||||
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent
|
||||
|
||||
AD_PATH = BASE_DIR / "AD.pdf"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import pymupdf4llm
|
||||
|
||||
AD_PATH = "188274\AD.pdf"
|
||||
CD_PATH = "188274\СD.pdf"
|
||||
AD_PATH = r"188274\AD.pdf"
|
||||
CD_PATH = r"188274\СD.pdf"
|
||||
|
||||
ad_md = pymupdf4llm.to_markdown(AD_PATH)
|
||||
cd_md = pymupdf4llm.to_markdown(CD_PATH)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from pathlib import Path
|
||||
import getpass
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pymupdf
|
||||
import requests
|
||||
@@ -206,7 +206,7 @@ def make_debug_data(
|
||||
) -> dict:
|
||||
choice = {}
|
||||
|
||||
if "choices" in data and data["choices"]:
|
||||
if data.get("choices"):
|
||||
choice = data["choices"][0]
|
||||
|
||||
message = choice.get("message", {})
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from pathlib import Path
|
||||
import getpass
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import requests
|
||||
|
||||
@@ -181,7 +181,7 @@ def make_debug_data(
|
||||
):
|
||||
choice = {}
|
||||
|
||||
if "choices" in data and data["choices"]:
|
||||
if data.get("choices"):
|
||||
choice = data["choices"][0]
|
||||
|
||||
message = choice.get("message", {})
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from pathlib import Path
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
SCRIPT_DIR = Path(__file__).resolve().parent
|
||||
ROOT_DIR = SCRIPT_DIR
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from pathlib import Path
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import pymupdf
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from pathlib import Path
|
||||
|
||||
import pymupdf # PyMuPDF
|
||||
|
||||
try:
|
||||
@@ -7,7 +8,7 @@ except ImportError:
|
||||
MarkItDown = None
|
||||
|
||||
|
||||
AD_PATH = Path("154115\AD.pdf")
|
||||
AD_PATH = Path(r"154115\AD.pdf")
|
||||
OUT_DIR = Path("ad_extraction_outputs3")
|
||||
OUT_DIR.mkdir(exist_ok=True)
|
||||
|
||||
|
||||
@@ -3,9 +3,9 @@ from __future__ import annotations
|
||||
import argparse
|
||||
import json
|
||||
from collections import Counter
|
||||
from statistics import mean, median
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from statistics import mean, median
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
|
||||
@@ -17,7 +17,7 @@ SERVICE_SOURCE_ROOT = ROOT.parents[1] / "service" / "src" / "main"
|
||||
if str(SERVICE_SOURCE_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(SERVICE_SOURCE_ROOT))
|
||||
|
||||
from inse.authors.institution_membership_query import ( # noqa: E402
|
||||
from inse.authors.institution_membership_query import (
|
||||
build_institution_membership_query,
|
||||
current_affiliation_year_cutoff,
|
||||
)
|
||||
@@ -852,9 +852,7 @@ def validate(result: dict[str, Any]) -> list[str]:
|
||||
if score is None:
|
||||
errors.append("basic_research_score_missing")
|
||||
elif score_is_usable:
|
||||
if quadrant == "pure_basic" and not 0 <= score <= 30:
|
||||
errors.append("basic_research_quadrant_score_mismatch")
|
||||
elif quadrant == "use_inspired_basic" and not 25 <= score <= 45:
|
||||
if quadrant == "pure_basic" and not 0 <= score <= 30 or quadrant == "use_inspired_basic" and 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")
|
||||
|
||||
@@ -26,12 +26,12 @@ import json
|
||||
import os
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from collections.abc import Iterable
|
||||
from pathlib import Path
|
||||
from typing import Any, Iterable
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
|
||||
|
||||
DEFAULT_AUTHOR_ID = "A5034365278"
|
||||
DEFAULT_WORK_YEAR_GTE = 1950
|
||||
SOURCE_INDEX = "openalex-works*"
|
||||
|
||||
@@ -373,8 +373,8 @@ def interval_distance(value: float, minimum: float, maximum: float) -> float:
|
||||
|
||||
|
||||
def safe_rate(
|
||||
numerator: int | float,
|
||||
denominator: int | float,
|
||||
numerator: float,
|
||||
denominator: float,
|
||||
) -> float | None:
|
||||
if not denominator:
|
||||
return None
|
||||
|
||||
+1
-2
@@ -13,7 +13,6 @@ from typing import Any
|
||||
|
||||
from openai import OpenAI
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
PROMPT_FILE = ROOT.parent / "prompt_frascati_hard_ranges_v2.txt"
|
||||
CONSENSUS_FILE = ROOT / "consensus_reference.json"
|
||||
@@ -282,7 +281,7 @@ def interval_distance(value: float, minimum: float, maximum: float) -> float:
|
||||
return 0.0
|
||||
|
||||
|
||||
def safe_rate(numerator: int | float, denominator: int | float) -> float | None:
|
||||
def safe_rate(numerator: float, denominator: float) -> float | None:
|
||||
if not denominator:
|
||||
return None
|
||||
return numerator / denominator
|
||||
|
||||
+2
-2
@@ -3,13 +3,13 @@ from __future__ import annotations
|
||||
import argparse
|
||||
import json
|
||||
from collections import Counter
|
||||
from collections.abc import Callable, Iterable
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Iterable
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
|
||||
ES_BASE_URL = "https://project.nes.uni-due.de/elastic"
|
||||
|
||||
@@ -8,7 +8,6 @@ from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
|
||||
from ollama import Client
|
||||
|
||||
|
||||
ENDPOINT = os.environ.get("OLLAMA_HOST", "https://project.nes.uni-due.de/llm2/")
|
||||
MODEL = os.environ.get("OLLAMA_MODEL", "gemma4:e4b-it-bf16")
|
||||
DATA_FOLDER = "data"
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import os
|
||||
import json
|
||||
import os
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from time import time
|
||||
|
||||
from openai import OpenAI, APIConnectionError
|
||||
from openai import APIConnectionError, OpenAI
|
||||
|
||||
DATA_FOLDER = "data2"
|
||||
BATCH_SIZE = 6
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import requests, json
|
||||
import json
|
||||
|
||||
import helpers
|
||||
import requests
|
||||
|
||||
AUTHOR_OPEN_ALEXID = helpers.get_all_author_ids_from_specific_university("University of Duisburg-Essen")
|
||||
#AUTHOR_OPEN_ALEXID = ["A5047117780"]
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import requests, json
|
||||
import json
|
||||
|
||||
import helpers
|
||||
import requests
|
||||
|
||||
AUTHOR_OPEN_ALEXID = helpers.get_all_author_ids_from_specific_university("University of Duisburg-Essen")
|
||||
#AUTHOR_OPEN_ALEXID = ["A5093075883", "A5047117780", "A5007170803"]
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import os
|
||||
|
||||
import requests
|
||||
|
||||
ELASTICSEARCH_URL = os.environ.get("ELASTICSEARCH_URL", "https://project.nes.uni-due.de/elastic")
|
||||
|
||||
@@ -2,8 +2,8 @@ import os
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from time import time
|
||||
|
||||
from openai import OpenAI, APIConnectionError
|
||||
import helpers
|
||||
from openai import APIConnectionError, OpenAI
|
||||
|
||||
DATA_FOLDER = "data2"
|
||||
BATCH_SIZE = 6
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
from typing import Any, Iterator
|
||||
from elasticsearch import Elasticsearch
|
||||
from collections import defaultdict
|
||||
import json
|
||||
from collections import defaultdict
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
from elasticsearch import NotFoundError
|
||||
from typing import Any
|
||||
|
||||
from elasticsearch import Elasticsearch, NotFoundError
|
||||
|
||||
# elasticseach library required. Here used elasticsearch==8.0.0
|
||||
# estimated execution time: 3-5 Minutes
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import os
|
||||
import json
|
||||
import os
|
||||
from time import time
|
||||
|
||||
from llm_classify_news import call, parse_label, parse_persons
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Baut aus den JSON-Dateien in data2/ eine eigenstaendige viewer.html.
|
||||
|
||||
@@ -8,8 +7,8 @@ mit Vor/Zurueck durch die News blaettern. Oben stehen _id, llm_label und
|
||||
llm_persons, darunter der full_content als reiner Text (kein Parsing).
|
||||
"""
|
||||
|
||||
import os
|
||||
import json
|
||||
import os
|
||||
|
||||
DATA_FOLDER = "validation_data"
|
||||
OUTPUT_FILE = "viewer.html"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import os
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
|
||||
import requests
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import os
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
|
||||
import requests
|
||||
from openai import OpenAI, APIConnectionError
|
||||
|
||||
from openai import APIConnectionError, OpenAI
|
||||
|
||||
INSE_URL = "https://inse.nes.uni-due.de/elastic"
|
||||
INDEX_URL = f"{INSE_URL}/aktuell"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import os
|
||||
import json
|
||||
import os
|
||||
|
||||
DATA_FOLDER = "data2"
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import json
|
||||
|
||||
from tabulate import tabulate
|
||||
|
||||
result_files = [
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
from urllib.parse import quote
|
||||
|
||||
import requests
|
||||
from requests.adapters import HTTPAdapter
|
||||
from urllib.parse import quote
|
||||
|
||||
INSE_URL = "https://inse.nes.uni-due.de/elastic"
|
||||
INSE_API_KEY = "bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw=="
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import requests
|
||||
from openai import OpenAI, APIConnectionError
|
||||
from openai import APIConnectionError, OpenAI
|
||||
|
||||
LLM_BASE_URL = "https://project.nes.uni-due.de/llm2/v1/"
|
||||
LLM_API_KEY = "c2d5e7ccf7a4760dd3d19bed2caed9d85ff7437400e0ea82a6d6f912ebc2f212"
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import argparse
|
||||
import json
|
||||
import threading
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
|
||||
import elastic.client as es_client
|
||||
import llm.client as llm_client
|
||||
import json
|
||||
import argparse
|
||||
import time
|
||||
import threading
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
|
||||
|
||||
def print_pretty_json(data):
|
||||
print(json.dumps(data, indent=2))
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
#!/usr/bin/env python3
|
||||
import os
|
||||
import sys
|
||||
import json
|
||||
import time
|
||||
import asyncio
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
import numpy as np
|
||||
|
||||
@@ -14,6 +14,7 @@ project_root = current_dir.parent.parent.resolve()
|
||||
env_path = project_root / "service" / "src" / "main" / "inse" / ".env"
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv(dotenv_path=env_path)
|
||||
|
||||
sys.path.append(str(project_root / "service" / "src" / "main"))
|
||||
@@ -311,7 +312,7 @@ async def evaluate():
|
||||
try:
|
||||
resp = client.post(f"{ELASTIC_URL}topicvectors/_search", json=payload, headers=headers)
|
||||
resp.raise_for_status()
|
||||
except Exception as exc:
|
||||
except Exception:
|
||||
# Log error but don't crash
|
||||
pass
|
||||
t1 = time.perf_counter()
|
||||
|
||||
@@ -4,15 +4,14 @@ Professional evaluation pipeline to benchmark different Sentence Transformer mod
|
||||
on the OpenAlex topics dataset. Measures Information Retrieval (IR) metrics,
|
||||
Taxonomy Clustering metrics, and operational performance metrics.
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import json
|
||||
import time
|
||||
import argparse
|
||||
import json
|
||||
import random
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
import numpy as np
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Add service/src/main to python path to load settings
|
||||
@@ -30,8 +29,8 @@ API_KEY = settings.elasticsearch_api_key
|
||||
# Import evaluation libraries
|
||||
from sentence_transformers import SentenceTransformer
|
||||
from sentence_transformers.evaluation import InformationRetrievalEvaluator
|
||||
from sklearn.cluster import KMeans
|
||||
from sklearn import metrics
|
||||
from sklearn.cluster import KMeans
|
||||
|
||||
DEFAULT_MODELS = [
|
||||
"paraphrase-multilingual-mpnet-base-v2",
|
||||
@@ -161,9 +160,9 @@ def evaluate_model(model_name, data, output_dir):
|
||||
model_safe_name = model_name.replace("/", "_").replace("-", "_")
|
||||
report_file = output_dir / f"model_report_{model_safe_name}.json"
|
||||
|
||||
print(f"\n==================================================")
|
||||
print("\n==================================================")
|
||||
print(f"Evaluating Model: '{model_name}'")
|
||||
print(f"==================================================")
|
||||
print("==================================================")
|
||||
|
||||
start_load = time.time()
|
||||
try:
|
||||
|
||||
+10
-1
@@ -6,5 +6,14 @@ RUN mkdir /test && \
|
||||
pip install --root-user-action=ignore --no-cache-dir torch --index-url https://download.pytorch.org/whl/cpu && \
|
||||
pip install --root-user-action=ignore --no-cache-dir "sentence-transformers~=5.5.1"
|
||||
|
||||
ARG MODEL_NAME=intfloat/multilingual-e5-base
|
||||
ENV MODEL_NAME=${MODEL_NAME}
|
||||
ENV SENTENCE_TRANSFORMERS_HOME=/models
|
||||
RUN python -c "from sentence_transformers import SentenceTransformer; SentenceTransformer('intfloat/multilingual-e5-base')"
|
||||
ENV HF_HOME=/models
|
||||
|
||||
RUN python -c "import os, sentence_transformers; sentence_transformers.SentenceTransformer(os.environ['MODEL_NAME'])"
|
||||
|
||||
ENV HF_HUB_OFFLINE=1
|
||||
ENV TRANSFORMERS_OFFLINE=1
|
||||
ENV HF_DATASETS_OFFLINE=1
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import logging
|
||||
import sys
|
||||
import time
|
||||
import logging
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
"""
|
||||
map_news_topics.py — Map news keywords to OpenAlex topics.
|
||||
|
||||
@@ -37,7 +37,7 @@ import json
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
|
||||
from dotenv import load_dotenv
|
||||
@@ -121,7 +121,7 @@ async def fetch_source_entries(cluster: str, max_docs: int | None) -> dict[str,
|
||||
|
||||
|
||||
async def run(args: argparse.Namespace) -> None:
|
||||
built_at = datetime.now(timezone.utc).isoformat()
|
||||
built_at = datetime.now(UTC).isoformat()
|
||||
model_name = os.getenv("SENTENCE_TRANSFORMERS_MODEL_NAME")
|
||||
|
||||
await base.check_backend(args.api_base_url)
|
||||
|
||||
@@ -3,10 +3,8 @@
|
||||
# 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
|
||||
from scrapy import signals
|
||||
|
||||
|
||||
class AktuellSpiderMiddleware:
|
||||
|
||||
@@ -5,7 +5,6 @@
|
||||
|
||||
|
||||
# useful for handling different item types with a single interface
|
||||
from itemadapter import ItemAdapter
|
||||
|
||||
|
||||
class AktuellPipeline:
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import scrapy
|
||||
|
||||
|
||||
class LinksCrawler(scrapy.Spider):
|
||||
name = "aktuell-links"
|
||||
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import scrapy
|
||||
import json
|
||||
from scrapy.linkextractors import LinkExtractor
|
||||
import os
|
||||
|
||||
import scrapy
|
||||
from scrapy.linkextractors import LinkExtractor
|
||||
|
||||
|
||||
class MetaDataCrawler(scrapy.Spider):
|
||||
name = "aktuell-metadata"
|
||||
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
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
|
||||
import time
|
||||
from random import randint
|
||||
|
||||
from elasticsearch import Elasticsearch
|
||||
from selenium import webdriver
|
||||
from selenium.common.exceptions import NoSuchElementException
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.firefox.options import Options
|
||||
|
||||
es = Elasticsearch()
|
||||
|
||||
@@ -32,7 +33,7 @@ def getLinks(link, driver):
|
||||
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:
|
||||
except NoSuchElementException:
|
||||
break
|
||||
|
||||
# get date
|
||||
@@ -45,7 +46,7 @@ def getLinks(link, driver):
|
||||
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:
|
||||
except NoSuchElementException:
|
||||
continue
|
||||
|
||||
links.append(link)
|
||||
@@ -67,17 +68,17 @@ def getData(driver, link, date, date_year, date_num):
|
||||
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:
|
||||
except NoSuchElementException:
|
||||
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:
|
||||
except NoSuchElementException:
|
||||
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:
|
||||
except NoSuchElementException:
|
||||
pass
|
||||
author = ""
|
||||
if redaktion != "":
|
||||
@@ -86,7 +87,7 @@ def getData(driver, link, date, date_year, date_num):
|
||||
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:
|
||||
except NoSuchElementException:
|
||||
pass
|
||||
|
||||
full_content = main_content
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import subprocess
|
||||
import sys
|
||||
import os
|
||||
import shutil
|
||||
import time
|
||||
import argparse
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import sys
|
||||
import os
|
||||
import json
|
||||
import time
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from urllib.parse import quote
|
||||
|
||||
import requests
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
"""
|
||||
build_patents_openalex_keywords.py — Build IPC/CPC → OpenAlex topic/keyword matches.
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
"""
|
||||
evaluate_keyword_patent_search.py — Systematic evaluation for keyword → patent search.
|
||||
|
||||
@@ -23,14 +23,14 @@ import asyncio
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
current_dir = Path(__file__).resolve().parent
|
||||
sys.path.insert(0, str(current_dir.parent.parent / "src" / "main"))
|
||||
|
||||
from inse.patents.keywords.eval_metrics import ( # noqa: E402
|
||||
from inse.patents.keywords.eval_metrics import (
|
||||
analyze_family_duplicates_in_top_k,
|
||||
average_precision,
|
||||
ipc_prefix_hit_rate,
|
||||
@@ -43,13 +43,13 @@ from inse.patents.keywords.eval_metrics import ( # noqa: E402
|
||||
recall_at_k,
|
||||
unique_family_precision_at_k,
|
||||
)
|
||||
from inse.patents.keywords.logic import ( # noqa: E402
|
||||
from inse.patents.keywords.logic import (
|
||||
_DEFAULT_SCORE_WEIGHTS,
|
||||
_MAX_PATENTS,
|
||||
_compute_final_score,
|
||||
get_patents_by_keywords,
|
||||
)
|
||||
from inse.patents.keywords.model import ( # noqa: E402
|
||||
from inse.patents.keywords.model import (
|
||||
KeywordPatentMatch,
|
||||
KeywordPatentSearchDiagnostics,
|
||||
KeywordPatentSearchItem,
|
||||
@@ -721,9 +721,7 @@ def _load_prior_candidate_grades(
|
||||
if existing is None:
|
||||
bucket[patent_id] = dict(candidate)
|
||||
continue
|
||||
if existing.get("grade") is None and grade is not None:
|
||||
bucket[patent_id] = dict(candidate)
|
||||
elif existing.get("grade") is None:
|
||||
if existing.get("grade") is None and grade is not None or existing.get("grade") is None:
|
||||
bucket[patent_id] = dict(candidate)
|
||||
return by_case
|
||||
|
||||
@@ -884,7 +882,7 @@ async def cmd_bootstrap(args: argparse.Namespace) -> int:
|
||||
}
|
||||
)
|
||||
|
||||
stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
||||
stamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ")
|
||||
labeling_path = out_dir / f"labeling_{stamp}.json"
|
||||
report_path = out_dir / f"bootstrap_report_{stamp}.json"
|
||||
|
||||
@@ -979,7 +977,7 @@ async def cmd_eval(args: argparse.Namespace) -> int:
|
||||
if presentation
|
||||
else _aggregate(case_reports, ks)
|
||||
)
|
||||
stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
||||
stamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ")
|
||||
report_name = "presentation_eval_report" if presentation else "eval_report"
|
||||
report_path = Path(args.out_dir) / f"{report_name}_{stamp}.json"
|
||||
_write_json(
|
||||
@@ -1071,7 +1069,7 @@ async def cmd_ablation(args: argparse.Namespace) -> int:
|
||||
f"P@10={p10}"
|
||||
)
|
||||
|
||||
stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
||||
stamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ")
|
||||
report_path = Path(args.out_dir) / f"ablation_report_{stamp}.json"
|
||||
_write_json(
|
||||
report_path,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
"""
|
||||
index_org_patents.py — Build the org_patents Elasticsearch index for one institution.
|
||||
|
||||
|
||||
@@ -1,23 +1,21 @@
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
import pandas as pd
|
||||
import requests
|
||||
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
|
||||
import os
|
||||
import math
|
||||
import requests
|
||||
import hashlib
|
||||
import argparse
|
||||
import logging
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
"""
|
||||
map_project_topics.py — Map project keywords to OpenAlex topics.
|
||||
|
||||
@@ -52,9 +52,10 @@ import json
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
from collections.abc import AsyncIterator
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, AsyncIterator
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from dotenv import load_dotenv
|
||||
@@ -396,7 +397,7 @@ async def bulk_index(index: str, cluster: str, documents: list[tuple[str, dict]]
|
||||
|
||||
|
||||
async def run(args: argparse.Namespace) -> None:
|
||||
built_at = datetime.now(timezone.utc).isoformat()
|
||||
built_at = datetime.now(UTC).isoformat()
|
||||
model_name = os.getenv("SENTENCE_TRANSFORMERS_MODEL_NAME")
|
||||
|
||||
await check_backend(args.api_base_url)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
"""
|
||||
test_keywords_matching.py
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
"""
|
||||
Download the sentence-transformers model to the default cache directory
|
||||
so it is available for local runs or testing.
|
||||
@@ -6,9 +6,28 @@ so it is available for local runs or testing.
|
||||
Usage (run once from project root):
|
||||
python service/sentence_transformer/download_model.py
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# Ensure service/src/main is in sys.path
|
||||
current_dir = Path(__file__).parent.resolve()
|
||||
src_main_dir = current_dir.parent / "src" / "main"
|
||||
if str(src_main_dir) not in sys.path:
|
||||
sys.path.insert(0, str(src_main_dir))
|
||||
|
||||
from inse.config import settings
|
||||
from sentence_transformers import SentenceTransformer
|
||||
|
||||
MODEL_NAME = "intfloat/multilingual-e5-base"
|
||||
print(f"Downloading '{MODEL_NAME}' to default cache directory...")
|
||||
MODEL_NAME = settings.sentence_transformers_model_name
|
||||
print(f"Downloading '{MODEL_NAME}' to cache directory...")
|
||||
model = SentenceTransformer(MODEL_NAME)
|
||||
print("Done.")
|
||||
|
||||
print(f"Verifying offline model loading for '{MODEL_NAME}'...")
|
||||
os.environ["HF_HUB_OFFLINE"] = "1"
|
||||
os.environ["TRANSFORMERS_OFFLINE"] = "1"
|
||||
os.environ["HF_DATASETS_OFFLINE"] = "1"
|
||||
|
||||
offline_model = SentenceTransformer(MODEL_NAME, local_files_only=True)
|
||||
print("Done. Model downloaded and verified for 100% offline usage.")
|
||||
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
"""
|
||||
Script to fetch all topics from 'openalex-topics',
|
||||
vectorize display names, full descriptions, and individual keywords using the sentence-transformers model,
|
||||
and push them to the 'topicvectors' index with multi-vector mapping.
|
||||
"""
|
||||
import sys
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
from dotenv import load_dotenv
|
||||
|
||||
@@ -26,7 +27,6 @@ API_KEY = settings.elasticsearch_api_key
|
||||
MODEL_NAME = settings.sentence_transformers_model_name
|
||||
|
||||
# Import sentence-transformers
|
||||
from sentence_transformers import SentenceTransformer
|
||||
|
||||
headers = {
|
||||
"Authorization": f"ApiKey {API_KEY}",
|
||||
@@ -169,8 +169,9 @@ def main():
|
||||
print("No topics found. Exiting.")
|
||||
return
|
||||
|
||||
from inse.util import get_model
|
||||
print(f"Initializing SentenceTransformer model '{MODEL_NAME}'...")
|
||||
model = SentenceTransformer(MODEL_NAME)
|
||||
model = get_model()
|
||||
|
||||
# 1. Gather all texts to embed
|
||||
keywords_by_topic = []
|
||||
|
||||
@@ -12,6 +12,11 @@ ELASTICSEARCH_API_KEY=am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ
|
||||
ELASTICSEARCH_INSE_URL=https://inse.nes.uni-due.de/elastic
|
||||
ELASTICSEARCH_INSE_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
|
||||
|
||||
# Debugging: Log every outgoing Elasticsearch query (index + payload)
|
||||
PRINT_ES_QUERIES=false
|
||||
# Debugging: Log the duration of every Elasticsearch request
|
||||
PRINT_ES_TIMINGS=true
|
||||
|
||||
# Sentence Transformers Configuration
|
||||
SENTENCE_TRANSFORMERS_MODEL_NAME=intfloat/multilingual-e5-base
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import uuid
|
||||
from typing import List, Optional
|
||||
|
||||
from pydantic import BaseModel, Field, model_validator
|
||||
|
||||
@@ -9,14 +8,14 @@ from inse.auth.model import UserRole, normalize_roles
|
||||
class OrganizationProfile(BaseModel):
|
||||
id: uuid.UUID
|
||||
name: str
|
||||
openalex_institution_id: Optional[str] = None
|
||||
openalex_institution_id: str | None = None
|
||||
|
||||
|
||||
class AccountProfile(BaseModel):
|
||||
id: uuid.UUID
|
||||
email: str
|
||||
name: str
|
||||
roles: List[UserRole]
|
||||
roles: list[UserRole]
|
||||
organization_id: uuid.UUID
|
||||
organization_name: str
|
||||
deleted: bool
|
||||
@@ -27,7 +26,7 @@ class AccountProfile(BaseModel):
|
||||
|
||||
|
||||
class AccountPage(BaseModel):
|
||||
items: List[AccountProfile]
|
||||
items: list[AccountProfile]
|
||||
total: int
|
||||
page: int
|
||||
page_size: int
|
||||
@@ -43,10 +42,10 @@ class CreateAccountRequest(BaseModel):
|
||||
|
||||
email: str = Field(min_length=3)
|
||||
name: str = Field(min_length=1)
|
||||
roles: List[UserRole] = Field(default_factory=lambda: [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
|
||||
openalex_person_id: str | None = None
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _normalize_roles(self):
|
||||
@@ -62,14 +61,14 @@ class UpdateAccountRequest(BaseModel):
|
||||
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)
|
||||
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
|
||||
email: str | None = Field(default=None, min_length=3)
|
||||
name: str | None = Field(default=None, min_length=1)
|
||||
roles: list[UserRole] | None = None
|
||||
organization_id: uuid.UUID | None = None
|
||||
password: str | None = Field(default=None, min_length=8)
|
||||
openalex_person_id: str | None = None
|
||||
deleted: bool | None = None
|
||||
activated: bool | None = None
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _normalize_roles(self):
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import uuid
|
||||
from typing import Annotated, Optional
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Query, Response, status
|
||||
|
||||
@@ -40,8 +40,8 @@ async def list_accounts(
|
||||
page: Annotated[int, Query(ge=0)] = 0,
|
||||
page_size: Annotated[int, Query(ge=1, le=100)] = 10,
|
||||
offset: Annotated[int, Query(ge=0)] = 0,
|
||||
search: Annotated[Optional[str], Query()] = None,
|
||||
organization_id: Annotated[Optional[uuid.UUID], Query()] = None,
|
||||
search: Annotated[str | None, Query()] = None,
|
||||
organization_id: Annotated[uuid.UUID | None, Query()] = None,
|
||||
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> AccountPage:
|
||||
return service.list_accounts(
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import HTTPException, status
|
||||
from sqlmodel import Session, func, or_, select
|
||||
@@ -84,7 +83,7 @@ def _ensure_account_in_editor_scope(account: Account, token: AccessTokenMetadata
|
||||
def _ensure_email_available(
|
||||
session: Session,
|
||||
email: str,
|
||||
excluded_account_id: Optional[uuid.UUID] = None,
|
||||
excluded_account_id: uuid.UUID | None = None,
|
||||
) -> None:
|
||||
normalized_email = email.lower().strip()
|
||||
if "@" not in normalized_email or "." not in normalized_email.rsplit("@", 1)[-1]:
|
||||
@@ -115,9 +114,9 @@ def list_accounts(
|
||||
access_token: AccessTokenMetadata,
|
||||
page: int,
|
||||
page_size: int,
|
||||
offset: Optional[int] = None,
|
||||
search: Optional[str] = None,
|
||||
organization_id: Optional[uuid.UUID] = None,
|
||||
offset: int | None = None,
|
||||
search: str | None = None,
|
||||
organization_id: uuid.UUID | None = None,
|
||||
) -> AccountPage:
|
||||
if access_token.effective_role not in {
|
||||
UserRole.SUPER_ADMIN,
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from enum import StrEnum
|
||||
from typing import List
|
||||
|
||||
from pydantic import BaseModel, model_validator
|
||||
from sqlalchemy import JSON, Column, UniqueConstraint
|
||||
@@ -24,8 +23,8 @@ ROLE_PRIORITY = {
|
||||
|
||||
|
||||
def normalize_roles(
|
||||
roles: List[UserRole] | List[str] | UserRole | str | None,
|
||||
) -> List[UserRole]:
|
||||
roles: list[UserRole] | list[str] | UserRole | str | None,
|
||||
) -> list[UserRole]:
|
||||
if roles is None:
|
||||
return [UserRole.USER]
|
||||
if isinstance(roles, (str, UserRole)):
|
||||
@@ -43,7 +42,7 @@ def normalize_roles(
|
||||
|
||||
|
||||
def effective_role_for_roles(
|
||||
roles: List[UserRole] | List[str] | UserRole | str | None,
|
||||
roles: list[UserRole] | list[str] | UserRole | str | None,
|
||||
) -> UserRole:
|
||||
return normalize_roles(roles)[0]
|
||||
|
||||
@@ -86,7 +85,26 @@ class Organization(Durable, table=True):
|
||||
description="The OpenAlex ID of the institution associated with the organization.",
|
||||
)
|
||||
|
||||
accounts: List["Account"] = Relationship(back_populates="organization")
|
||||
accounts: list["Account"] = Relationship(back_populates="organization")
|
||||
|
||||
|
||||
class OrganizationInstitution(SQLModel, table=True):
|
||||
__tablename__ = "organization_institution"
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
"organization_id",
|
||||
"position",
|
||||
name="uq_organization_institution_position",
|
||||
),
|
||||
)
|
||||
|
||||
organization_id: uuid.UUID = Field(
|
||||
foreign_key="organization.id",
|
||||
primary_key=True,
|
||||
index=True,
|
||||
)
|
||||
openalex_institution_id: str = Field(primary_key=True, index=True)
|
||||
position: int = Field(nullable=False)
|
||||
|
||||
|
||||
class Account(Durable, table=True):
|
||||
@@ -141,7 +159,7 @@ class Account(Durable, table=True):
|
||||
nullable=False,
|
||||
description="The unique identifier of the organization strictly associated with this account.",
|
||||
)
|
||||
roles: List[UserRole] = Field(
|
||||
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.",
|
||||
@@ -249,7 +267,7 @@ class AccessTokenMetadata(BaseTokenData):
|
||||
default=UserRole.USER,
|
||||
description="The specific role this access token grants within its organization.",
|
||||
)
|
||||
effective_roles: List[UserRole] = Field(
|
||||
effective_roles: list[UserRole] = Field(
|
||||
default_factory=lambda: [UserRole.USER],
|
||||
description="The roles this access token grants within its organization.",
|
||||
)
|
||||
@@ -300,7 +318,7 @@ class RefreshTokenMetadata(BaseTokenData):
|
||||
default=UserRole.USER,
|
||||
description="The specific role this access token grants within its organization.",
|
||||
)
|
||||
effective_roles: List[UserRole] = Field(
|
||||
effective_roles: list[UserRole] = Field(
|
||||
default_factory=lambda: [UserRole.USER],
|
||||
description="The roles this access token grants within its organization.",
|
||||
)
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
import logging
|
||||
from typing import Annotated
|
||||
import uuid
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Body, Depends, Response, status
|
||||
from fastapi import APIRouter, Body, Depends, Query, Response, status
|
||||
from sqlmodel import Session
|
||||
|
||||
from inse.tags import Tags
|
||||
|
||||
import inse.auth.service as auth_service
|
||||
from inse.database import SessionDep, get_session
|
||||
from inse.auth.model import (
|
||||
AccessResponse,
|
||||
AccessToken,
|
||||
@@ -18,6 +15,8 @@ from inse.auth.model import (
|
||||
OtkResponse,
|
||||
RefreshTokenMetadata,
|
||||
)
|
||||
from inse.database import SessionDep, get_session
|
||||
from inse.tags import Tags
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -205,3 +204,30 @@ async def change_password(
|
||||
current_password=current_password,
|
||||
new_password=new_password,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/can-fetch-gdpr-relevant-data",
|
||||
summary="Check if user can fetch GDPR-relevant data",
|
||||
description="Check if the authenticated user can fetch GDPR-relevant data for a given author and institution.",
|
||||
operation_id="canFetchGdprRelevantData",
|
||||
)
|
||||
async def can_fetch_gdpr_relevant_data(
|
||||
access_token: Annotated[
|
||||
AccessTokenMetadata,
|
||||
auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
],
|
||||
raw_oa_author_id: Annotated[
|
||||
str | None,
|
||||
Query(description="OpenAlex author ID to check access for"),
|
||||
] = None,
|
||||
raw_oa_institution_id: Annotated[
|
||||
str | None,
|
||||
Query(description="OpenAlex institution ID to check access for"),
|
||||
] = None,
|
||||
) -> bool:
|
||||
return await auth_service.can_fetch_gdpr_relevant_data(
|
||||
access_token=access_token,
|
||||
raw_oa_author_id=raw_oa_author_id,
|
||||
raw_oa_institution_id=raw_oa_institution_id,
|
||||
)
|
||||
|
||||
@@ -4,7 +4,7 @@ import json
|
||||
import logging
|
||||
import secrets
|
||||
import uuid
|
||||
from typing import Annotated, Any, Dict, Optional
|
||||
from typing import Annotated, Any
|
||||
|
||||
import jwt
|
||||
from argon2 import PasswordHasher
|
||||
@@ -22,6 +22,7 @@ from inse.auth.model import (
|
||||
IdTokenMetadata,
|
||||
LoginResponse,
|
||||
Organization,
|
||||
OrganizationInstitution,
|
||||
OtkResponse,
|
||||
RefreshTokenMetadata,
|
||||
Secret,
|
||||
@@ -31,6 +32,7 @@ from inse.auth.model import (
|
||||
effective_role_for_roles,
|
||||
normalize_roles,
|
||||
)
|
||||
from inse.authors.v2 import service as authors_service
|
||||
from inse.config import get_settings
|
||||
from inse.database import get_session
|
||||
|
||||
@@ -95,11 +97,14 @@ def create_predefined_accounts(session: Session, file_path: str):
|
||||
|
||||
try:
|
||||
with open(file_path, "r") as file:
|
||||
data: Dict[str, Any] = json.loads(file.read())
|
||||
data: dict[str, Any] = json.loads(file.read())
|
||||
for organization_data in data.get("organizations", []):
|
||||
organization_id = organization_data.get("id")
|
||||
if organization_id is not None:
|
||||
organization_id = uuid.UUID(organization_id)
|
||||
organization_id_value = organization_data.get("id")
|
||||
organization_id = (
|
||||
uuid.UUID(organization_id_value)
|
||||
if organization_id_value is not None
|
||||
else uuid.uuid4()
|
||||
)
|
||||
organization_name = organization_data["name"]
|
||||
openalex_institution_id = organization_data.get(
|
||||
"openalex_institution_id"
|
||||
@@ -112,6 +117,14 @@ def create_predefined_accounts(session: Session, file_path: str):
|
||||
openalex_institution_id=openalex_institution_id,
|
||||
)
|
||||
session.add(organization)
|
||||
if openalex_institution_id:
|
||||
session.add(
|
||||
OrganizationInstitution(
|
||||
organization_id=organization.id,
|
||||
openalex_institution_id=openalex_institution_id,
|
||||
position=0,
|
||||
)
|
||||
)
|
||||
for account_data in data.get("accounts", []):
|
||||
organization_id = uuid.UUID(account_data["organization_id"])
|
||||
roles = normalize_roles(
|
||||
@@ -215,7 +228,7 @@ def request_otk(session: Session, email: str, password: str):
|
||||
account = session.exec(
|
||||
select(Account).where(
|
||||
Account.email == email,
|
||||
Account.deleted == False, # noqa: E712
|
||||
Account.deleted == False,
|
||||
)
|
||||
).first()
|
||||
|
||||
@@ -254,7 +267,7 @@ def request_otk(session: Session, email: str, password: str):
|
||||
)
|
||||
).first()
|
||||
|
||||
expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
|
||||
expires_at = datetime.datetime.now(datetime.UTC) + datetime.timedelta(
|
||||
minutes=OTK_EXPIRATION_MINUTES
|
||||
)
|
||||
|
||||
@@ -293,19 +306,19 @@ def request_otk(session: Session, email: str, password: str):
|
||||
return OtkResponse(status="success", account_id=account.id)
|
||||
|
||||
|
||||
def request_password_reset(session: Session, email: str) -> Dict[str, Any]:
|
||||
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)
|
||||
now = datetime.datetime.now(datetime.UTC)
|
||||
|
||||
account = session.exec(
|
||||
select(Account).where(
|
||||
Account.email == email,
|
||||
Account.deleted == False, # noqa: E712
|
||||
Account.deleted == False,
|
||||
)
|
||||
).first()
|
||||
|
||||
@@ -328,9 +341,7 @@ def request_password_reset(session: Session, email: str) -> Dict[str, Any]:
|
||||
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_started_at = window_started_at.replace(tzinfo=datetime.UTC)
|
||||
|
||||
window_ends_at = window_started_at + datetime.timedelta(
|
||||
minutes=PASSWORD_RESET_RATE_LIMIT_WINDOW_MINUTES
|
||||
@@ -435,7 +446,7 @@ def reset_password(
|
||||
session: Session,
|
||||
reset_token: str,
|
||||
new_password: str,
|
||||
) -> Dict[str, str]:
|
||||
) -> dict[str, str]:
|
||||
"""Resets an account password using a one-time password reset token.
|
||||
|
||||
Args:
|
||||
@@ -449,7 +460,7 @@ def reset_password(
|
||||
Returns:
|
||||
Dict[str, str]: A status response.
|
||||
"""
|
||||
now = datetime.datetime.now(datetime.timezone.utc)
|
||||
now = datetime.datetime.now(datetime.UTC)
|
||||
reset_token_hash = _hash_reset_token(reset_token.strip())
|
||||
|
||||
secret = session.exec(
|
||||
@@ -467,7 +478,7 @@ def reset_password(
|
||||
|
||||
secret_expires = secret.expires_at
|
||||
if getattr(secret_expires, "tzinfo", None) is None:
|
||||
secret_expires = secret_expires.replace(tzinfo=datetime.timezone.utc)
|
||||
secret_expires = secret_expires.replace(tzinfo=datetime.UTC)
|
||||
|
||||
if secret_expires <= now:
|
||||
session.delete(secret)
|
||||
@@ -515,7 +526,7 @@ def login(
|
||||
Returns:
|
||||
LoginResponse: The response containing the ID token issued upon successful login.
|
||||
"""
|
||||
now = datetime.datetime.now(datetime.timezone.utc)
|
||||
now = datetime.datetime.now(datetime.UTC)
|
||||
|
||||
secret = session.exec(
|
||||
select(Secret).where(
|
||||
@@ -536,7 +547,7 @@ def login(
|
||||
|
||||
secret_expires = secret.expires_at
|
||||
if getattr(secret_expires, "tzinfo", None) is None:
|
||||
secret_expires = secret_expires.replace(tzinfo=datetime.timezone.utc)
|
||||
secret_expires = secret_expires.replace(tzinfo=datetime.UTC)
|
||||
|
||||
if secret_expires <= now:
|
||||
logger.warning("Login failed: invalid or expired code %s", email_code)
|
||||
@@ -611,7 +622,7 @@ def _get_current_user_access_token_payload(
|
||||
real_account_id=uuid.UUID(access_token_payload[REAL_ACCOUNT_ID_KEY]),
|
||||
effective_account_id=uuid.UUID(access_token_payload[EFFECTIVE_ACCOUNT_ID_KEY]),
|
||||
expires_at=datetime.datetime.fromtimestamp(
|
||||
access_token_payload["exp"], tz=datetime.timezone.utc
|
||||
access_token_payload["exp"], tz=datetime.UTC
|
||||
),
|
||||
epoch=access_token_payload[EPOCH_KEY],
|
||||
effective_role=UserRole(access_token_payload[EFFECTIVE_ROLE_KEY]),
|
||||
@@ -657,7 +668,7 @@ def _get_current_user_refresh_token_payload(
|
||||
real_account_id=uuid.UUID(refresh_token_payload[REAL_ACCOUNT_ID_KEY]),
|
||||
effective_account_id=uuid.UUID(refresh_token_payload[EFFECTIVE_ACCOUNT_ID_KEY]),
|
||||
expires_at=datetime.datetime.fromtimestamp(
|
||||
refresh_token_payload["exp"], tz=datetime.timezone.utc
|
||||
refresh_token_payload["exp"], tz=datetime.UTC
|
||||
),
|
||||
epoch=refresh_token_payload[EPOCH_KEY],
|
||||
effective_role=UserRole(refresh_token_payload[EFFECTIVE_ROLE_KEY]),
|
||||
@@ -708,7 +719,7 @@ def _get_current_user_id_token_payload(
|
||||
return IdTokenMetadata(
|
||||
real_account_id=uuid.UUID(id_token_payload[REAL_ACCOUNT_ID_KEY]),
|
||||
expires_at=datetime.datetime.fromtimestamp(
|
||||
id_token_payload["exp"], tz=datetime.timezone.utc
|
||||
id_token_payload["exp"], tz=datetime.UTC
|
||||
),
|
||||
epoch=id_token_payload[EPOCH_KEY],
|
||||
)
|
||||
@@ -784,9 +795,7 @@ def _get_account_organization(session: Session, account_id: uuid.UUID) -> uuid.U
|
||||
return account.organization_id
|
||||
|
||||
|
||||
def _get_account_institution_id(
|
||||
session: Session, account_id: uuid.UUID
|
||||
) -> Optional[str]:
|
||||
def _get_account_institution_id(session: Session, account_id: uuid.UUID) -> str | None:
|
||||
"""Retrieves the OpenAlex institution ID for the given account ID.
|
||||
|
||||
Args:
|
||||
@@ -872,7 +881,7 @@ def get_access_token(
|
||||
session: Session,
|
||||
id_token: IdTokenMetadata,
|
||||
real_account_id: uuid.UUID,
|
||||
effective_account_id: Optional[uuid.UUID] = None,
|
||||
effective_account_id: uuid.UUID | None = None,
|
||||
) -> AccessResponse:
|
||||
# IMPORTANT: The ID token has already been verified by the dependency injection system, so we can trust its payload here.
|
||||
|
||||
@@ -1054,7 +1063,7 @@ def _build_id_token(
|
||||
Returns:
|
||||
IdToken: The generated ID token object.
|
||||
"""
|
||||
expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
|
||||
expires_at = datetime.datetime.now(datetime.UTC) + datetime.timedelta(
|
||||
minutes=ID_TOKEN_EXPIRATION_MINUTES
|
||||
)
|
||||
payload = {
|
||||
@@ -1082,7 +1091,7 @@ def _set_refresh_token(
|
||||
effective_organization_id: uuid.UUID,
|
||||
epoch: int,
|
||||
effective_roles: list[UserRole] | None = None,
|
||||
effective_institution_id: Optional[str] = None,
|
||||
effective_institution_id: str | None = None,
|
||||
) -> RefreshTokenMetadata:
|
||||
"""Builds a refresh token for the specified account IDs, role, organization ID, epoch, and fingerprint hash.
|
||||
|
||||
@@ -1098,7 +1107,7 @@ def _set_refresh_token(
|
||||
Returns:
|
||||
RefreshTokenMetadata: The generated refresh token object.
|
||||
"""
|
||||
expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
|
||||
expires_at = datetime.datetime.now(datetime.UTC) + datetime.timedelta(
|
||||
minutes=REFRESH_TOKEN_EXPIRATION_MINUTES
|
||||
)
|
||||
effective_roles = normalize_roles(effective_roles or effective_role)
|
||||
@@ -1137,7 +1146,7 @@ def _build_access_token(
|
||||
epoch: int,
|
||||
user_fingerprint_hash: str,
|
||||
effective_roles: list[UserRole] | None = None,
|
||||
effective_institution_id: Optional[str] = None,
|
||||
effective_institution_id: str | None = None,
|
||||
) -> AccessToken:
|
||||
"""Builds an access token for the specified account IDs, role, organization ID, epoch, and fingerprint hash.
|
||||
|
||||
@@ -1153,7 +1162,7 @@ def _build_access_token(
|
||||
Returns:
|
||||
AccessToken: The generated access token object.
|
||||
"""
|
||||
expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
|
||||
expires_at = datetime.datetime.now(datetime.UTC) + datetime.timedelta(
|
||||
minutes=ACCESS_TOKEN_EXPIRATION_MINUTES
|
||||
)
|
||||
effective_roles = normalize_roles(effective_roles or effective_role)
|
||||
@@ -1189,7 +1198,7 @@ def _build_access_token(
|
||||
|
||||
|
||||
def _build_token(
|
||||
payload: Dict[str, Any],
|
||||
payload: dict[str, Any],
|
||||
expiration_datetime: datetime.datetime,
|
||||
token_type: TokenType,
|
||||
) -> str:
|
||||
@@ -1203,7 +1212,7 @@ def _build_token(
|
||||
Returns:
|
||||
str: The encoded JWT token.
|
||||
"""
|
||||
now = datetime.datetime.now(datetime.timezone.utc)
|
||||
now = datetime.datetime.now(datetime.UTC)
|
||||
payload.update(
|
||||
{
|
||||
"exp": expiration_datetime,
|
||||
@@ -1219,7 +1228,7 @@ def _build_token(
|
||||
return token
|
||||
|
||||
|
||||
def _verify_id_token(raw_id_token: str, session: Session) -> Dict[str, Any]:
|
||||
def _verify_id_token(raw_id_token: str, session: Session) -> dict[str, Any]:
|
||||
"""Verifies the provided ID token and returns the decoded payload if valid.
|
||||
|
||||
Args:
|
||||
@@ -1239,7 +1248,7 @@ def _verify_id_token(raw_id_token: str, session: Session) -> Dict[str, Any]:
|
||||
return payload
|
||||
|
||||
|
||||
def _verify_refresh_token(raw_refresh_token: str, session: Session) -> Dict[str, Any]:
|
||||
def _verify_refresh_token(raw_refresh_token: str, session: Session) -> dict[str, Any]:
|
||||
"""Verifies the provided refresh token and returns the decoded payload if valid.
|
||||
|
||||
Args:
|
||||
@@ -1263,7 +1272,7 @@ def _verify_access_token_fp(
|
||||
secure_fgp: str,
|
||||
raw_access_token: str,
|
||||
session: Session,
|
||||
) -> Dict[str, Any]:
|
||||
) -> dict[str, Any]:
|
||||
"""Verifies the provided accesstoken against the fingerprint stored in the specified cookie and returns the decoded payload if valid.
|
||||
|
||||
Args:
|
||||
@@ -1381,7 +1390,7 @@ def _get_active_account(session: Session, account_id: uuid.UUID) -> Account:
|
||||
return account
|
||||
|
||||
|
||||
def logout(session: Session, access_token: AccessTokenMetadata) -> Dict[str, str]:
|
||||
def logout(session: Session, access_token: AccessTokenMetadata) -> dict[str, str]:
|
||||
"""Logout the user by incrementing the epoch of the account associated with the provided access token, effectively invalidating all existing tokens for that account.
|
||||
|
||||
Args:
|
||||
@@ -1408,7 +1417,7 @@ def change_password(
|
||||
access_token: AccessTokenMetadata,
|
||||
current_password: str,
|
||||
new_password: str,
|
||||
) -> Dict[str, str]:
|
||||
) -> dict[str, str]:
|
||||
"""Change the password for the user associated with the provided access token.
|
||||
|
||||
Args:
|
||||
@@ -1455,3 +1464,69 @@ def change_password(
|
||||
logger.info("Password changed successfully for account %s", account.id)
|
||||
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
async def can_fetch_gdpr_relevant_data(
|
||||
access_token: AccessTokenMetadata,
|
||||
raw_oa_author_id: str | None = None,
|
||||
raw_oa_institution_id: str | None = None,
|
||||
) -> bool:
|
||||
"""Returns True if the user associated with the provided access token is allowed to fetch GDPR-relevant data for the specified OpenAlex author ID and institution ID, based on their effective institution ID.
|
||||
|
||||
Args:
|
||||
access_token (AccessTokenMetadata): The access token for the user.
|
||||
raw_oa_author_id (str | None, optional): The OpenAlex author ID for which to check access. Defaults to None.
|
||||
raw_oa_institution_id (str | None, optional): The OpenAlex institution ID for which to check access. Defaults to None.
|
||||
|
||||
Returns:
|
||||
bool: True if the user is allowed to fetch GDPR-relevant data for the specified IDs, False otherwise.
|
||||
"""
|
||||
|
||||
logger.debug(
|
||||
"Checking if user with effective institution ID %s can fetch GDPR-relevant data for author ID %s and institution ID %s",
|
||||
access_token.effective_institution_id,
|
||||
raw_oa_author_id,
|
||||
raw_oa_institution_id,
|
||||
)
|
||||
|
||||
if not raw_oa_author_id and not raw_oa_institution_id:
|
||||
logger.debug("No OpenAlex author ID or institution ID provided")
|
||||
return False
|
||||
|
||||
effective_institution_id = access_token.effective_institution_id
|
||||
# Current user does not belong to any institution
|
||||
if not effective_institution_id:
|
||||
logger.debug(
|
||||
"Current user does not belong to any institution, cannot fetch GDPR-relevant data"
|
||||
)
|
||||
return False
|
||||
|
||||
# Current user belongs to an institution, but the request is for a different institution
|
||||
if (
|
||||
raw_oa_institution_id
|
||||
and effective_institution_id
|
||||
and raw_oa_institution_id != effective_institution_id
|
||||
):
|
||||
logger.debug(
|
||||
"Current user belongs to institution %s, but request is for institution %s, cannot fetch GDPR-relevant data",
|
||||
effective_institution_id,
|
||||
raw_oa_institution_id,
|
||||
)
|
||||
return False
|
||||
|
||||
# Current user belongs to an institution, but request is for author not belonging to that institution
|
||||
if raw_oa_author_id:
|
||||
author_belongs_to_institution = (
|
||||
await authors_service.author_currently_belongs_to_institution(
|
||||
raw_oa_author_id or "", effective_institution_id
|
||||
)
|
||||
)
|
||||
logger.debug(
|
||||
"Author %s belongs to institution %s: %s",
|
||||
raw_oa_author_id,
|
||||
effective_institution_id,
|
||||
author_belongs_to_institution,
|
||||
)
|
||||
return author_belongs_to_institution
|
||||
|
||||
return True
|
||||
|
||||
@@ -1,24 +1,22 @@
|
||||
import inse.config as config_module
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
from sqlmodel import Session, SQLModel, create_engine, select
|
||||
|
||||
|
||||
from fastapi import Response, HTTPException
|
||||
import datetime as _dt
|
||||
import uuid
|
||||
from datetime import timedelta
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException, Response
|
||||
from sqlmodel import Session, SQLModel, create_engine, select
|
||||
|
||||
import inse.config as config_module
|
||||
from inse.auth import service as auth_service
|
||||
from inse.auth.model import (
|
||||
AccessToken,
|
||||
AccessTokenMetadata,
|
||||
Account,
|
||||
IdTokenMetadata,
|
||||
Organization,
|
||||
RefreshTokenMetadata,
|
||||
Secret,
|
||||
SecretPurpose,
|
||||
AccessToken,
|
||||
IdTokenMetadata,
|
||||
AccessTokenMetadata,
|
||||
RefreshTokenMetadata,
|
||||
UserRole,
|
||||
)
|
||||
|
||||
@@ -188,7 +186,7 @@ def test_access_and_refresh_token_flow(in_memory_session, settings_backup):
|
||||
refresh_payload[auth_service.EFFECTIVE_ACCOUNT_ID_KEY]
|
||||
),
|
||||
expires_at=_dt.datetime.fromtimestamp(
|
||||
refresh_payload["exp"], tz=_dt.timezone.utc
|
||||
refresh_payload["exp"], tz=_dt.UTC
|
||||
),
|
||||
epoch=refresh_payload[auth_service.EPOCH_KEY],
|
||||
effective_role=UserRole(refresh_payload[auth_service.EFFECTIVE_ROLE_KEY]),
|
||||
@@ -346,7 +344,7 @@ def test_login_with_expired_secret(in_memory_session, settings_backup):
|
||||
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||
assert acc.id is not None
|
||||
|
||||
expired_at = _dt.datetime.now(_dt.timezone.utc) - timedelta(minutes=10)
|
||||
expired_at = _dt.datetime.now(_dt.UTC) - timedelta(minutes=10)
|
||||
secret = Secret(
|
||||
account_id=acc.id,
|
||||
purpose=SecretPurpose.LOGIN_OTK,
|
||||
@@ -593,7 +591,7 @@ def test_expired_jwt_token_raises(in_memory_session, settings_backup):
|
||||
assert acc.id is not None
|
||||
|
||||
response = Response()
|
||||
past = _dt.datetime.now(_dt.timezone.utc) - timedelta(minutes=5)
|
||||
past = _dt.datetime.now(_dt.UTC) - timedelta(minutes=5)
|
||||
access_fingerprint_hash = auth_service._set_access_fp_cookie(response)
|
||||
payload = {
|
||||
auth_service.REAL_ACCOUNT_ID_KEY: str(acc.id),
|
||||
@@ -624,7 +622,7 @@ def test_missing_hmac_key_raises_value_error(settings_backup):
|
||||
with pytest.raises(ValueError):
|
||||
auth_service._build_token(
|
||||
payload={},
|
||||
expiration_datetime=_dt.datetime.now(_dt.timezone.utc),
|
||||
expiration_datetime=_dt.datetime.now(_dt.UTC),
|
||||
token_type=auth_service.TokenType.ID_TOKEN,
|
||||
)
|
||||
config_module.settings.token_hmac_key = saved
|
||||
@@ -715,7 +713,7 @@ def test_reset_password_changes_password_and_increments_epoch(in_memory_session)
|
||||
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),
|
||||
expires_at=_dt.datetime.now(_dt.UTC) + timedelta(minutes=5),
|
||||
)
|
||||
in_memory_session.add(secret)
|
||||
in_memory_session.commit()
|
||||
@@ -753,7 +751,7 @@ def test_reset_password_rejects_reused_token(in_memory_session):
|
||||
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),
|
||||
expires_at=_dt.datetime.now(_dt.UTC) + timedelta(minutes=5),
|
||||
)
|
||||
in_memory_session.add(secret)
|
||||
in_memory_session.commit()
|
||||
@@ -792,7 +790,7 @@ def test_reset_password_rejects_expired_token(in_memory_session):
|
||||
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),
|
||||
expires_at=_dt.datetime.now(_dt.UTC) - timedelta(minutes=1),
|
||||
)
|
||||
in_memory_session.add(secret)
|
||||
in_memory_session.commit()
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterable
|
||||
from datetime import datetime, timezone
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any, Literal
|
||||
|
||||
|
||||
AFFILIATION_LOOKBACK_YEARS = 2
|
||||
OPENALEX_ID_PREFIX = "https://openalex.org/"
|
||||
AffiliationYearMode = Literal["all", "in", "from"]
|
||||
AffiliationYearMode = Literal["all", "in", "from", "between"]
|
||||
|
||||
|
||||
def current_affiliation_year_cutoff(
|
||||
@@ -21,7 +20,7 @@ def current_affiliation_year_cutoff(
|
||||
when needed.
|
||||
"""
|
||||
|
||||
current_time = reference_time or datetime.now(timezone.utc)
|
||||
current_time = reference_time or datetime.now(UTC)
|
||||
return current_time.year - AFFILIATION_LOOKBACK_YEARS
|
||||
|
||||
|
||||
@@ -29,17 +28,20 @@ def build_institution_affiliation_query(
|
||||
institution_id: str,
|
||||
year_mode: AffiliationYearMode = "all",
|
||||
year: int | None = None,
|
||||
year_to: int | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Build an affiliation query for an institution and optional year rule.
|
||||
|
||||
``all`` accepts an affiliation from any year and requires ``year=None``.
|
||||
``in`` requires an affiliation in exactly ``year``.
|
||||
``from`` requires an affiliation in ``year`` or any later year.
|
||||
``between`` requires an affiliation between ``year`` and ``year_to``,
|
||||
including both boundary years.
|
||||
Institution IDs are normalized to their full OpenAlex URL.
|
||||
"""
|
||||
|
||||
normalized_institution_id = _normalize_openalex_id(institution_id)
|
||||
_validate_year_mode(year_mode, year)
|
||||
_validate_year_mode(year_mode, year, year_to)
|
||||
|
||||
affiliation_filters: list[dict[str, Any]] = [
|
||||
{
|
||||
@@ -56,6 +58,17 @@ def build_institution_affiliation_query(
|
||||
affiliation_filters.append(
|
||||
{"range": {"affiliations.years": {"gte": year}}}
|
||||
)
|
||||
elif year_mode == "between":
|
||||
affiliation_filters.append(
|
||||
{
|
||||
"range": {
|
||||
"affiliations.years": {
|
||||
"gte": year,
|
||||
"lte": year_to,
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
"nested": {
|
||||
@@ -69,6 +82,7 @@ def build_institution_membership_query(
|
||||
institution_id: str,
|
||||
year_mode: AffiliationYearMode = "all",
|
||||
year: int | None = None,
|
||||
year_to: int | None = None,
|
||||
author_ids: Iterable[str] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Build an institution membership query for the selected year mode.
|
||||
@@ -83,10 +97,11 @@ def build_institution_membership_query(
|
||||
last-known institution IDs are available.
|
||||
|
||||
``in`` deliberately excludes condition 2 because an exact year requires
|
||||
explicit affiliation evidence for that year. When ``author_ids`` are
|
||||
supplied, the query is restricted to those authors in the same
|
||||
Elasticsearch request. Empty ``author_ids`` produce ``match_none``.
|
||||
Institution and author IDs are normalized to full OpenAlex URLs.
|
||||
explicit affiliation evidence for that year. ``between`` applies the same
|
||||
rule to its bounded period. When ``author_ids`` are supplied, the query is
|
||||
restricted to those authors in the same Elasticsearch request. Empty
|
||||
``author_ids`` produce ``match_none``. Institution and author IDs are
|
||||
normalized to full OpenAlex URLs.
|
||||
"""
|
||||
|
||||
normalized_institution_id = _normalize_openalex_id(institution_id)
|
||||
@@ -94,6 +109,7 @@ def build_institution_membership_query(
|
||||
normalized_institution_id,
|
||||
year_mode=year_mode,
|
||||
year=year,
|
||||
year_to=year_to,
|
||||
)
|
||||
|
||||
author_filters: list[dict[str, Any]] = []
|
||||
@@ -158,7 +174,7 @@ def build_institution_membership_query(
|
||||
}
|
||||
},
|
||||
]
|
||||
if year_mode != "in":
|
||||
if year_mode in {"all", "from"}:
|
||||
# Last-known is the fallback only when affiliation IDs are unavailable.
|
||||
membership_branches.insert(
|
||||
1,
|
||||
@@ -213,15 +229,28 @@ def build_active_institution_membership_query(
|
||||
def _validate_year_mode(
|
||||
year_mode: AffiliationYearMode,
|
||||
year: int | None,
|
||||
year_to: int | None,
|
||||
) -> None:
|
||||
if year_mode not in {"all", "in", "from"}:
|
||||
if year_mode not in {"all", "in", "from", "between"}:
|
||||
raise ValueError(f"Unsupported affiliation year mode: {year_mode}")
|
||||
if year_mode == "all":
|
||||
if year is not None:
|
||||
raise ValueError("year must be omitted when year_mode is 'all'")
|
||||
if year is not None or year_to is not None:
|
||||
raise ValueError(
|
||||
"year and year_to must be omitted when year_mode is 'all'"
|
||||
)
|
||||
return
|
||||
if isinstance(year, bool) or not isinstance(year, int):
|
||||
raise ValueError(f"year is required when year_mode is '{year_mode}'")
|
||||
if year_mode != "between":
|
||||
if year_to is not None:
|
||||
raise ValueError(
|
||||
f"year_to must be omitted when year_mode is '{year_mode}'"
|
||||
)
|
||||
return
|
||||
if isinstance(year_to, bool) or not isinstance(year_to, int):
|
||||
raise ValueError("year_to is required when year_mode is 'between'")
|
||||
if year > year_to:
|
||||
raise ValueError("year must be less than or equal to year_to")
|
||||
|
||||
|
||||
def _normalize_openalex_id(raw_id: str) -> str:
|
||||
|
||||
@@ -65,7 +65,7 @@ def mark_collaboration_graph_job_completed(
|
||||
return
|
||||
job.status = CollaborationGraphStatus.COMPLETED
|
||||
job.set_result(result)
|
||||
job.updated_at = datetime.datetime.now(datetime.timezone.utc)
|
||||
job.updated_at = datetime.datetime.now(datetime.UTC)
|
||||
session.add(job)
|
||||
session.commit()
|
||||
|
||||
@@ -86,7 +86,7 @@ def mark_collaboration_graph_job_failed(
|
||||
return
|
||||
job.status = CollaborationGraphStatus.FAILED
|
||||
job.error_message = error_message
|
||||
job.updated_at = datetime.datetime.now(datetime.timezone.utc)
|
||||
job.updated_at = datetime.datetime.now(datetime.UTC)
|
||||
session.add(job)
|
||||
session.commit()
|
||||
|
||||
@@ -103,7 +103,7 @@ def cleanup_old_collaboration_graph_jobs(
|
||||
Returns:
|
||||
int: The number of stale jobs that were cleaned up.
|
||||
"""
|
||||
cutoff_time = datetime.datetime.now(datetime.timezone.utc) - max_age
|
||||
cutoff_time = datetime.datetime.now(datetime.UTC) - max_age
|
||||
statement = select(CollaborationGraphJob).where(
|
||||
CollaborationGraphJob.created_at < cutoff_time
|
||||
)
|
||||
|
||||
@@ -9,6 +9,7 @@ from inse.authors.v2.model import (
|
||||
StartCollaborationGraphResponse,
|
||||
)
|
||||
from inse.database import SessionDep
|
||||
from inse.models.openalex.author import Author
|
||||
from inse.router_prefixes import RouterPrefixes
|
||||
from inse.tags import Tags
|
||||
|
||||
@@ -18,6 +19,22 @@ logger = logging.getLogger(__name__)
|
||||
router = APIRouter(prefix=RouterPrefixes.AUTHORS_V2, tags=[Tags.AUTHORS_V2])
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{raw_oa_author_id}",
|
||||
operation_id="getAuthorById",
|
||||
summary="Returns an author for a given author ID.",
|
||||
)
|
||||
async def get_author_by_id(
|
||||
raw_oa_author_id: Annotated[
|
||||
str,
|
||||
Path(description="The ID of the author to retrieve."),
|
||||
],
|
||||
) -> Author:
|
||||
return await authors_service.get_author_by_id_strict_or_raise(
|
||||
raw_oa_author_id=raw_oa_author_id
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/authors/id",
|
||||
operation_id="getAuthorsByIds",
|
||||
|
||||
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
@@ -18,6 +18,7 @@ from inse.authors.v2.model import (
|
||||
StartCollaborationGraphResponse,
|
||||
WorkNode,
|
||||
)
|
||||
from inse.exceptions import NotFoundException
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESIndex
|
||||
from inse.models.openalex.author import Author
|
||||
@@ -68,21 +69,41 @@ async def search_authors(
|
||||
return AuthorPage(elements=authors, total=len(authors), page=page, size=size)
|
||||
|
||||
|
||||
async def get_author_by_id(author_id: str) -> Author | None:
|
||||
async def get_author_by_id(raw_oa_author_id: str) -> Author | None:
|
||||
"""Retrieves an author from the OpenAlex Elasticsearch index based on the provided author ID.
|
||||
|
||||
Args:
|
||||
author_id (str): The ID of the author to retrieve.
|
||||
raw_oa_author_id (str): The raw OpenAlex author ID of the author to retrieve.
|
||||
|
||||
Returns:
|
||||
Optional[Author]: The retrieved author, or None if not found.
|
||||
"""
|
||||
response = await elasticsearch.get(index=ESIndex.OPENALEX_AUTHORS, doc_id=author_id)
|
||||
response = await elasticsearch.get(
|
||||
index=ESIndex.OPENALEX_AUTHORS, doc_id=raw_oa_author_id
|
||||
)
|
||||
if not response.get("found"):
|
||||
return None
|
||||
return Author.from_dict(response.get("_source", {})) # type: ignore
|
||||
|
||||
|
||||
async def get_author_by_id_strict_or_raise(raw_oa_author_id: str) -> Author:
|
||||
"""Retrieves an author from the OpenAlex Elasticsearch index based on the provided author ID.
|
||||
|
||||
Args:
|
||||
raw_oa_author_id (str): The raw OpenAlex author ID of the author to retrieve.
|
||||
|
||||
Returns:
|
||||
Author: The retrieved author.
|
||||
|
||||
Raises:
|
||||
ValueError: If the author is not found.
|
||||
"""
|
||||
author = await get_author_by_id(raw_oa_author_id=raw_oa_author_id)
|
||||
if not author:
|
||||
raise NotFoundException(f"Author with ID {raw_oa_author_id} not found.")
|
||||
return author
|
||||
|
||||
|
||||
async def autocomplete_authors_for_selector(query: str) -> AuthorPage:
|
||||
"""Autocompletes authors based on a search term for use in a selector component.
|
||||
|
||||
@@ -121,7 +142,7 @@ async def get_authors_by_ids(author_ids: list[str]) -> AuthorPage:
|
||||
|
||||
return await search_authors(
|
||||
page=0,
|
||||
size=len(author_ids),
|
||||
size=min(10000, len(author_ids)),
|
||||
query={"terms": {"id": author_ids}},
|
||||
source=[
|
||||
"id",
|
||||
@@ -367,7 +388,7 @@ async def _build_collaboration_graph(
|
||||
f"Searching works for collaboration graph of author {raw_oa_author_id} with query: {query}"
|
||||
)
|
||||
|
||||
work_page: WorkPageV2 = await works_service.search_works(
|
||||
work_page: WorkPageV2 = await works_service._search_works(
|
||||
query=query,
|
||||
source=COLLABORATION_GRAPH_SOURCE_FIELDS,
|
||||
page=0,
|
||||
|
||||
@@ -2,9 +2,8 @@
|
||||
Database tables and API schemas for the background job runner.
|
||||
"""
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from datetime import UTC, datetime
|
||||
from enum import StrEnum
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel
|
||||
from sqlmodel import JSON, Column, Field, SQLModel
|
||||
@@ -23,13 +22,13 @@ class JobTriggeredBy(StrEnum):
|
||||
|
||||
|
||||
def utcnow() -> datetime:
|
||||
return datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
return datetime.now(UTC).replace(tzinfo=None)
|
||||
|
||||
|
||||
class JobDefinition(SQLModel, table=True):
|
||||
__tablename__ = "background_job_definition"
|
||||
|
||||
id: Optional[int] = Field(default=None, primary_key=True)
|
||||
id: int | None = Field(default=None, primary_key=True)
|
||||
name: str = Field(
|
||||
index=True, unique=True, description="Human-readable job name shown in the UI."
|
||||
)
|
||||
@@ -37,12 +36,12 @@ class JobDefinition(SQLModel, table=True):
|
||||
target_index: str = Field(
|
||||
default="", description="Elasticsearch index the job writes to (UI info)."
|
||||
)
|
||||
image: Optional[str] = Field(
|
||||
image: str | None = Field(
|
||||
default=None,
|
||||
description="Docker image to run. Null falls back to the configured "
|
||||
"background-jobs image.",
|
||||
)
|
||||
command: Optional[str] = Field(
|
||||
command: str | None = Field(
|
||||
default=None,
|
||||
description="Command passed to the image. Null uses the job name (for "
|
||||
"known jobs) or the image's default entrypoint.",
|
||||
@@ -52,14 +51,14 @@ class JobDefinition(SQLModel, table=True):
|
||||
sa_column=Column(JSON),
|
||||
description="Extra environment variables passed to the container.",
|
||||
)
|
||||
schedule: Optional[str] = Field(
|
||||
schedule: str | None = Field(
|
||||
default=None,
|
||||
description="Cron expression in UTC (e.g. '0 3 * * *'). Null = manual only.",
|
||||
)
|
||||
enabled: bool = Field(
|
||||
default=True, description="Disabled definitions are never scheduled."
|
||||
)
|
||||
next_run_at: Optional[datetime] = Field(
|
||||
next_run_at: datetime | None = Field(
|
||||
default=None, description="Computed by the scheduler from the cron expression."
|
||||
)
|
||||
created_at: datetime = Field(default_factory=utcnow)
|
||||
@@ -68,19 +67,19 @@ class JobDefinition(SQLModel, table=True):
|
||||
class JobRun(SQLModel, table=True):
|
||||
__tablename__ = "background_job_run"
|
||||
|
||||
id: Optional[int] = Field(default=None, primary_key=True)
|
||||
id: int | None = Field(default=None, primary_key=True)
|
||||
definition_id: int = Field(
|
||||
foreign_key="background_job_definition.id", index=True
|
||||
)
|
||||
container_id: Optional[str] = Field(default=None)
|
||||
container_id: str | None = Field(default=None)
|
||||
status: JobRunStatus = Field(default=JobRunStatus.RUNNING)
|
||||
triggered_by: JobTriggeredBy = Field(
|
||||
description="Whether the scheduler or a superadmin started this run."
|
||||
)
|
||||
started_at: datetime = Field(default_factory=utcnow)
|
||||
finished_at: Optional[datetime] = Field(default=None)
|
||||
exit_code: Optional[int] = Field(default=None)
|
||||
logs: Optional[str] = Field(
|
||||
finished_at: datetime | None = Field(default=None)
|
||||
exit_code: int | None = Field(default=None)
|
||||
logs: str | None = Field(
|
||||
default=None,
|
||||
description="Captured stdout/stderr, filled in when the run finishes "
|
||||
"(the container itself is removed afterwards).",
|
||||
@@ -89,24 +88,24 @@ class JobRun(SQLModel, table=True):
|
||||
|
||||
class JobDefinitionCreateRequest(BaseModel):
|
||||
name: str
|
||||
image: Optional[str] = None
|
||||
command: Optional[str] = None
|
||||
image: str | None = None
|
||||
command: str | None = None
|
||||
env: dict[str, str] = {}
|
||||
description: str = ""
|
||||
target_index: str = ""
|
||||
schedule: Optional[str] = None
|
||||
schedule: str | None = None
|
||||
enabled: bool = True
|
||||
|
||||
|
||||
class JobDefinitionUpdateRequest(BaseModel):
|
||||
name: Optional[str] = None
|
||||
image: Optional[str] = None
|
||||
command: Optional[str] = None
|
||||
env: Optional[dict[str, str]] = None
|
||||
description: Optional[str] = None
|
||||
target_index: Optional[str] = None
|
||||
schedule: Optional[str] = None
|
||||
enabled: Optional[bool] = None
|
||||
name: str | None = None
|
||||
image: str | None = None
|
||||
command: str | None = None
|
||||
env: dict[str, str] | None = None
|
||||
description: str | None = None
|
||||
target_index: str | None = None
|
||||
schedule: str | None = None
|
||||
enabled: bool | None = None
|
||||
|
||||
|
||||
class BackgroundJobTask(BaseModel):
|
||||
@@ -114,13 +113,13 @@ class BackgroundJobTask(BaseModel):
|
||||
name: str
|
||||
description: str
|
||||
target_index: str
|
||||
image: Optional[str]
|
||||
command: Optional[str]
|
||||
image: str | None
|
||||
command: str | None
|
||||
env: dict[str, str]
|
||||
schedule: Optional[str]
|
||||
schedule: str | None
|
||||
enabled: bool
|
||||
next_run_at: Optional[datetime]
|
||||
last_run: Optional[JobRun]
|
||||
next_run_at: datetime | None
|
||||
last_run: JobRun | None
|
||||
status: str
|
||||
|
||||
|
||||
|
||||
@@ -11,11 +11,11 @@ from .model import (
|
||||
AvailableImages,
|
||||
BackgroundJobTask,
|
||||
DockerHealth,
|
||||
RegistryHealth,
|
||||
JobDefinitionCreateRequest,
|
||||
JobDefinitionUpdateRequest,
|
||||
JobRun,
|
||||
JobRunLogs,
|
||||
RegistryHealth,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/api/background-jobs", tags=[Tags.BACKGROUND_JOBS])
|
||||
|
||||
@@ -8,7 +8,6 @@ import logging
|
||||
import re
|
||||
from datetime import datetime
|
||||
from threading import RLock
|
||||
from typing import Optional
|
||||
|
||||
import docker
|
||||
import httpx
|
||||
@@ -28,7 +27,7 @@ settings = config.get_settings()
|
||||
|
||||
RUN_STATE_LOCK = RLock()
|
||||
|
||||
_client: Optional[docker.DockerClient] = None
|
||||
_client: docker.DockerClient | None = None
|
||||
|
||||
|
||||
def get_docker_client() -> docker.DockerClient:
|
||||
@@ -42,7 +41,7 @@ def docker_reachable() -> tuple[bool, str]:
|
||||
try:
|
||||
get_docker_client().ping()
|
||||
return True, "ok"
|
||||
except Exception as error: # noqa: BLE001
|
||||
except Exception as error:
|
||||
return False, str(error)
|
||||
|
||||
|
||||
@@ -59,7 +58,7 @@ def registry_reachable() -> tuple[bool, str]:
|
||||
if response.status_code == 401:
|
||||
return False, "authentication failed (401)"
|
||||
return False, f"unexpected status {response.status_code}"
|
||||
except Exception as error: # noqa: BLE001
|
||||
except Exception as error:
|
||||
return False, str(error)
|
||||
|
||||
|
||||
@@ -110,23 +109,23 @@ def list_registry_images() -> tuple[list[str], str]:
|
||||
response = client.get(f"{base}/v2/{repository}/tags/list")
|
||||
response.raise_for_status()
|
||||
tags = response.json().get("tags") or []
|
||||
except Exception: # noqa: BLE001
|
||||
except Exception:
|
||||
tags = []
|
||||
if tags:
|
||||
images.extend(f"{host}/{repository}:{tag}" for tag in tags)
|
||||
else:
|
||||
images.append(f"{host}/{repository}")
|
||||
return sorted(images), ""
|
||||
except Exception as error: # noqa: BLE001
|
||||
except Exception as error:
|
||||
logger.warning("Could not list registry images.", exc_info=True)
|
||||
return [], str(error)
|
||||
|
||||
|
||||
def resolve_image(definition: JobDefinition) -> Optional[str]:
|
||||
def resolve_image(definition: JobDefinition) -> str | None:
|
||||
return definition.image or None
|
||||
|
||||
|
||||
def is_registry_image(image: Optional[str]) -> bool:
|
||||
def is_registry_image(image: str | None) -> bool:
|
||||
return bool(image) and image.split("/", 1)[0] == registry_host()
|
||||
|
||||
|
||||
@@ -151,7 +150,7 @@ def resolve_environment(definition: JobDefinition) -> dict[str, str]:
|
||||
return {**base, **(definition.env or {})}
|
||||
|
||||
|
||||
def registry_auth() -> Optional[dict[str, str]]:
|
||||
def registry_auth() -> dict[str, str] | None:
|
||||
if (
|
||||
settings.background_jobs_registry_username
|
||||
and settings.background_jobs_registry_password
|
||||
@@ -189,7 +188,7 @@ def start_run(
|
||||
if settings.background_jobs_pull_before_run and is_registry_image(image):
|
||||
try:
|
||||
pull_image(image)
|
||||
except Exception as error: # noqa: BLE001
|
||||
except Exception as error:
|
||||
run.status = JobRunStatus.FAILED
|
||||
run.finished_at = utcnow()
|
||||
run.logs = (
|
||||
@@ -211,7 +210,7 @@ def start_run(
|
||||
remove=False,
|
||||
)
|
||||
run.container_id = container.id
|
||||
except Exception as error: # noqa: BLE001
|
||||
except Exception as error:
|
||||
run.status = JobRunStatus.FAILED
|
||||
run.finished_at = utcnow()
|
||||
run.logs = (
|
||||
@@ -241,8 +240,8 @@ def schedule_due_jobs(session: Session) -> None:
|
||||
now = utcnow()
|
||||
scheduled = session.exec(
|
||||
select(JobDefinition).where(
|
||||
JobDefinition.enabled == True, # noqa: E712
|
||||
JobDefinition.schedule != None, # noqa: E711
|
||||
JobDefinition.enabled == True,
|
||||
JobDefinition.schedule != None,
|
||||
)
|
||||
).all()
|
||||
|
||||
@@ -276,8 +275,8 @@ def finalize_run(
|
||||
*,
|
||||
new_status: JobRunStatus,
|
||||
expected_status: JobRunStatus = JobRunStatus.RUNNING,
|
||||
exit_code: Optional[int] = None,
|
||||
logs: Optional[str] = None,
|
||||
exit_code: int | None = None,
|
||||
logs: str | None = None,
|
||||
) -> bool:
|
||||
values: dict = {"status": new_status, "finished_at": utcnow()}
|
||||
if exit_code is not None:
|
||||
@@ -300,7 +299,7 @@ def append_system_log(logs: str, message: str) -> str:
|
||||
def remove_container(container, run_id: int) -> None:
|
||||
try:
|
||||
container.remove()
|
||||
except Exception: # noqa: BLE001
|
||||
except Exception:
|
||||
logger.warning(
|
||||
"Could not remove container for run %s.", run_id, exc_info=True
|
||||
)
|
||||
@@ -371,6 +370,6 @@ async def scheduler_loop() -> None:
|
||||
while True:
|
||||
try:
|
||||
await asyncio.to_thread(tick)
|
||||
except Exception: # noqa: BLE001
|
||||
except Exception:
|
||||
logger.exception("Background job scheduler tick failed.")
|
||||
await asyncio.sleep(settings.background_jobs_tick_seconds)
|
||||
|
||||
@@ -17,7 +17,6 @@ from .model import (
|
||||
AvailableImages,
|
||||
BackgroundJobTask,
|
||||
DockerHealth,
|
||||
RegistryHealth,
|
||||
JobDefinition,
|
||||
JobDefinitionCreateRequest,
|
||||
JobDefinitionUpdateRequest,
|
||||
@@ -25,6 +24,7 @@ from .model import (
|
||||
JobRunLogs,
|
||||
JobRunStatus,
|
||||
JobTriggeredBy,
|
||||
RegistryHealth,
|
||||
utcnow,
|
||||
)
|
||||
|
||||
@@ -289,7 +289,7 @@ def get_run_logs(
|
||||
"utf-8", errors="replace"
|
||||
),
|
||||
)
|
||||
except Exception: # noqa: BLE001
|
||||
except Exception:
|
||||
pass
|
||||
return JobRunLogs(
|
||||
run_id=run_id, status=run.status, logs=_tail_log_lines(run.logs or "")
|
||||
@@ -319,7 +319,7 @@ def stop_run(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail=f"Container for run {run_id} no longer exists.",
|
||||
) from error
|
||||
except Exception as error: # noqa: BLE001
|
||||
except Exception as error:
|
||||
logger.warning(
|
||||
"Could not inspect run %s before stopping.", run_id, exc_info=True
|
||||
)
|
||||
@@ -340,7 +340,7 @@ def stop_run(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail=f"Could not stop container for run {run_id}.",
|
||||
) from error
|
||||
except Exception as error: # noqa: BLE001
|
||||
except Exception as error:
|
||||
logger.warning("Could not stop run %s.", run_id, exc_info=True)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from pydantic import BaseModel, Field as PydanticField
|
||||
from pydantic import BaseModel
|
||||
from pydantic import Field as PydanticField
|
||||
from sqlalchemy import UniqueConstraint
|
||||
from sqlmodel import Field, SQLModel
|
||||
|
||||
@@ -21,7 +22,7 @@ class PersonBookmark(SQLModel, table=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
|
||||
default_factory=lambda: datetime.now(UTC), nullable=False, index=True
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -7,7 +7,6 @@ from inse.database import SessionDep
|
||||
from . import service
|
||||
from .model import CreatePersonBookmark, PersonBookmarkResponse
|
||||
|
||||
|
||||
router = APIRouter(prefix="/api/bookmarks", tags=["Bookmarks"])
|
||||
|
||||
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from . import model
|
||||
from inse.authors.v2.service import author_currently_belongs_to_institution
|
||||
from inse.exceptions import NotFoundException
|
||||
|
||||
from . import model
|
||||
from .search_client import CompanyConnectionsSearchClient
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -1,14 +1,10 @@
|
||||
from typing import Any
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
from inse.exceptions import ElasticsearchNotFoundException
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster
|
||||
from inse.exceptions import ElasticsearchNotFoundException
|
||||
|
||||
|
||||
from inse.exceptions import MissingApiKeyError
|
||||
from .. import config
|
||||
|
||||
|
||||
class CompanyConnectionsSearchClient:
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
REST API for possible company connections of OpenAlex authors.
|
||||
"""
|
||||
|
||||
@@ -1,17 +1,16 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
This module contains the configuration properties
|
||||
that can be adjusted via environment variables.
|
||||
"""
|
||||
|
||||
from functools import lru_cache
|
||||
import logging
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
from typing import Dict, List, Literal, Optional
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
from dotenv import load_dotenv
|
||||
from typing import Literal
|
||||
|
||||
from dotenv import load_dotenv
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -35,17 +34,17 @@ class Settings(BaseSettings):
|
||||
openalex_works_search_timeout_seconds: float = 30.0
|
||||
# OpenAlex public API config
|
||||
openalex_api_base_url: str = "https://api.openalex.org"
|
||||
openalex_api_key: Optional[str] = None
|
||||
openalex_api_key: str | None = None
|
||||
openalex_api_timeout_seconds: float = 30.0
|
||||
|
||||
# Patent Elasticsearch config
|
||||
patent_elasticsearch_url: str = "https://inse.nes.uni-due.de/elastic"
|
||||
patent_elasticsearch_api_key: Optional[str] = None
|
||||
patent_elasticsearch_api_key: str | None = None
|
||||
|
||||
# LLM config
|
||||
llm_api_url: Optional[str] = None
|
||||
llm_api_key: Optional[str] = None
|
||||
llm_model: Optional[str] = None
|
||||
llm_api_url: str | None = None
|
||||
llm_api_key: str | None = None
|
||||
llm_model: str | None = None
|
||||
|
||||
# Background job runner config (Docker-out-of-Docker)
|
||||
background_jobs_image: str = "docker.nes.uni-due.de/inse/background-jobs:latest"
|
||||
@@ -58,23 +57,25 @@ class Settings(BaseSettings):
|
||||
# Credentials for pulling the job image from a private registry (e.g. the
|
||||
# Nexus at docker.nes.uni-due.de). Needed because the runner pulls via the
|
||||
# Docker SDK inside the service container, which has no `docker login` creds.
|
||||
background_jobs_registry_username: Optional[str] = None
|
||||
background_jobs_registry_password: Optional[str] = None
|
||||
background_jobs_registry_username: str | None = None
|
||||
background_jobs_registry_password: str | None = None
|
||||
|
||||
# Sentence Transformers config
|
||||
sentence_transformers_model_name: str = "intfloat/multilingual-e5-base"
|
||||
|
||||
# Elasticsearch config
|
||||
elasticsearch_url: str = "https://project.nes.uni-due.de/elastic"
|
||||
elasticsearch_api_key: Optional[str] = None
|
||||
elasticsearch_inse_url: Optional[str] = None
|
||||
elasticsearch_inse_api_key: Optional[str] = None
|
||||
elasticsearch_api_key: str | None = None
|
||||
elasticsearch_inse_url: str | None = None
|
||||
elasticsearch_inse_api_key: str | None = None
|
||||
print_es_queries: bool = False
|
||||
print_es_timings: bool = False
|
||||
|
||||
model_config = SettingsConfigDict(env_file=str(ENV_FILE))
|
||||
|
||||
allowed_origins: List[str] = ["http://localhost:4200"]
|
||||
allowed_origins: list[str] = ["http://localhost:4200"]
|
||||
|
||||
servers: List[Dict[str, str]] = [
|
||||
servers: list[dict[str, str]] = [
|
||||
{"url": "http://localhost:8000", "description": "Local development server"},
|
||||
]
|
||||
|
||||
@@ -82,8 +83,8 @@ class Settings(BaseSettings):
|
||||
|
||||
environment: Literal["dev", "prod"] = "dev"
|
||||
|
||||
token_issuer_id: Optional[str] = None
|
||||
token_hmac_key: Optional[str] = None
|
||||
token_issuer_id: str | None = None
|
||||
token_hmac_key: str | None = None
|
||||
|
||||
skip_otk_validation: bool = True
|
||||
# SMTP / email config
|
||||
@@ -93,8 +94,8 @@ class Settings(BaseSettings):
|
||||
smtp_server: str = "localhost"
|
||||
smtp_port: int = 25
|
||||
smtp_sender: str = "no-reply@smartguide.local"
|
||||
smtp_username: Optional[str] = None
|
||||
smtp_password: Optional[str] = None
|
||||
smtp_username: str | None = None
|
||||
smtp_password: str | None = None
|
||||
smtp_use_tls: bool = False
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
import hashlib
|
||||
from collections import defaultdict
|
||||
from typing import Any
|
||||
|
||||
from inse.institutions.institutions_search_client import InstitutionsSearchClient
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster, ESIndex
|
||||
from inse.projects import service as projects_service
|
||||
|
||||
from .model import BundProjectTopics, DfgProjectKeyword, DfgProjectTopic
|
||||
from .common import (
|
||||
dashboard_period as _dashboard_period,
|
||||
normalize_institution_id as _normalize_institution_id,
|
||||
raw_institution_id as _raw_institution_id,
|
||||
)
|
||||
|
||||
|
||||
async def get_dashboard_bund_topics(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> BundProjectTopics:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
page_size = 1000
|
||||
page_number = 0
|
||||
project_ids: set[str] = set()
|
||||
|
||||
while True:
|
||||
projects = await projects_service.search_bund_projects_with_filters(
|
||||
institutions_search_client=InstitutionsSearchClient(),
|
||||
executing_agency=None,
|
||||
raw_oa_institution_id=_raw_institution_id(normalized_id),
|
||||
title=None,
|
||||
keywords=None,
|
||||
funding_arts=None,
|
||||
topic_ids=None,
|
||||
filter_topic_ids=None,
|
||||
funding_start_years=None,
|
||||
funding_end_years=None,
|
||||
active_from_year=period[0],
|
||||
active_to_year=period[1],
|
||||
countries=None,
|
||||
page=page_number,
|
||||
size=page_size,
|
||||
sort_by="id",
|
||||
sort_direction="asc",
|
||||
fuzzy=False,
|
||||
)
|
||||
project_ids.update(
|
||||
project.funding_code
|
||||
for project in projects.elements
|
||||
if project.funding_code
|
||||
)
|
||||
if len(project_ids) >= projects.total or not projects.elements:
|
||||
break
|
||||
page_number += 1
|
||||
|
||||
topics: dict[str, dict[str, Any]] = {}
|
||||
matched_project_ids: set[str] = set()
|
||||
if project_ids:
|
||||
mapping_project_ids = sorted(
|
||||
hashlib.sha256(project_id.encode("utf-8")).hexdigest()
|
||||
for project_id in project_ids
|
||||
)
|
||||
async for hit in elasticsearch.scan(
|
||||
index=str(ESIndex.PROJECTS_BUND_TOPICS),
|
||||
query={"terms": {"project_id": mapping_project_ids}},
|
||||
source=["project_id", "keyword", "topic_matches"],
|
||||
page_size=1000,
|
||||
cluster=ESCluster.INSE,
|
||||
):
|
||||
source = hit.get("_source", {})
|
||||
project_id = str(source.get("project_id") or "")
|
||||
if not project_id:
|
||||
continue
|
||||
keyword = str(source.get("keyword") or "").strip()
|
||||
matched_project_ids.add(project_id)
|
||||
for match in source.get("topic_matches", []):
|
||||
topic_id = str(match.get("topic_id") or "")
|
||||
if not topic_id:
|
||||
continue
|
||||
topic = topics.setdefault(
|
||||
topic_id,
|
||||
{
|
||||
"id": topic_id,
|
||||
"name": str(match.get("topic_display_name") or topic_id),
|
||||
"subfield": match.get("subfield"),
|
||||
"field": match.get("field"),
|
||||
"domain": match.get("domain"),
|
||||
"project_ids": set(),
|
||||
"keywords": {},
|
||||
},
|
||||
)
|
||||
topic["project_ids"].add(project_id)
|
||||
if keyword:
|
||||
topic["keywords"].setdefault(keyword, set()).add(project_id)
|
||||
|
||||
field_project_ids: dict[str, set[str]] = defaultdict(set)
|
||||
subfield_project_ids: dict[tuple[str, str], set[str]] = defaultdict(set)
|
||||
for topic in topics.values():
|
||||
field_name = str(topic["field"] or "")
|
||||
subfield_name = str(topic["subfield"] or "")
|
||||
field_project_ids[field_name].update(topic["project_ids"])
|
||||
subfield_project_ids[(field_name, subfield_name)].update(topic["project_ids"])
|
||||
|
||||
topic_list = [
|
||||
DfgProjectTopic(
|
||||
id=topic["id"],
|
||||
name=topic["name"],
|
||||
subfield=topic["subfield"],
|
||||
field=topic["field"],
|
||||
domain=topic["domain"],
|
||||
project_count=len(topic["project_ids"]),
|
||||
field_project_count=len(field_project_ids[str(topic["field"] or "")]),
|
||||
subfield_project_count=len(
|
||||
subfield_project_ids[
|
||||
(str(topic["field"] or ""), str(topic["subfield"] or ""))
|
||||
]
|
||||
),
|
||||
keywords=sorted(
|
||||
[
|
||||
DfgProjectKeyword(
|
||||
name=keyword,
|
||||
project_count=len(keyword_project_ids),
|
||||
)
|
||||
for keyword, keyword_project_ids in topic["keywords"].items()
|
||||
],
|
||||
key=lambda entry: (-entry.project_count, entry.name),
|
||||
),
|
||||
)
|
||||
for topic in topics.values()
|
||||
]
|
||||
topic_list.sort(key=lambda topic: (-topic.project_count, topic.name, topic.id))
|
||||
return BundProjectTopics(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
project_count=len(project_ids),
|
||||
matched_project_count=len(matched_project_ids),
|
||||
topics=topic_list,
|
||||
)
|
||||
@@ -0,0 +1,92 @@
|
||||
from typing import Any, Literal
|
||||
|
||||
from fastapi import HTTPException, status
|
||||
|
||||
DashboardPeriod = tuple[int | None, int | None]
|
||||
|
||||
|
||||
def dashboard_period(
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> DashboardPeriod:
|
||||
if from_year is not None and to_year is not None and from_year > to_year:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="from_year must be less than or equal to to_year.",
|
||||
)
|
||||
return from_year, to_year
|
||||
|
||||
|
||||
def project_overlap_filter(
|
||||
start_field: str,
|
||||
end_field: str,
|
||||
period: DashboardPeriod,
|
||||
*,
|
||||
missing_end_is_ongoing: bool = False,
|
||||
) -> dict[str, Any] | None:
|
||||
from_year, to_year = period
|
||||
filters: list[dict[str, Any]] = []
|
||||
if to_year is not None:
|
||||
filters.append({"range": {start_field: {"lte": to_year}}})
|
||||
if from_year is not None:
|
||||
end_filter: dict[str, Any] = {"range": {end_field: {"gte": from_year}}}
|
||||
if missing_end_is_ongoing:
|
||||
end_filter = {
|
||||
"bool": {
|
||||
"should": [
|
||||
end_filter,
|
||||
{"bool": {"must_not": {"exists": {"field": end_field}}}},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
filters.append(end_filter)
|
||||
return {"bool": {"filter": filters}} if filters else None
|
||||
|
||||
|
||||
def project_boundary_year_filter(
|
||||
start_field: str,
|
||||
end_field: str,
|
||||
period: DashboardPeriod,
|
||||
date_format: Literal["iso", "de", "year"],
|
||||
) -> dict[str, Any] | None:
|
||||
from_year, to_year = period
|
||||
filters: list[dict[str, Any]] = []
|
||||
if to_year is not None:
|
||||
if date_format == "year":
|
||||
filters.append({"range": {start_field: {"lte": to_year}}})
|
||||
else:
|
||||
last_day = (
|
||||
f"{to_year}-12-31" if date_format == "iso" else f"31.12.{to_year}"
|
||||
)
|
||||
filters.append({"range": {start_field: {"lte": last_day}}})
|
||||
if from_year is not None:
|
||||
if date_format == "year":
|
||||
filters.append({"range": {end_field: {"gte": from_year}}})
|
||||
else:
|
||||
first_day = (
|
||||
f"{from_year}-01-01" if date_format == "iso" else f"01.01.{from_year}"
|
||||
)
|
||||
filters.append({"range": {end_field: {"gte": first_day}}})
|
||||
return {"bool": {"filter": filters}} if filters else None
|
||||
|
||||
|
||||
def normalize_institution_id(value: str) -> str:
|
||||
return (
|
||||
value
|
||||
if value.startswith("https://openalex.org/")
|
||||
else f"https://openalex.org/{value}"
|
||||
)
|
||||
|
||||
|
||||
def raw_institution_id(value: str) -> str:
|
||||
return normalize_institution_id(value).removeprefix("https://openalex.org/")
|
||||
|
||||
|
||||
def institution_works_query(institution_id: str) -> dict[str, Any]:
|
||||
return {
|
||||
"nested": {
|
||||
"path": "authorships.institutions",
|
||||
"query": {"term": {"authorships.institutions.id": institution_id}},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
from collections import defaultdict
|
||||
from typing import Any
|
||||
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster, ESIndex
|
||||
|
||||
from .model import DfgProjectKeyword, DfgProjectTopic, DfgProjectTopics
|
||||
from .common import normalize_institution_id as _normalize_institution_id
|
||||
from .project_ids_service import _get_dfg_project_ids_from_projects_service
|
||||
|
||||
|
||||
async def get_dashboard_dfg_topics(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> DfgProjectTopics:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
project_ids = await _get_dfg_project_ids_from_projects_service(
|
||||
normalized_id,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
topics: dict[str, dict[str, Any]] = {}
|
||||
matched_project_ids: set[str] = set()
|
||||
|
||||
if project_ids:
|
||||
async for hit in elasticsearch.scan(
|
||||
index=str(ESIndex.PROJECTS_DFG_OPENALEX_TOPICS),
|
||||
query={"terms": {"project_id": project_ids}},
|
||||
source=["project_id", "keyword", "topic_matches"],
|
||||
page_size=1000,
|
||||
cluster=ESCluster.INSE,
|
||||
):
|
||||
source = hit.get("_source", {})
|
||||
project_id = str(source.get("project_id") or "")
|
||||
if not project_id:
|
||||
continue
|
||||
keyword = str(source.get("keyword") or "").strip()
|
||||
matched_project_ids.add(project_id)
|
||||
for match in source.get("topic_matches", []):
|
||||
topic_id = str(match.get("topic_id") or "")
|
||||
if not topic_id:
|
||||
continue
|
||||
topic = topics.setdefault(
|
||||
topic_id,
|
||||
{
|
||||
"id": topic_id,
|
||||
"name": str(match.get("topic_display_name") or topic_id),
|
||||
"subfield": match.get("subfield"),
|
||||
"field": match.get("field"),
|
||||
"domain": match.get("domain"),
|
||||
"project_ids": set(),
|
||||
"keywords": {},
|
||||
},
|
||||
)
|
||||
topic["project_ids"].add(project_id)
|
||||
if keyword:
|
||||
topic["keywords"].setdefault(keyword, set()).add(project_id)
|
||||
|
||||
field_project_ids: dict[str, set[str]] = defaultdict(set)
|
||||
subfield_project_ids: dict[tuple[str, str], set[str]] = defaultdict(set)
|
||||
for topic in topics.values():
|
||||
field_name = str(topic["field"] or "")
|
||||
subfield_name = str(topic["subfield"] or "")
|
||||
field_project_ids[field_name].update(topic["project_ids"])
|
||||
subfield_project_ids[(field_name, subfield_name)].update(topic["project_ids"])
|
||||
|
||||
topic_list = [
|
||||
DfgProjectTopic(
|
||||
id=topic["id"],
|
||||
name=topic["name"],
|
||||
subfield=topic["subfield"],
|
||||
field=topic["field"],
|
||||
domain=topic["domain"],
|
||||
project_count=len(topic["project_ids"]),
|
||||
field_project_count=len(field_project_ids[str(topic["field"] or "")]),
|
||||
subfield_project_count=len(
|
||||
subfield_project_ids[
|
||||
(str(topic["field"] or ""), str(topic["subfield"] or ""))
|
||||
]
|
||||
),
|
||||
keywords=sorted(
|
||||
[
|
||||
DfgProjectKeyword(
|
||||
name=keyword,
|
||||
project_count=len(keyword_project_ids),
|
||||
)
|
||||
for keyword, keyword_project_ids in topic["keywords"].items()
|
||||
],
|
||||
key=lambda entry: (-entry.project_count, entry.name),
|
||||
),
|
||||
)
|
||||
for topic in topics.values()
|
||||
]
|
||||
topic_list.sort(key=lambda topic: (-topic.project_count, topic.name, topic.id))
|
||||
return DfgProjectTopics(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
project_count=len(project_ids),
|
||||
matched_project_count=len(matched_project_ids),
|
||||
topics=topic_list,
|
||||
)
|
||||
@@ -0,0 +1,109 @@
|
||||
from collections import defaultdict
|
||||
from typing import Any
|
||||
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster, ESIndex
|
||||
|
||||
from .model import DfgProjectKeyword, DfgProjectTopic, EuProjectTopics
|
||||
from .common import normalize_institution_id as _normalize_institution_id
|
||||
from .project_ids_service import _get_eu_project_ids_from_projects_service
|
||||
|
||||
|
||||
async def get_dashboard_eu_topics(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> EuProjectTopics:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
project_ids = await _get_eu_project_ids_from_projects_service(
|
||||
normalized_id,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
topics: dict[str, dict[str, Any]] = {}
|
||||
matched_project_ids: set[str] = set()
|
||||
|
||||
if project_ids:
|
||||
mapping_indices = (
|
||||
ESIndex.PROJECTS_CORDIS_EU_FP7_TOPICS_MAPPING,
|
||||
ESIndex.PROJECTS_CORDIS_EU_H2020_TOPICS,
|
||||
ESIndex.PROJECTS_CORDIS_EU_HEUROPE_TOPICS,
|
||||
)
|
||||
for mapping_index in mapping_indices:
|
||||
async for hit in elasticsearch.scan(
|
||||
index=str(mapping_index),
|
||||
query={"terms": {"project_id": project_ids}},
|
||||
source=["project_id", "keyword", "topic_matches"],
|
||||
page_size=1000,
|
||||
cluster=ESCluster.INSE,
|
||||
):
|
||||
source = hit.get("_source", {})
|
||||
project_id = str(source.get("project_id") or "")
|
||||
if not project_id:
|
||||
continue
|
||||
keyword = str(source.get("keyword") or "").strip()
|
||||
matched_project_ids.add(project_id)
|
||||
for match in source.get("topic_matches", []):
|
||||
topic_id = str(match.get("topic_id") or "")
|
||||
if not topic_id:
|
||||
continue
|
||||
topic = topics.setdefault(
|
||||
topic_id,
|
||||
{
|
||||
"id": topic_id,
|
||||
"name": str(match.get("topic_display_name") or topic_id),
|
||||
"subfield": match.get("subfield"),
|
||||
"field": match.get("field"),
|
||||
"domain": match.get("domain"),
|
||||
"project_ids": set(),
|
||||
"keywords": {},
|
||||
},
|
||||
)
|
||||
topic["project_ids"].add(project_id)
|
||||
if keyword:
|
||||
topic["keywords"].setdefault(keyword, set()).add(project_id)
|
||||
|
||||
field_project_ids: dict[str, set[str]] = defaultdict(set)
|
||||
subfield_project_ids: dict[tuple[str, str], set[str]] = defaultdict(set)
|
||||
for topic in topics.values():
|
||||
field_name = str(topic["field"] or "")
|
||||
subfield_name = str(topic["subfield"] or "")
|
||||
field_project_ids[field_name].update(topic["project_ids"])
|
||||
subfield_project_ids[(field_name, subfield_name)].update(topic["project_ids"])
|
||||
|
||||
topic_list = [
|
||||
DfgProjectTopic(
|
||||
id=topic["id"],
|
||||
name=topic["name"],
|
||||
subfield=topic["subfield"],
|
||||
field=topic["field"],
|
||||
domain=topic["domain"],
|
||||
project_count=len(topic["project_ids"]),
|
||||
field_project_count=len(field_project_ids[str(topic["field"] or "")]),
|
||||
subfield_project_count=len(
|
||||
subfield_project_ids[
|
||||
(str(topic["field"] or ""), str(topic["subfield"] or ""))
|
||||
]
|
||||
),
|
||||
keywords=sorted(
|
||||
[
|
||||
DfgProjectKeyword(
|
||||
name=keyword,
|
||||
project_count=len(keyword_project_ids),
|
||||
)
|
||||
for keyword, keyword_project_ids in topic["keywords"].items()
|
||||
],
|
||||
key=lambda entry: (-entry.project_count, entry.name),
|
||||
),
|
||||
)
|
||||
for topic in topics.values()
|
||||
]
|
||||
topic_list.sort(key=lambda topic: (-topic.project_count, topic.name, topic.id))
|
||||
return EuProjectTopics(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
project_count=len(project_ids),
|
||||
matched_project_count=len(matched_project_ids),
|
||||
topics=topic_list,
|
||||
)
|
||||
@@ -34,6 +34,19 @@ class BmbfProjectStatusStatistics(BaseModel):
|
||||
completed: int
|
||||
|
||||
|
||||
class DfgProjectStatusStatistics(BaseModel):
|
||||
institution_id: str
|
||||
organization_name: str
|
||||
ongoing: int
|
||||
upcoming: int
|
||||
completed: int
|
||||
|
||||
|
||||
class DfgProjectKeyword(BaseModel):
|
||||
name: str
|
||||
project_count: int
|
||||
|
||||
|
||||
class DfgProjectTopic(BaseModel):
|
||||
id: str
|
||||
name: str
|
||||
@@ -41,6 +54,9 @@ class DfgProjectTopic(BaseModel):
|
||||
field: str | None = None
|
||||
domain: str | None = None
|
||||
project_count: int
|
||||
field_project_count: int
|
||||
subfield_project_count: int
|
||||
keywords: list[DfgProjectKeyword]
|
||||
|
||||
|
||||
class DfgProjectTopics(BaseModel):
|
||||
@@ -51,6 +67,22 @@ class DfgProjectTopics(BaseModel):
|
||||
topics: list[DfgProjectTopic]
|
||||
|
||||
|
||||
class EuProjectTopics(BaseModel):
|
||||
institution_id: str
|
||||
organization_name: str
|
||||
project_count: int
|
||||
matched_project_count: int
|
||||
topics: list[DfgProjectTopic]
|
||||
|
||||
|
||||
class BundProjectTopics(BaseModel):
|
||||
institution_id: str
|
||||
organization_name: str
|
||||
project_count: int
|
||||
matched_project_count: int
|
||||
topics: list[DfgProjectTopic]
|
||||
|
||||
|
||||
class TopAuthor(BaseModel):
|
||||
id: str | None = None
|
||||
name: str
|
||||
@@ -60,11 +92,17 @@ class TopAuthor(BaseModel):
|
||||
class TopAuthorStatistics(BaseModel):
|
||||
institution_id: str
|
||||
works: list[TopAuthor]
|
||||
projects: list[TopAuthor]
|
||||
eu_projects: list[TopAuthor]
|
||||
patents: list[TopAuthor]
|
||||
news: list[TopAuthor]
|
||||
|
||||
|
||||
class TopAuthorAnalysis(BaseModel):
|
||||
institution_id: str
|
||||
authors: list[TopAuthor]
|
||||
|
||||
|
||||
class TopicHeatmapValue(BaseModel):
|
||||
year: int
|
||||
count: int
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
from inse.institutions.institutions_search_client import InstitutionsSearchClient
|
||||
from inse.projects import service as projects_service
|
||||
from inse.projects.model import EuCordisProjectType
|
||||
|
||||
from .common import (
|
||||
dashboard_period as _dashboard_period,
|
||||
raw_institution_id as _raw_institution_id,
|
||||
)
|
||||
|
||||
|
||||
async def _get_dfg_project_ids_from_projects_service(
|
||||
institution_id: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> list[str]:
|
||||
"""Returns every matching DFG project ID through the canonical project service."""
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
page_size = 1000
|
||||
page_number = 0
|
||||
project_ids: set[str] = set()
|
||||
|
||||
while True:
|
||||
projects = await projects_service.get_dfg_projects(
|
||||
institutions_search_client=InstitutionsSearchClient(),
|
||||
raw_oa_institution_id=_raw_institution_id(institution_id),
|
||||
author_id=None,
|
||||
author_filter_ids=None,
|
||||
institution_ids=None,
|
||||
keywords=None,
|
||||
topic_ids=None,
|
||||
filter_topic_ids=None,
|
||||
title=None,
|
||||
funding_start_years=(
|
||||
[str(year) for year in range(1900, period[1] + 1)]
|
||||
if period[1] is not None
|
||||
else None
|
||||
),
|
||||
funding_end_years=(
|
||||
[str(year) for year in range(period[0], 2101)]
|
||||
if period[0] is not None
|
||||
else None
|
||||
),
|
||||
page=page_number,
|
||||
size=page_size,
|
||||
sort_by="id",
|
||||
sort_direction="asc",
|
||||
fuzzy=False,
|
||||
skip_enrichment=True,
|
||||
)
|
||||
project_ids.update(project.id for project in projects.elements if project.id)
|
||||
if len(project_ids) >= projects.total or not projects.elements:
|
||||
break
|
||||
page_number += 1
|
||||
|
||||
return sorted(project_ids)
|
||||
|
||||
|
||||
async def _get_eu_project_ids_from_projects_service(
|
||||
institution_id: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> list[str]:
|
||||
"""Loads all organization EU project IDs from the canonical project service."""
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
page_size = 1000
|
||||
page_number = 0
|
||||
project_ids: set[str] = set()
|
||||
|
||||
while True:
|
||||
projects = await projects_service.search_eu_cordis_projects(
|
||||
institutions_search_client=InstitutionsSearchClient(),
|
||||
raw_oa_institution_id=_raw_institution_id(institution_id),
|
||||
author_id=None,
|
||||
author_ids=None,
|
||||
organization_ids=None,
|
||||
organization_names=None,
|
||||
project_types=list(EuCordisProjectType),
|
||||
keywords=None,
|
||||
topic_ids=None,
|
||||
filter_topic_ids=None,
|
||||
title=None,
|
||||
funding_start_years=None,
|
||||
funding_end_years=None,
|
||||
active_from_year=period[0],
|
||||
active_to_year=period[1],
|
||||
countries=None,
|
||||
framework_programmes=None,
|
||||
funding_schemes=None,
|
||||
statuses=None,
|
||||
page=page_number,
|
||||
size=page_size,
|
||||
sort_by="id",
|
||||
sort_direction="asc",
|
||||
fuzzy=False,
|
||||
skip_enrichment=True,
|
||||
)
|
||||
project_ids.update(project.id for project in projects.elements if project.id)
|
||||
if len(project_ids) >= projects.total or not projects.elements:
|
||||
break
|
||||
page_number += 1
|
||||
|
||||
return sorted(project_ids)
|
||||
@@ -0,0 +1,122 @@
|
||||
from inse.institutions.institutions_search_client import InstitutionsSearchClient
|
||||
from inse.projects import service as projects_service
|
||||
from inse.projects.model import EuCordisProjectType
|
||||
|
||||
from .common import (
|
||||
dashboard_period as _dashboard_period,
|
||||
normalize_institution_id as _normalize_institution_id,
|
||||
raw_institution_id as _raw_institution_id,
|
||||
)
|
||||
from .model import DashboardStatisticValue
|
||||
|
||||
|
||||
async def get_dashboard_eu_projects(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> DashboardStatisticValue:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
projects = await projects_service.search_eu_cordis_projects(
|
||||
institutions_search_client=InstitutionsSearchClient(),
|
||||
raw_oa_institution_id=_raw_institution_id(normalized_id),
|
||||
author_id=None,
|
||||
author_ids=None,
|
||||
organization_ids=None,
|
||||
organization_names=None,
|
||||
project_types=list(EuCordisProjectType),
|
||||
keywords=None,
|
||||
topic_ids=None,
|
||||
filter_topic_ids=None,
|
||||
title=None,
|
||||
funding_start_years=None,
|
||||
funding_end_years=None,
|
||||
active_from_year=period[0],
|
||||
active_to_year=period[1],
|
||||
countries=None,
|
||||
framework_programmes=None,
|
||||
funding_schemes=None,
|
||||
statuses=None,
|
||||
page=0,
|
||||
size=1,
|
||||
sort_by="id",
|
||||
sort_direction="asc",
|
||||
fuzzy=False,
|
||||
)
|
||||
return DashboardStatisticValue(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
value=projects.total,
|
||||
)
|
||||
|
||||
|
||||
async def get_dashboard_bmbf_projects(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> DashboardStatisticValue:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
projects = await projects_service.search_bund_projects_with_filters(
|
||||
institutions_search_client=InstitutionsSearchClient(),
|
||||
executing_agency=None,
|
||||
raw_oa_institution_id=_raw_institution_id(normalized_id),
|
||||
title=None,
|
||||
keywords=None,
|
||||
funding_arts=None,
|
||||
topic_ids=None,
|
||||
filter_topic_ids=None,
|
||||
funding_start_years=None,
|
||||
funding_end_years=None,
|
||||
active_from_year=period[0],
|
||||
active_to_year=period[1],
|
||||
countries=None,
|
||||
page=0,
|
||||
size=1,
|
||||
sort_by="id",
|
||||
sort_direction="asc",
|
||||
fuzzy=False,
|
||||
)
|
||||
return DashboardStatisticValue(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
value=projects.total,
|
||||
)
|
||||
|
||||
|
||||
async def get_dashboard_dfg_projects(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> DashboardStatisticValue:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
projects = await projects_service.get_dfg_projects(
|
||||
institutions_search_client=InstitutionsSearchClient(),
|
||||
raw_oa_institution_id=_raw_institution_id(normalized_id),
|
||||
author_id=None,
|
||||
author_filter_ids=None,
|
||||
institution_ids=None,
|
||||
keywords=None,
|
||||
topic_ids=None,
|
||||
filter_topic_ids=None,
|
||||
title=None,
|
||||
funding_start_years=None,
|
||||
funding_end_years=None,
|
||||
active_from_year=period[0],
|
||||
active_to_year=period[1],
|
||||
page=0,
|
||||
size=1,
|
||||
sort_by="id",
|
||||
sort_direction="asc",
|
||||
fuzzy=False,
|
||||
skip_enrichment=True,
|
||||
)
|
||||
return DashboardStatisticValue(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
value=projects.total,
|
||||
)
|
||||
@@ -0,0 +1,513 @@
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from inse.institutions.institutions_search_client import InstitutionsSearchClient
|
||||
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster, ESIndex
|
||||
|
||||
from .common import (
|
||||
DashboardPeriod,
|
||||
dashboard_period as _dashboard_period,
|
||||
normalize_institution_id as _normalize_institution_id,
|
||||
project_boundary_year_filter as _project_boundary_year_filter,
|
||||
project_overlap_filter as _project_overlap_filter,
|
||||
raw_institution_id as _raw_institution_id,
|
||||
)
|
||||
from .institute_helper import get_openalex_institution
|
||||
from .model import (
|
||||
BmbfProjectStatusStatistics,
|
||||
DfgProjectStatusStatistics,
|
||||
EuProjectStatusStatistics,
|
||||
)
|
||||
from .project_statistics_service import (
|
||||
get_dashboard_bmbf_projects,
|
||||
get_dashboard_dfg_projects,
|
||||
get_dashboard_eu_projects,
|
||||
)
|
||||
|
||||
|
||||
def _status_count(aggregations: dict[str, Any], status_name: str) -> int:
|
||||
return int(aggregations.get(status_name, {}).get("projects", {}).get("value", 0))
|
||||
|
||||
|
||||
def reconcile_status_counts(
|
||||
total: int, ongoing: int, upcoming: int, completed: int
|
||||
) -> tuple[int, int, int]:
|
||||
"""Make status buckets add up to the authoritative project-service total."""
|
||||
counts = [max(0, ongoing), max(0, upcoming), max(0, completed)]
|
||||
difference = total - sum(counts)
|
||||
if difference >= 0:
|
||||
counts[0] += difference
|
||||
return counts[0], counts[1], counts[2]
|
||||
|
||||
excess = -difference
|
||||
for index in (0, 1, 2):
|
||||
reduction = min(counts[index], excess)
|
||||
counts[index] -= reduction
|
||||
excess -= reduction
|
||||
if excess == 0:
|
||||
break
|
||||
return counts[0], counts[1], counts[2]
|
||||
|
||||
|
||||
def _status_filter_aggregations(
|
||||
start_field: str, end_field: str, today: str
|
||||
) -> dict[str, Any]:
|
||||
return {
|
||||
"ongoing": {
|
||||
"filter": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{"range": {start_field: {"lte": today}}},
|
||||
{"range": {end_field: {"gte": today}}},
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"upcoming": {"filter": {"range": {start_field: {"gt": today}}}},
|
||||
"completed": {"filter": {"range": {end_field: {"lt": today}}}},
|
||||
}
|
||||
|
||||
|
||||
async def get_dashboard_eu_project_statuses(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> EuProjectStatusStatistics:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
aliases = await _institution_aliases(normalized_id, organization_name)
|
||||
project_ids = await _eu_project_ids_for_aliases(aliases)
|
||||
total = (
|
||||
await get_dashboard_eu_projects(
|
||||
normalized_id, organization_name, from_year=from_year, to_year=to_year
|
||||
)
|
||||
).value
|
||||
if not project_ids:
|
||||
return EuProjectStatusStatistics(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
ongoing=total,
|
||||
upcoming=0,
|
||||
completed=0,
|
||||
)
|
||||
|
||||
today = datetime.now().date().isoformat()
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
filters: list[dict[str, Any]] = [{"terms": {"id": sorted(project_ids)}}]
|
||||
if period_filter := _project_boundary_year_filter(
|
||||
"startDate", "endDate", period, "iso"
|
||||
):
|
||||
filters.append(period_filter)
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
|
||||
body={
|
||||
"size": 0,
|
||||
"query": filters[0] if len(filters) == 1 else {"bool": {"filter": filters}},
|
||||
"aggs": {
|
||||
"ongoing": {
|
||||
"filter": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{"range": {"startDate": {"lte": today}}},
|
||||
{"range": {"endDate": {"gte": today}}},
|
||||
]
|
||||
}
|
||||
},
|
||||
"aggs": {"projects": {"cardinality": {"field": "id"}}},
|
||||
},
|
||||
"upcoming": {
|
||||
"filter": {"range": {"startDate": {"gt": today}}},
|
||||
"aggs": {"projects": {"cardinality": {"field": "id"}}},
|
||||
},
|
||||
"completed": {
|
||||
"filter": {"range": {"endDate": {"lt": today}}},
|
||||
"aggs": {"projects": {"cardinality": {"field": "id"}}},
|
||||
},
|
||||
},
|
||||
},
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
aggregations = response.get("aggregations", {})
|
||||
ongoing, upcoming, completed = reconcile_status_counts(
|
||||
total,
|
||||
_status_count(aggregations, "ongoing"),
|
||||
_status_count(aggregations, "upcoming"),
|
||||
_status_count(aggregations, "completed"),
|
||||
)
|
||||
return EuProjectStatusStatistics(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
ongoing=ongoing,
|
||||
upcoming=upcoming,
|
||||
completed=completed,
|
||||
)
|
||||
|
||||
|
||||
async def get_dashboard_bmbf_project_statuses(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> BmbfProjectStatusStatistics:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
aliases = await _institution_aliases(normalized_id, organization_name)
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
filters = [_alias_match_query("Zuwendungsempfänger", aliases)]
|
||||
if period_filter := _project_boundary_year_filter(
|
||||
"funding_start", "funding_end", period, "de"
|
||||
):
|
||||
filters.append(period_filter)
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.PROJECTS_BUND_V1,
|
||||
body={
|
||||
"size": 0,
|
||||
"query": filters[0] if len(filters) == 1 else {"bool": {"filter": filters}},
|
||||
"aggs": _status_filter_aggregations(
|
||||
"funding_start", "funding_end", datetime.now().strftime("%d.%m.%Y")
|
||||
),
|
||||
},
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
aggregations = response.get("aggregations", {})
|
||||
total = (
|
||||
await get_dashboard_bmbf_projects(
|
||||
normalized_id, organization_name, from_year=from_year, to_year=to_year
|
||||
)
|
||||
).value
|
||||
ongoing, upcoming, completed = reconcile_status_counts(
|
||||
total,
|
||||
int(aggregations.get("ongoing", {}).get("doc_count", 0)),
|
||||
int(aggregations.get("upcoming", {}).get("doc_count", 0)),
|
||||
int(aggregations.get("completed", {}).get("doc_count", 0)),
|
||||
)
|
||||
return BmbfProjectStatusStatistics(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
ongoing=ongoing,
|
||||
upcoming=upcoming,
|
||||
completed=completed,
|
||||
)
|
||||
|
||||
|
||||
async def get_dashboard_dfg_project_statuses(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> DfgProjectStatusStatistics:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
project_ids = await _get_dfg_project_ids_for_institution(normalized_id)
|
||||
total = (
|
||||
await get_dashboard_dfg_projects(
|
||||
normalized_id, organization_name, from_year=from_year, to_year=to_year
|
||||
)
|
||||
).value
|
||||
if not project_ids:
|
||||
return DfgProjectStatusStatistics(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
ongoing=total,
|
||||
upcoming=0,
|
||||
completed=0,
|
||||
)
|
||||
|
||||
filters: list[dict[str, Any]] = [
|
||||
{
|
||||
"terms": {
|
||||
"projects.project_id": [int(project_id) for project_id in project_ids]
|
||||
}
|
||||
}
|
||||
]
|
||||
if period_filter := _project_boundary_year_filter(
|
||||
"projects.funding_start", "projects.funding_end", period, "year"
|
||||
):
|
||||
filters.append(period_filter)
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.DFG_INSTITUTES_V2,
|
||||
body={
|
||||
"size": 0,
|
||||
"aggs": {
|
||||
"projects_nested": {
|
||||
"nested": {"path": "projects"},
|
||||
"aggs": {
|
||||
"selected_projects": {
|
||||
"filter": filters[0]
|
||||
if len(filters) == 1
|
||||
else {"bool": {"filter": filters}},
|
||||
"aggs": {
|
||||
"ongoing": {
|
||||
"filter": {
|
||||
"match_phrase": {
|
||||
"projects.status_de": "laufend"
|
||||
}
|
||||
},
|
||||
"aggs": {
|
||||
"projects": {
|
||||
"cardinality": {
|
||||
"field": "projects.project_id"
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
"completed": {
|
||||
"filter": {
|
||||
"match_phrase": {
|
||||
"projects.status_de": "abgeschlossen"
|
||||
}
|
||||
},
|
||||
"aggs": {
|
||||
"projects": {
|
||||
"cardinality": {
|
||||
"field": "projects.project_id"
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
},
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
aggregations = (
|
||||
response.get("aggregations", {})
|
||||
.get("projects_nested", {})
|
||||
.get("selected_projects", {})
|
||||
)
|
||||
ongoing, upcoming, completed = reconcile_status_counts(
|
||||
total,
|
||||
_status_count(aggregations, "ongoing"),
|
||||
0,
|
||||
_status_count(aggregations, "completed"),
|
||||
)
|
||||
return DfgProjectStatusStatistics(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
ongoing=ongoing,
|
||||
upcoming=upcoming,
|
||||
completed=completed,
|
||||
)
|
||||
|
||||
|
||||
async def _get_dfg_project_ids_for_institution(
|
||||
institution_id: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> list[str]:
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
institution = await get_openalex_institution(institution_id)
|
||||
institution_names = _openalex_institution_names(institution)
|
||||
|
||||
institutes_response = await elasticsearch.search(
|
||||
index=ESIndex.DFG_INSTITUTES_V2,
|
||||
body={
|
||||
"size": 0,
|
||||
"query": _dfg_institute_name_query(institution_names),
|
||||
"aggs": {
|
||||
"institute_ids": {"terms": {"field": "institute_id", "size": 1000}}
|
||||
},
|
||||
},
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
institute_ids = [
|
||||
bucket["key"]
|
||||
for bucket in (
|
||||
institutes_response.get("aggregations", {})
|
||||
.get("institute_ids", {})
|
||||
.get("buckets", [])
|
||||
)
|
||||
if bucket.get("key") is not None
|
||||
]
|
||||
if not institute_ids:
|
||||
return []
|
||||
|
||||
projects_response = await elasticsearch.search(
|
||||
index=ESIndex.DFG_INSTITUTES_V2,
|
||||
body={
|
||||
"size": 0,
|
||||
"query": {"terms": {"institute_id": institute_ids}},
|
||||
"aggs": {
|
||||
"projects_nested": {
|
||||
"nested": {"path": "projects"},
|
||||
"aggs": {
|
||||
"project_ids": {
|
||||
"filter": {
|
||||
"terms": {"projects.institute_ref_id": institute_ids}
|
||||
},
|
||||
"aggs": {
|
||||
"values": {
|
||||
"terms": {
|
||||
"field": "projects.project_id",
|
||||
"size": 10000,
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
},
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
project_ids = [
|
||||
str(bucket["key"])
|
||||
for bucket in (
|
||||
projects_response.get("aggregations", {})
|
||||
.get("projects_nested", {})
|
||||
.get("project_ids", {})
|
||||
.get("values", {})
|
||||
.get("buckets", [])
|
||||
)
|
||||
if bucket.get("key") is not None
|
||||
]
|
||||
return await _filter_dfg_project_ids_by_period(project_ids, period)
|
||||
|
||||
|
||||
async def _eu_project_ids_for_aliases(aliases: list[str]) -> set[str]:
|
||||
project_ids: set[str] = set()
|
||||
async for hit in elasticsearch.scan(
|
||||
index=str(ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD),
|
||||
query=_eu_organization_query(aliases),
|
||||
source=["projectID"],
|
||||
page_size=1000,
|
||||
cluster=ESCluster.INSE,
|
||||
):
|
||||
project_id = hit.get("_source", {}).get("projectID")
|
||||
if project_id is not None:
|
||||
project_ids.add(str(project_id))
|
||||
return project_ids
|
||||
|
||||
|
||||
async def _filter_dfg_project_ids_by_period(
|
||||
project_ids: list[str],
|
||||
period: DashboardPeriod,
|
||||
) -> list[str]:
|
||||
period_filter = _project_overlap_filter(
|
||||
"funding_start",
|
||||
"funding_end",
|
||||
period,
|
||||
missing_end_is_ongoing=True,
|
||||
)
|
||||
if not project_ids or not period_filter:
|
||||
return project_ids
|
||||
|
||||
numeric_project_ids = [
|
||||
int(project_id) for project_id in project_ids if str(project_id).isdigit()
|
||||
]
|
||||
if not numeric_project_ids:
|
||||
return []
|
||||
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.DFG_PROJECTS,
|
||||
body={
|
||||
"size": 0,
|
||||
"query": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{"terms": {"id": numeric_project_ids}},
|
||||
period_filter,
|
||||
]
|
||||
}
|
||||
},
|
||||
"aggs": {
|
||||
"project_ids": {
|
||||
"terms": {
|
||||
"field": "id",
|
||||
"size": len(numeric_project_ids),
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
return [
|
||||
str(bucket["key"])
|
||||
for bucket in (
|
||||
response.get("aggregations", {}).get("project_ids", {}).get("buckets", [])
|
||||
)
|
||||
if bucket.get("key") is not None
|
||||
]
|
||||
|
||||
|
||||
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 _openalex_institution_names(institution: Any) -> list[str]:
|
||||
return sorted(
|
||||
{
|
||||
name.strip()
|
||||
for name in [
|
||||
institution.display_name,
|
||||
*(institution.display_name_alternatives or []),
|
||||
*(institution.display_name_acronyms or []),
|
||||
]
|
||||
if name and name.strip()
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _dfg_institute_name_query(institution_names: list[str]) -> dict[str, Any]:
|
||||
return {
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"terms": {
|
||||
"institute_name_de.keyword": institution_names,
|
||||
}
|
||||
},
|
||||
{
|
||||
"terms": {
|
||||
"institute_name_en.keyword": institution_names,
|
||||
}
|
||||
},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
@@ -10,30 +10,48 @@ from inse.tags import Tags
|
||||
|
||||
from .model import (
|
||||
BmbfProjectStatusStatistics,
|
||||
DashboardStatisticValue,
|
||||
BundProjectTopics,
|
||||
DashboardStatistics,
|
||||
DashboardStatisticValue,
|
||||
DfgProjectStatusStatistics,
|
||||
DfgProjectTopics,
|
||||
EuProjectTopics,
|
||||
EuProjectStatusStatistics,
|
||||
TopAuthorStatistics,
|
||||
TopAuthorAnalysis,
|
||||
TopicHeatmap,
|
||||
TopicWordCloud,
|
||||
)
|
||||
from .service import (
|
||||
get_dashboard_bmbf_project_statuses,
|
||||
get_dashboard_bmbf_projects,
|
||||
get_dashboard_dfg_projects,
|
||||
get_dashboard_dfg_topics,
|
||||
get_dashboard_eu_projects,
|
||||
get_dashboard_eu_project_statuses,
|
||||
get_dashboard_organization,
|
||||
get_dashboard_patents,
|
||||
get_dashboard_persons,
|
||||
get_dashboard_publications,
|
||||
get_dashboard_statistics,
|
||||
get_top_authors,
|
||||
get_topic_heatmap,
|
||||
get_topic_word_cloud,
|
||||
)
|
||||
from .project_statistics_service import (
|
||||
get_dashboard_bmbf_projects,
|
||||
get_dashboard_dfg_projects,
|
||||
get_dashboard_eu_projects,
|
||||
)
|
||||
from .bund_topics_service import get_dashboard_bund_topics
|
||||
from .dfg_topics_service import get_dashboard_dfg_topics
|
||||
from .eu_topics_service import get_dashboard_eu_topics
|
||||
from .project_status_service import (
|
||||
get_dashboard_bmbf_project_statuses,
|
||||
get_dashboard_dfg_project_statuses,
|
||||
get_dashboard_eu_project_statuses,
|
||||
)
|
||||
from .top_authors_service import (
|
||||
get_top_authors,
|
||||
get_top_eu_project_authors,
|
||||
get_top_news_authors,
|
||||
get_top_patent_authors,
|
||||
get_top_project_authors,
|
||||
get_top_work_authors,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/api/dashboard", tags=[Tags.DASHBOARD])
|
||||
|
||||
@@ -60,6 +78,8 @@ async def dashboard_statistics(
|
||||
response_model=DashboardStatisticValue,
|
||||
)
|
||||
async def dashboard_publications(
|
||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
to_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> DashboardStatisticValue:
|
||||
@@ -67,6 +87,8 @@ async def dashboard_publications(
|
||||
return await get_dashboard_publications(
|
||||
organization.openalex_institution_id,
|
||||
organization.name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
|
||||
|
||||
@@ -76,6 +98,8 @@ async def dashboard_publications(
|
||||
response_model=DashboardStatisticValue,
|
||||
)
|
||||
async def dashboard_persons(
|
||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
to_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> DashboardStatisticValue:
|
||||
@@ -83,6 +107,8 @@ async def dashboard_persons(
|
||||
return await get_dashboard_persons(
|
||||
organization.openalex_institution_id,
|
||||
organization.name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
|
||||
|
||||
@@ -92,6 +118,8 @@ async def dashboard_persons(
|
||||
response_model=DashboardStatisticValue,
|
||||
)
|
||||
async def dashboard_patents(
|
||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
to_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> DashboardStatisticValue:
|
||||
@@ -99,6 +127,8 @@ async def dashboard_patents(
|
||||
return await get_dashboard_patents(
|
||||
organization.openalex_institution_id,
|
||||
organization.name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
|
||||
|
||||
@@ -108,6 +138,8 @@ async def dashboard_patents(
|
||||
response_model=DashboardStatisticValue,
|
||||
)
|
||||
async def dashboard_eu_projects(
|
||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
to_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> DashboardStatisticValue:
|
||||
@@ -115,6 +147,8 @@ async def dashboard_eu_projects(
|
||||
return await get_dashboard_eu_projects(
|
||||
organization.openalex_institution_id,
|
||||
organization.name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
|
||||
|
||||
@@ -124,6 +158,8 @@ async def dashboard_eu_projects(
|
||||
response_model=EuProjectStatusStatistics,
|
||||
)
|
||||
async def dashboard_eu_project_statuses(
|
||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
to_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> EuProjectStatusStatistics:
|
||||
@@ -131,6 +167,8 @@ async def dashboard_eu_project_statuses(
|
||||
return await get_dashboard_eu_project_statuses(
|
||||
organization.openalex_institution_id,
|
||||
organization.name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
|
||||
|
||||
@@ -140,6 +178,8 @@ async def dashboard_eu_project_statuses(
|
||||
response_model=DashboardStatisticValue,
|
||||
)
|
||||
async def dashboard_bmbf_projects(
|
||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
to_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> DashboardStatisticValue:
|
||||
@@ -147,6 +187,8 @@ async def dashboard_bmbf_projects(
|
||||
return await get_dashboard_bmbf_projects(
|
||||
organization.openalex_institution_id,
|
||||
organization.name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
|
||||
|
||||
@@ -156,6 +198,8 @@ async def dashboard_bmbf_projects(
|
||||
response_model=BmbfProjectStatusStatistics,
|
||||
)
|
||||
async def dashboard_bmbf_project_statuses(
|
||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
to_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> BmbfProjectStatusStatistics:
|
||||
@@ -163,6 +207,8 @@ async def dashboard_bmbf_project_statuses(
|
||||
return await get_dashboard_bmbf_project_statuses(
|
||||
organization.openalex_institution_id,
|
||||
organization.name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
|
||||
|
||||
@@ -172,6 +218,8 @@ async def dashboard_bmbf_project_statuses(
|
||||
response_model=DashboardStatisticValue,
|
||||
)
|
||||
async def dashboard_dfg_projects(
|
||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
to_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> DashboardStatisticValue:
|
||||
@@ -179,6 +227,28 @@ async def dashboard_dfg_projects(
|
||||
return await get_dashboard_dfg_projects(
|
||||
organization.openalex_institution_id,
|
||||
organization.name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/projects/dfg/status",
|
||||
operation_id="getDashboardDfgProjectStatuses",
|
||||
response_model=DfgProjectStatusStatistics,
|
||||
)
|
||||
async def dashboard_dfg_project_statuses(
|
||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
to_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> DfgProjectStatusStatistics:
|
||||
organization = get_dashboard_organization(session, access_token)
|
||||
return await get_dashboard_dfg_project_statuses(
|
||||
organization.openalex_institution_id,
|
||||
organization.name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
|
||||
|
||||
@@ -188,6 +258,8 @@ async def dashboard_dfg_projects(
|
||||
response_model=DfgProjectTopics,
|
||||
)
|
||||
async def dashboard_dfg_project_topics(
|
||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
to_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> DfgProjectTopics:
|
||||
@@ -195,6 +267,48 @@ async def dashboard_dfg_project_topics(
|
||||
return await get_dashboard_dfg_topics(
|
||||
organization.openalex_institution_id,
|
||||
organization.name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/projects/eu/topics",
|
||||
operation_id="getDashboardEuProjectTopics",
|
||||
response_model=EuProjectTopics,
|
||||
)
|
||||
async def dashboard_eu_project_topics(
|
||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
to_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> EuProjectTopics:
|
||||
organization = get_dashboard_organization(session, access_token)
|
||||
return await get_dashboard_eu_topics(
|
||||
organization.openalex_institution_id,
|
||||
organization.name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/projects/bund/topics",
|
||||
operation_id="getDashboardBundProjectTopics",
|
||||
response_model=BundProjectTopics,
|
||||
)
|
||||
async def dashboard_bund_project_topics(
|
||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
to_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> BundProjectTopics:
|
||||
organization = get_dashboard_organization(session, access_token)
|
||||
return await get_dashboard_bund_topics(
|
||||
organization.openalex_institution_id,
|
||||
organization.name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
|
||||
|
||||
@@ -208,6 +322,8 @@ async def dashboard_top_authors(
|
||||
default="all_time",
|
||||
pattern="^(all_time|last_5_years)$",
|
||||
),
|
||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
to_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> TopAuthorStatistics:
|
||||
@@ -216,6 +332,96 @@ async def dashboard_top_authors(
|
||||
organization.openalex_institution_id,
|
||||
organization.name,
|
||||
works_period=works_period,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/top-authors/works",
|
||||
operation_id="getDashboardTopWorkAuthors",
|
||||
response_model=TopAuthorAnalysis,
|
||||
)
|
||||
async def dashboard_top_work_authors(
|
||||
works_period: Literal["all_time", "last_5_years"] = Query(
|
||||
default="all_time", pattern="^(all_time|last_5_years)$"
|
||||
),
|
||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
to_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> TopAuthorAnalysis:
|
||||
organization = get_dashboard_organization(session, access_token)
|
||||
return await get_top_work_authors(
|
||||
organization.openalex_institution_id, works_period, from_year, to_year
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/top-authors/projects",
|
||||
operation_id="getDashboardTopProjectAuthors",
|
||||
response_model=TopAuthorAnalysis,
|
||||
)
|
||||
async def dashboard_top_project_authors(
|
||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
to_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> TopAuthorAnalysis:
|
||||
organization = get_dashboard_organization(session, access_token)
|
||||
return await get_top_project_authors(
|
||||
organization.openalex_institution_id, organization.name, from_year, to_year
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/top-authors/eu-projects",
|
||||
operation_id="getDashboardTopEuProjectAuthors",
|
||||
response_model=TopAuthorAnalysis,
|
||||
)
|
||||
async def dashboard_top_eu_project_authors(
|
||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
to_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> TopAuthorAnalysis:
|
||||
organization = get_dashboard_organization(session, access_token)
|
||||
return await get_top_eu_project_authors(
|
||||
organization.openalex_institution_id, from_year, to_year
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/top-authors/patents",
|
||||
operation_id="getDashboardTopPatentAuthors",
|
||||
response_model=TopAuthorAnalysis,
|
||||
)
|
||||
async def dashboard_top_patent_authors(
|
||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
to_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> TopAuthorAnalysis:
|
||||
organization = get_dashboard_organization(session, access_token)
|
||||
return await get_top_patent_authors(
|
||||
organization.openalex_institution_id, from_year, to_year
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/top-authors/news",
|
||||
operation_id="getDashboardTopNewsAuthors",
|
||||
response_model=TopAuthorAnalysis,
|
||||
)
|
||||
async def dashboard_top_news_authors(
|
||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
to_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> TopAuthorAnalysis:
|
||||
organization = get_dashboard_organization(session, access_token)
|
||||
return await get_top_news_authors(
|
||||
organization.openalex_institution_id, from_year, to_year
|
||||
)
|
||||
|
||||
|
||||
|
||||
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
@@ -107,6 +107,30 @@ def create_db_and_tables():
|
||||
)
|
||||
)
|
||||
|
||||
# Preserve the former single institution as the first manually selected
|
||||
# institution.
|
||||
# The legacy column remains synchronized for portal sections that have not yet
|
||||
# been migrated to organization-wide institution lists.
|
||||
with engine.begin() as connection:
|
||||
connection.execute(
|
||||
text(
|
||||
"""
|
||||
INSERT INTO organization_institution (
|
||||
organization_id, openalex_institution_id, position
|
||||
)
|
||||
SELECT id, openalex_institution_id, 0
|
||||
FROM organization
|
||||
WHERE openalex_institution_id IS NOT NULL
|
||||
AND TRIM(openalex_institution_id) != ''
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM organization_institution oi
|
||||
WHERE oi.organization_id = organization.id
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def get_session():
|
||||
"""Yields a database session for use in FastAPI endpoints.
|
||||
|
||||
@@ -10,22 +10,18 @@ class NotFoundException(Exception):
|
||||
|
||||
class ElasticsearchException(Exception):
|
||||
"""Base exception for all Elasticsearch integrations."""
|
||||
pass
|
||||
|
||||
|
||||
class ElasticsearchNotFoundException(NotFoundException, ElasticsearchException):
|
||||
"""Raised when an Elasticsearch document or index is not found."""
|
||||
pass
|
||||
|
||||
|
||||
class ElasticsearchConnectionException(ElasticsearchException):
|
||||
"""Raised when connecting to Elasticsearch fails."""
|
||||
pass
|
||||
|
||||
|
||||
class MissingApiKeyError(Exception):
|
||||
"""Raised when a required API key is missing."""
|
||||
pass
|
||||
|
||||
|
||||
class UpstreamAPIException(Exception):
|
||||
@@ -38,4 +34,3 @@ class UpstreamAPIException(Exception):
|
||||
|
||||
class BadRequestException(Exception):
|
||||
"""Raised when request parameters are invalid or validation fails."""
|
||||
pass
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
Funders domain package.
|
||||
"""
|
||||
|
||||
@@ -1,16 +1,14 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
HTTP client for funded-publication searches in the OpenAlex works index.
|
||||
"""
|
||||
from typing import Any
|
||||
|
||||
from .. import config
|
||||
from inse.exceptions import MissingApiKeyError
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster
|
||||
|
||||
|
||||
from inse.exceptions import MissingApiKeyError
|
||||
from .. import config
|
||||
|
||||
|
||||
class FundedPublicationsSearchClient:
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
Business logic for author funding based on publication works.
|
||||
"""
|
||||
@@ -7,10 +6,14 @@ import logging
|
||||
from typing import Any
|
||||
|
||||
from pydantic import ValidationError
|
||||
|
||||
from inse.exceptions import (
|
||||
UpstreamAPIException,
|
||||
)
|
||||
|
||||
from ..persons import logic as person_logic
|
||||
from . import model
|
||||
from .elastic_search_client import FundedPublicationsSearchClient
|
||||
from inse.exceptions import MissingApiKeyError, ElasticsearchException, UpstreamAPIException
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
from typing import Any
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic import Field
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class PublicationsByAuthorResponse(BaseModel):
|
||||
|
||||
@@ -1,16 +1,12 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
REST API for author publications and funding.
|
||||
"""
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter
|
||||
from fastapi import Query
|
||||
|
||||
from . import logic
|
||||
from . import model
|
||||
from fastapi import APIRouter, Query
|
||||
|
||||
from . import logic, model
|
||||
|
||||
router = APIRouter(prefix="/api/inse-service/authors", tags=["Funding"])
|
||||
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import pytest
|
||||
from unittest.mock import AsyncMock, patch
|
||||
from inse.exceptions import MissingApiKeyError
|
||||
|
||||
import pytest
|
||||
|
||||
from inse.exceptions import MissingApiKeyError
|
||||
from inse.funders import logic
|
||||
from inse.funders.elastic_search_client import FundedPublicationsSearchClient
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user